Create model for users with email and password
This commit is contained in:
parent
d6500e013d
commit
6682c8c300
6 changed files with 72 additions and 14 deletions
40
vote.rb
40
vote.rb
|
|
@ -15,6 +15,9 @@ class Candidate < ActiveRecord::Base
|
|||
belongs_to :vote
|
||||
end
|
||||
|
||||
class User < ActiveRecord::Base
|
||||
end
|
||||
|
||||
def hash_password(password)
|
||||
BCrypt::Password.create(password).to_s
|
||||
end
|
||||
|
|
@ -23,13 +26,6 @@ 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
|
||||
|
|
@ -38,13 +34,23 @@ get '/' do
|
|||
erb :home
|
||||
end
|
||||
|
||||
get '/signup' do
|
||||
erb :signup
|
||||
end
|
||||
|
||||
post '/signup' do
|
||||
@user = User.create(email: params[:email],
|
||||
password: hash_password(params[:password]))
|
||||
redirect '/'
|
||||
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)
|
||||
user = User.find_by(email: params[:email])
|
||||
if user && verify_password(params[:password], user.password)
|
||||
session.clear
|
||||
session[:user_id] = user.id
|
||||
redirect '/'
|
||||
|
|
@ -64,6 +70,7 @@ get '/votes/new' do
|
|||
end
|
||||
|
||||
get '/votes/:id' do
|
||||
redirect '/login' unless current_user
|
||||
@vote = Vote.find(params[:id])
|
||||
erb :votes_show
|
||||
end
|
||||
|
|
@ -84,10 +91,23 @@ post '/votes/:id/candidates' do
|
|||
redirect '/votes/' + @vote.secure_id
|
||||
end
|
||||
|
||||
post '/votes/:id/ratings' do
|
||||
redirect '/login' unless current_user
|
||||
vote = Vote.find(params[:id])
|
||||
vote.candidates.each do |candidate|
|
||||
rating = Rating.find_by(user: current_user)
|
||||
rating = Rating.find_by(candidate: candidate)
|
||||
rating = Rating.find_or_initialize_by(user: current_user, candidate: candidate)
|
||||
rating.value = params[candidate.id.to_s]
|
||||
rating.save
|
||||
end
|
||||
redirect '/votes/' + vote.secure_id
|
||||
end
|
||||
|
||||
helpers do
|
||||
def current_user
|
||||
if session[:user_id]
|
||||
USERS.find { |u| u.id == session[:user_id] }
|
||||
User.find(session[:user_id])
|
||||
else
|
||||
nil
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue