-
-
Save alexch/159216 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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