Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class SecurityController < ApplicationController
  def login
    if request.post?
      login_if_valid { Account.authenticate_with_password(params[:email], params[:password]) }
    elsif !params[:key].nil?
      login_if_valid { Account.authenticate_with_key(params[:key]) }
    end
  end
  
  def logout
    session[:account] = nil
    raise "We should NOT be logged in after logging out!" if logged_in?
    redirect_to home_url
  end
  
  private
  
  def login_if_valid
    raise "Must pass a block to login_if_valid!" unless block_given?
    begin
      account = yield
    rescue AuthenticationError => e
      logger.debug "Authentication Error Occurred!"
      session[:account] = nil
      raise "We should NOT be logged in after failing to log in!" if logged_in?
      redirect_to login_url and return false
    end
    session[:account] = account.id # this means we're logged in.
    raise "We should be logged in after logging in!" unless logged_in?
    redirect_to my_home_url
  end
end