# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController

  # render new.rhtml
  def new
    if params[:admin_required]
      redirect_back_or_default root_url if logged_in? && current_user.is_admin
    elsif logged_in?
      if logged_in_as_current_customer?
        redirect_back_or_default root_url
      else
        redirect_to secure_subdomain(:controller => 'customers', :action => 'choose', :return_to => params[:return_to])
      end
    end
  end

  def create
    logout_keeping_session!
    begin
      user = User.authenticate(params[:email], params[:password])
    rescue User::UserSuspended
      flash[:error] = $!; return
    end

    if user
      # Protects against session fixation attacks, causes request forgery
      # protection if user resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset_session
      self.current_user = user
      new_cookie_flag = (params[:remember_me] == "1")
      handle_remember_cookie! new_cookie_flag

      if user.pending?
        flash[:error] = "Your email address is not yet validated. Please click on the link in the message we have sent you."
      else
        flash[:notice] = "Logged in successfully"
      end

      redirect_to :controller => "customers", :action => "choose", :return_to => params[:return_to]
    else
      note_failed_signin
      @email       = params[:email]
      @remember_me = params[:remember_me]
      render :action => 'new'
    end
  end

  def destroy
    logout_killing_session!
    flash[:notice] = "You have been logged out."
    redirect_back_or_default(current_customer ? '/login' : '/')
  end

protected
  # Track failed login attempts
  def note_failed_signin
    flash[:error] = "Couldn't log you in as '#{params[:email]}'"
    logger.warn "Failed login for '#{params[:email]}' from #{request.remote_ip} at #{Time.now.utc}"
  end
end
