82 lines
1.5 KiB
Ruby
82 lines
1.5 KiB
Ruby
require 'bundler/setup'
|
|
require 'sinatra'
|
|
require 'sinatra/activerecord'
|
|
require 'bcrypt'
|
|
require 'securerandom'
|
|
|
|
#set :database, 'sqlite3:db/vote.sqlite3'
|
|
|
|
class Vote < ActiveRecord::Base
|
|
self.primary_key = "secure_id"
|
|
end
|
|
|
|
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
|
|
redirect '/login' unless current_user
|
|
@votes = Vote.all
|
|
erb :home
|
|
end
|
|
|
|
get '/login' do
|
|
erb :login
|
|
end
|
|
|
|
post '/login' do
|
|
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
|
|
|
|
get '/votes/new' do
|
|
erb :votes_new
|
|
end
|
|
|
|
get '/votes/:id' do
|
|
@vote = Vote.find(params[:id])
|
|
erb :votes_show
|
|
end
|
|
|
|
post '/votes' do
|
|
secure_id = SecureRandom.hex(8)
|
|
@vote = Vote.create(secure_id: secure_id,
|
|
title: params[:title],
|
|
description: params[:description])
|
|
redirect '/votes/' + secure_id
|
|
end
|
|
|
|
helpers do
|
|
def current_user
|
|
if session[:user_id]
|
|
USERS.find { |u| u.id == session[:user_id] }
|
|
else
|
|
nil
|
|
end
|
|
end
|
|
end
|