Sha256: 608ce65a7bf5454a8b2938bb62a5d6bf20083ae3a0c45ce0058d3fa32993710d

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

class User < ActiveRecord::Base
    validates_length_of :login, :within => 3..40
    validates_length_of :password, :within => 5..40, :allow_blank => true
    validates_presence_of :login, :email, :salt, :crypted_password
    validates_uniqueness_of :login, :email
    validates_confirmation_of :password
    validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "Invalid email"
    
    validates :password, :confirmation => true
    
    # These are protected so they can't be forged by users
    attr_protected :id, :salt
    
    attr_accessor :password
    
    # Assign password field encrypts into crypted_password database-backed field
    def password=(pass)
        @password=pass
        self.salt = User.random_string(10) if !self.salt?
        self.crypted_password = User.encrypt(@password, self.salt)
    end

    # Authenticate
    def self.authenticate(login, pass)
        u = find(:first, :conditions=>["login = ?", login])
        return nil if u.nil?
        return u if User.encrypt(pass, u.salt) == u.crypted_password
        return nil
    end

    def is_webmaster
        return self.role == 0
    end

    def is_admin
        return self.role <= 1
    end

    # Called if the user forgets their password; sets it to a random one, emails that to the user's email address
    def send_new_password
        new_pass = User.random_string(10)
        self.password = self.password_confirmation = new_pass
        self.save
        Notifications.deliver_forgot_password(self.email, self.login, new_pass)
    end

    protected

    # Used to make salt
    def self.random_string(len)
        #generate a random password consisting of strings and digits
        chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
        newpass = ""
        1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
        return newpass
    end

    # SHA1 encrypt
    def self.encrypt(pass, salt)
        Digest::SHA1.hexdigest(pass+salt)
    end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fs_auth-0.0.1 app/models/user.rb