Start with basic authentication

This commit is contained in:
ricola 2025-04-06 17:04:31 -06:00
commit 5e8cda6fc0
6 changed files with 89 additions and 0 deletions

2
.bundle/config Normal file
View file

@ -0,0 +1,2 @@
---
BUNDLE_PATH: "gems"

4
Gemfile Normal file
View file

@ -0,0 +1,4 @@
source "http://rubygems.org"
gem "sinatra"
gem "bcrypt"

5
views/home.erb Normal file
View file

@ -0,0 +1,5 @@
<h1>Home</h1>
<p>Hello, <%= current_user.email %>.</p>
<form action="/logout" method="POST">
<input type="submit" value="Log out" />
</form>

10
views/layout.erb Normal file
View file

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
</head>
<body>
<%= yield %>
</body>
</html>

9
views/login.erb Normal file
View file

@ -0,0 +1,9 @@
<h1>Log in</h1>
<% if @error %>
<p class="error"><%= @error %></p>
<% end %>
<form action="/login" method="POST">
<input name="email" placeholder="Email" />
<input name="password" type="password" placeholder="Password" />
<input type="submit" value="Log in" />
</form>

59
vote.rb Normal file
View 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