Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Account < ActiveRecord::Base
- has_many :users, :through => :groups, :dependent => :destroy
- has_many :changerequests, :dependent => :destroy
- has_many :tasks, :through => :changerequests, :dependent => :destroy
- has_many :comments, :through => :changerequests, :dependent => :destroy
- has_many :groups, :dependent => :destroy
- validates_format_of :name, :with => /^[a-zA-Z0-9]*?$/, :message => 'accepts letters and numbers only.'
- validates_presence_of :name
- validates_uniqueness_of :name
- validates_associated :groups
- def before_save
- # Transform all account names (subdomains) to lowercase
- self.name.downcase!
- end
- end
- class Group < ActiveRecord::Base
- has_many :users, :dependent => :destroy
- belongs_to :account
- validates_presence_of :name
- validates_uniqueness_of :name, :scope => :account_id
- validates_associated :users
- end
- class User < ActiveRecord::Base
- has_many :changerequests
- has_many :tasks
- has_many :comments, :dependent => :destroy
- belongs_to :group
- has_one :account, :through => :groups
- validates_presence_of :first, :last, :email, :username
- validate :uniqueness_of_username
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- validate :password_non_blank
- def self.authenticate(username, password)
- user = self.find_by_username(username.downcase)
- if user
- expected_password = encrypted_password(password, user.salt)
- if user.hashed_password != expected_password
- user = nil
- end
- end
- user
- end
- # 'password' is a virtual attribute
- def password
- @password
- end
- def password=(pwd)
- @password = pwd
- return if pwd.blank?
- create_new_salt
- self.hashed_password = User.encrypted_password(self.password, self.salt)
- end
- def before_save
- # Transition all usernames to lowercase
- self.username.downcase!
- end
- private
- def password_non_blank
- errors.add_to_base("Missing password" ) if hashed_password.blank?
- end
- def create_new_salt
- self.salt = self.object_id.to_s + rand.to_s
- end
- def self.encrypted_password(password, salt)
- string_to_hash = password + "wibble" + salt
- Digest::SHA1.hexdigest(string_to_hash)
- end
- protected
- def uniqueness_of_username
- # Ensure username is unique per account
- @account = Account.find(self.group.account_id) if self.group_id
- if @account
- errors.add(:username, ' is already taken.') if @account.users.find(:all, :conditions => { :username => :username })
- end
- end
- end
Add Comment
Please, Sign In to add comment