Skip to content

Instantly share code, notes, and snippets.

@Inversion-des
Created December 17, 2024 16:22
Show Gist options
  • Save Inversion-des/94d3980aec23f3c045dda60660a4711a to your computer and use it in GitHub Desktop.
Save Inversion-des/94d3980aec23f3c045dda60660a4711a to your computer and use it in GitHub Desktop.
Store hashed passwords in DB
require 'sinatra'
require 'sqlite3'
require 'bcrypt'
# initialize SQLite database
DB = SQLite3::Database.new 'users.db'
DB.results_as_hash = true
# create users table if needed
DB.execute <<-SQL
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
SQL
get '/' do
"""
<h1>Welcome to the secret App</h1>
<ul>
<li><a href='/register'>Register</a></li>
<li><a href='/login'>Login</a></li>
</ul>
"""
end
get '/register' do
"""
<form method='POST' action='/register'>
Username: <input type='text' name='username' required autofocus><br>
Password: <input type='password' name='password' required><br>
<input type='submit' value='Register'>
</form>
"""
end
post '/register' do
username = params[:username]
password = params[:password]
begin
hashed_password = BCrypt::Password.create(password)
DB.execute("INSERT INTO users (username, password) VALUES (?, ?)", [username, hashed_password])
"Registration successful! <a href='/login'>Login here</a>"
rescue SQLite3::ConstraintException
"User already exists. <a href='/register'>Try again</a>"
end
end
get '/login' do
"""
<form method='POST' action='/login'>
Username: <input type='text' name='username' required autofocus><br>
Password: <input type='password' name='password' required><br>
<input type='submit' value='Login'>
</form>
"""
end
post '/login' do
username = params[:username]
password = params[:password]
user = DB.execute("SELECT * FROM users WHERE username = ?", [username]).first
if user
if BCrypt::Password.new(user['password']).is_password? password
return "<font color=green>Login successful! Welcome, #{username}!"
end
end
"<font color=red>Invalid credentials. <a href='/login'>Try again</a>"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment