Skip to content

Instantly share code, notes, and snippets.

@LaoLiulaoliu
Created December 19, 2014 02:58
Show Gist options
  • Save LaoLiulaoliu/3db498440f83c637f200 to your computer and use it in GitHub Desktop.
Save LaoLiulaoliu/3db498440f83c637f200 to your computer and use it in GitHub Desktop.
ruby on rails simple auth
# == Schema Information
#
# Table name: admins
#
# id :integer not null, primary key
# username :string(255) not null
# encrypted_password :string(255) not null
# salt :string(255) not null
# created_at :datetime
# updated_at :datetime
#
require 'digest/sha1'
class Admin < ActiveRecord::Base
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates_presence_of :encrypted_password, :on => :create
validates_presence_of :salt, :on => :create
def self.create_one(username, password)
salt = Digest::SHA1.hexdigest("# We add #{username} as unique value and #{Time.now} as random value.")
encrypted_password= Digest::SHA1.hexdigest("Adding #{salt} to #{password}")
self.create(username: username, encrypted_password: encrypted_password, salt: salt)
end
def self.auth(username, password)
admin = Admin.find_by(username: username)
encrypted = Digest::SHA1.hexdigest("Adding #{admin.salt} to #{password}")
if admin.encrypted_password == encrypted
return admin.id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment