Skip to content

Instantly share code, notes, and snippets.

@sebastjan-hribar
Created March 14, 2015 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastjan-hribar/38b5b640ffd29d96cc70 to your computer and use it in GitHub Desktop.
Save sebastjan-hribar/38b5b640ffd29d96cc70 to your computer and use it in GitHub Desktop.
camping - authentication
#Migration
class UserFields < V 1.1
def self.up
create_table User.table_name do |t|
t.string :username
t.string :email
t.string :role
t.string :password_hash
t.string :assword_salt
end
end
def self.down
drop_table User.table_name
end
end
#User model
class User < Base
attr_accessor :password
validates_confirmation_of :password
before_save :encrypt_password
def encrypt_password
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
def self.authenticate(username, password)
user = User.where(username: username).first
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
end
#New user controller
class UserNew
def get
@user = User.new
render :new_user_registration
end
def post
@user = User.create(user_reg_attr)
begin
@user.save!
@user_success_message = "Vaš uporabniški račun je bil uspešno ustvarjen."
return(redirect Login, @user)
rescue Exception => ex
@user_errors = @user.errors || [ ex.to_s ]
return(render(:index))
end
end
end
#Login controller
class Login
def get
render :login
end
def post
@user = User.authenticate(input.username, input.password)
if @user
@state.user_id = @user.id
@state.username = @user.username
redirect Index
else
redirect Login
end
end
end
#Logout controller
class Logout
def get
@state.user_id = nil
@state.username = nil
redirect Login
end
end
#Edit user controller
class EdituserN
def get(user_id)
@user = User.find(user_id)
render :edit_user
end
def post(user_id)
@user = User.find(user_id)
@user.update_attribute(:role, input.role)
@user.save
redirect UserN, @user
end
end
#User registration attributes helper method
def user_reg_attr
user_reg_attr = {username: input.username, email: input.email, role: "translator", password: input.password, password_confirmation: input.password_confirmation}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment