Start with basic authentication
This commit is contained in:
commit
5e8cda6fc0
6 changed files with 89 additions and 0 deletions
59
vote.rb
Normal file
59
vote.rb
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
require 'sinatra'
|
||||
require 'bcrypt'
|
||||
|
||||
def hash_password(password)
|
||||
BCrypt::Password.create(password).to_s
|
||||
end
|
||||
|
||||
def verify_password(password, hash)
|
||||
BCrypt::Password.new(hash) == password
|
||||
end
|
||||
|
||||
User = Struct.new(:id, :email, :password_hash)
|
||||
USERS = [
|
||||
User.new(1, 'P1', hash_password('P1')),
|
||||
User.new(2, 'P2', hash_password('P2')),
|
||||
User.new(3, 'P3', hash_password('P3')),
|
||||
]
|
||||
|
||||
enable :sessions
|
||||
|
||||
get '/' do
|
||||
if current_user
|
||||
erb :home
|
||||
else
|
||||
redirect '/login'
|
||||
end
|
||||
end
|
||||
|
||||
get '/login' do
|
||||
erb :login
|
||||
end
|
||||
|
||||
post '/login' do
|
||||
puts params
|
||||
user = USERS.find { |u| u.email == params[:email] }
|
||||
if user && verify_password(params[:password], user.password_hash)
|
||||
session.clear
|
||||
session[:user_id] = user.id
|
||||
redirect '/'
|
||||
else
|
||||
@error = 'Username or password was incorrect'
|
||||
erb :login
|
||||
end
|
||||
end
|
||||
|
||||
post '/logout' do
|
||||
session.clear
|
||||
redirect '/login'
|
||||
end
|
||||
|
||||
helpers do
|
||||
def current_user
|
||||
if session[:user_id]
|
||||
USERS.find { |u| u.id == session[:user_id] }
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue