Module: Sinatra::Doorman::ForgotPassword

Defined in:
lib/doorman/base.rb

Overview

Forgot Password Feature

Class Method Summary collapse

Class Method Details

.registered(app) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/doorman/base.rb', line 186

def self.registered(app)
  Warden::Manager.after_authentication do |user, auth, opts|
    # If the user requested a new password,
    # but then remembers and logs in,
    # then invalidate password reset token
    if auth.winning_strategy.is_a?(PasswordStrategy)
      user.remembered_password!
    end
  end

  app.get '/forgot/?' do
    redirect '/home' if authenticated?
    haml :forgot
  end

  app.post '/forgot' do
    redirect '/home' if authenticated?
    redirect '/' unless params['user']

    user = User.(params['user']['login'])

    if user.nil?
      notify :error, :forgot_no_user
      redirect back
    end

    user.forgot_password!
    Pony.mail(
      :to => user.email, 
      :from => "no-reply@#{env['SERVER_NAME']}", 
      :body => token_link('reset', user))
    notify :success, :forgot_success
    redirect '/login'
  end

  app.get '/reset/:token/?' do
    redirect '/home' if authenticated?

    if params[:token].nil? || params[:token].empty?
      notify :error, :reset_no_token
      redirect '/'
    end

    user = User.first(:confirm_token => params[:token])
    if user.nil?
      notify :error, :reset_no_user
      redirect '/login'
    end

    haml :reset, :locals => { :confirm_token => user.confirm_token }
  end

  app.post '/reset' do
    redirect '/home' if authenticated?
    redirect '/' unless params['user']
    
    user = User.first(:confirm_token => params[:user][:confirm_token])
    if user.nil?
      notify :error, :reset_no_user
      redirect '/login'
    end

    success = user.reset_password!(
      params['user']['password'], 
      params['user']['password_confirmation'])

    unless success
      notify :error, :reset_unmatched_passwords
      redirect back
    end

    user.confirm_email!
    env['warden'].set_user(user)
    notify :success, :reset_success
    redirect '/home'
  end
end