Concepts of modular tonton web application that share authentication
This commit is contained in:
parent
7fe8986bdb
commit
eb759a8454
7 changed files with 192 additions and 75 deletions
109
lib/tonton_web/app.rb
Normal file
109
lib/tonton_web/app.rb
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
require_relative 'auth'
|
||||
require "warden"
|
||||
require 'sinatra/flash'
|
||||
|
||||
Warden::Manager.serialize_from_session do |id|
|
||||
TonTonWeb::App.find_user id: id
|
||||
end
|
||||
|
||||
Warden::Manager.serialize_into_session do |user|
|
||||
user.id
|
||||
end
|
||||
|
||||
Warden::Manager.before_failure do |env,opts|
|
||||
env['REQUEST_METHOD'] = "POST"
|
||||
|
||||
env['rack.session']['warden.options'] = opts
|
||||
end
|
||||
|
||||
Warden::Strategies.add(:password) do
|
||||
def valid?
|
||||
params['user'] && params['user']['username'] && params['user']['password']
|
||||
end
|
||||
|
||||
def authenticate!
|
||||
user_params = params['user']
|
||||
|
||||
user = TonTonWeb::App.authenticate user_params['username'], user_params['password']
|
||||
|
||||
if not user
|
||||
throw(:warden)
|
||||
else
|
||||
success!(user)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class TonTonWeb::App < Sinatra::Base
|
||||
@db = SQLite3::Database.new(Dir.getwd + '/database.sqlite')
|
||||
|
||||
register Sinatra::Flash
|
||||
register TonTonWeb::Auth
|
||||
|
||||
use Warden::Manager do |manager|
|
||||
manager.default_strategies :password
|
||||
|
||||
manager.failure_app = self
|
||||
|
||||
manager.scope_defaults :default, strategies: [:password], action: 'unauthenticated'
|
||||
end
|
||||
|
||||
helpers do
|
||||
def check_authentication
|
||||
if not env['warden'].authenticated?
|
||||
flash[:error] = 'You must log in to access this page.'
|
||||
|
||||
redirect '/login'
|
||||
end
|
||||
end
|
||||
|
||||
def current_user
|
||||
env['warden'].user
|
||||
end
|
||||
end
|
||||
|
||||
set :host_authorization, { permitted_hosts: ['localhost', 'mytonton.com.br'] }
|
||||
|
||||
get '/' do
|
||||
redirect "/readme.md"
|
||||
end
|
||||
|
||||
get '/status' do
|
||||
puts env['warden']
|
||||
check_authentication
|
||||
"Hello"
|
||||
end
|
||||
|
||||
post '/unauthenticated' do
|
||||
session['warden.return_to'] = env['warden.options'][:attempted_path]
|
||||
|
||||
flash[:error] = 'You must log in to access this page.'
|
||||
|
||||
redirect '/login'
|
||||
end
|
||||
|
||||
get '/login' do
|
||||
@error = flash[:error]
|
||||
|
||||
erb :login
|
||||
end
|
||||
|
||||
post '/login' do
|
||||
env['warden'].authenticate!
|
||||
|
||||
if env['warden'].authenticated?
|
||||
redirect_path = session.delete('warden.return_to') || '/'
|
||||
|
||||
redirect redirect_path
|
||||
else
|
||||
redirect '/login'
|
||||
end
|
||||
end
|
||||
|
||||
get '/logout' do
|
||||
env['warden'].logout
|
||||
|
||||
redirect '/'
|
||||
end
|
||||
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue