Skip to content

Instantly share code, notes, and snippets.

@alexch
Forked from anonymous/gist:159215
Created July 31, 2009 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexch/159216 to your computer and use it in GitHub Desktop.
Save alexch/159216 to your computer and use it in GitHub Desktop.
# A group of actions and related helper methods dealing with login/logout.
# These are loaded from my main Sinatra app via "register Actions::Login".
# I put this file in a subdirectory called "actions".
module Actions
module Login
module Helpers
def logged_in?
if session[:user_id]
true
else
false
end
end
def current_user
session[:user_id] ? User.find(session[:user_id]) : nil
end
def require_login!
redirect '/login' unless logged_in?
end
def logout
session[:user_id] = nil
end
end
def self.registered(app)
app.helpers Helpers
app.get '/login' do
Views::Login.new.to_s
end
app.post '/login' do
user = ::User.authenticate(params["name"], params["password"])
if user
session[:user_id] = user.id
flash("Login successful.")
redirect '/'
else
session[:user_id] = nil
flash("Login failed - Please try again.")
redirect '/login'
end
end
app.get '/logout' do
logout
flash("Logout successful.")
redirect '/'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment