Created
September 7, 2014 18:26
-
-
Save markglenfletcher/db82d2c44f9de2de10dd to your computer and use it in GitHub Desktop.
simple mongoid auth
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
require 'digest/sha1' | |
class User | |
include Mongoid::Document | |
attr_accessor :password, :password_confirmation | |
field :email, type: String | |
field :hashed_password, type: String | |
field :salt, type: String | |
before_validation :set_hashed_password | |
def has_password?(pass) | |
hashed_password == encrypt_password(pass, salt) | |
end | |
private | |
def set_hashed_password | |
self.salt ||= generate_salt | |
self.hashed_password = encrypt_password(password, salt) | |
end | |
def generate_salt | |
random_string = (0..25).map{ ('a'..'z').to_a[rand(26)] }.join | |
Digest::SHA1.hexdigest(random_string) | |
end | |
def encrypt_password(password, salt) | |
Digest::SHA1.hexdigest(password + salt) | |
end | |
class << self | |
def authenticate(email, password) | |
user = User.where(email: email).first | |
return false unless user | |
user.has_password?(password) | |
end | |
end | |
end | |
################### | |
u = User.create(email: 'test@example.com', password: 'password', password_confirmation: 'password') | |
=> #<User _id: 540ca2fe4d61722071000000, email: "test@example.com", hashed_password: "14f763e4ea4ba2bc38c6ba3f7c60de99a978dcd5", salt: "acf19b17ec24f70e5f4818b8899db480cba539b1"> | |
u.has_password?('password') | |
=> true | |
User.authenticate('test@example.com','password') | |
=> true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment