DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

App/models/user.rb

06.15.2008
| 4053 views |
  • submit to reddit
        
require 'digest/sha1'

# this model expects a certain database layout and its based on the name/login pattern.
class User < ActiveRecord::Base
        has_and_belongs_to_many :groups,
                :class_name => 'Group',
                :join_table => 'users_groups'

        def self.authenticate(username, password)
                @user = find(:first, :conditions => ["username = ? AND password = ? and confirmed = ?", username, sha1(password), true])
        end

        def remember_me
                self.remember_token_expires = 2.weeks.from_now
                self.remember_token = Digest::SHA1.hexdigest("GFDHDFUHFJI&&%ET%&*%^£FESER^&J&IJR%TXEYFGU(*I$R^%E&DU&-#{self.email}#{self.remember_token_expires}")
                self.save_with_validation(false)
        end

        def forget_me
                self.remember_token_expires = nil
                self.remember_token = nil
                self.save_with_validation(false)
        end

        def reset_password
                tmppwd = self.generate_password
                write_attribute("password", self.class.sha1(tmppwd))
                self.save_with_validation(false)
                tmppwd
        end

        protected

        def generate_password
                chars = ("a".."z").to_a + ("1".."9").to_a
                Array.new(6, '').collect{chars[rand(chars.size)]}.join
        end

        def self.sha1(pass)
                Digest::SHA1.hexdigest(pass + "FSDT%^Y&JTFHY^&*IFY^H&&*(T&&RG%U&*I^HFGCDUI*TUF^HYU&*Y&T^F&*^&FUH")
        end

        before_create :crypt_password

        def crypt_password
                write_attribute("password", self.class.sha1(password))
        end

        validates_length_of :username, :within => 4..24
        validates_length_of :password, :within => 6..32
        validates_presence_of :username, :password, :password_confirmation
        validates_uniqueness_of :username, :on => :create
        validates_confirmation_of :password, :on => :create

        validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
        validates_format_of :username, :with => /^(\w*)$/i
        validates_format_of :name, :with => /^([\w ]*)$/i

        validates_presence_of :email, :name
        validates_length_of :name, :within => 6..32
        validates_uniqueness_of :email, :on => :create
end