Created
February 10, 2012 19:28
-
-
Save Shamaoke/1791998 to your computer and use it in GitHub Desktop.
Rails' Authentication example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# module | |
require 'digest/sha2' | |
module Extensions | |
module Authentication | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def find_and_authenticate(attributes) | |
@user.authenticate(attributes[:password]) if @user = find_by_email(attributes[:email]) | |
end | |
end | |
def encrypt_password(password, salt) | |
Digest::SHA2.hexdigest(password << salt) | |
end | |
def authenticate(password) | |
id if hashed_password == encrypt_password(password, salt) | |
end | |
def password=(password) | |
assign_attributes salt: get_or_generate_salt, hashed_password: encrypt_password(password, get_or_generate_salt) | |
end | |
def get_or_generate_salt | |
@salt ||= rand.to_s | |
end | |
end | |
end | |
# model | |
class User < ActiveRecord::Base | |
include Extensions::Authentication | |
end | |
# controller | |
class SessionsController < ApplicationController | |
def create | |
if session[:user_id] = User.find_and_authenticate(params[:user]) | |
flash[:notice] = 'User has been logged in' | |
redirect_to users_path | |
else | |
flash.now[:notice] = 'User has not been logged in' | |
render new_session_path | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment