Buildwise::App.controllers :sessions do
  
  get :login, :map => "/login" do
    @title = "Sign In"
    render "sessions/login.erb"
  end
 
  
  get :logout, :map => '/logout' do    
    if current_user
      current_user.forget
    end
    session[:user_id] = nil
    session[:sort_direction] = nil
    session[:sort_column]  = nil

    cookies.delete(:user_id)
    cookies.delete(:remember_token)
    
    Buildwise::App.cache.clear
    redirect '/'
  end

  post :authenticate, :map => "/sessions", :csrf_protection => false  do
    if User.retrieve_all.count == 0
      if defined?(SERVER_DIGEST)      
        User.create!(:username => "admin", :password => "buildwise", :server_digest => SERVER_DIGEST)
      else
        User.create!(:username => "admin", :password => "buildwise")
      end
    end    
    
    if defined?(SERVER_DIGEST)      
      @user = User.where(:server_digest => SERVER_DIGEST).where("username = ? OR email = ?", params[:login], params[:login]).first
    else    
      @user = User.where("username = ? OR email = ?", params[:login], params[:login]).first
    end
  
    if @user && @user.authenticate(params[:password])
    
      session[:user_id] = @user.id      
      Buildwise::App.cache.clear    
      
      if (params[:remember_me] && params[:remember_me].to_s == "true")
        remember(@user)
      end

      if session[:original_request] 
        redirect_to_original_request
      else
        redirect "/projects"
      end      
    else
      flash[:alert] = 'You could not be signed in. Did you enter the correct username and password?'
      redirect '/login'
    end

  end



end