Skip to content

Instantly share code, notes, and snippets.

@Shamaoke
Created February 10, 2012 19:28
Show Gist options
  • Save Shamaoke/1791998 to your computer and use it in GitHub Desktop.
Save Shamaoke/1791998 to your computer and use it in GitHub Desktop.
Rails' Authentication example
# 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