vedia/vote.rb

115 lines
2.3 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"
has_many :candidates
end
class Candidate < ActiveRecord::Base
belongs_to :vote
end
class User < ActiveRecord::Base
end
def hash_password(password)
BCrypt::Password.create(password).to_s
end
def verify_password(password, hash)
BCrypt::Password.new(hash) == password
end
enable :sessions
get '/' do
redirect '/login' unless current_user
@votes = Vote.all
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 = User.find_by(email: params[:email])
if user && verify_password(params[:password], user.password)
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
redirect '/login' unless current_user
@vote = Vote.find(params[:id])
erb :votes_show
end
post '/votes' do
@vote = Vote.create(secure_id: SecureRandom.hex(8),
title: params[:title],
description: params[:description])
redirect '/votes/' + @vote.secure_id
end
post '/votes/:id/candidates' do
@vote = Vote.find(params[:id])
@candidate = Candidate.new(name: params[:name],
description: params[:description])
@candidate.vote = @vote
@candidate.save
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]
User.find(session[:user_id])
else
nil
end
end
end