class User < ActiveRecord::Base include ActionView::Helpers::DateHelper validates :login, presence: true, uniqueness: true, length: { maximum: 80 } validates :first_name, presence: true validates :last_name, presence: true VALID_EMAIL_REGEX = Rails.env.production? ? /\A[\w+\-.]+@akamai\.com\z/i : /\A[\w+\-.]+@(akamai|mailinator)\.com\z/i validates :email, presence: true, uniqueness: true, format: { with: VALID_EMAIL_REGEX, message: Rails.env.production? ? "must be an Akamai email address." : "must be an Akamai or Mailinator email address." } has_secure_password validates :password, length: { minimum: 6 }, :if => :password_required? has_many :apis, foreign_key: 'owner_id' before_create :create_remember_token before_create :create_password_reset_token before_save { self.login = login.downcase; self.email = email.downcase } before_destroy :deny_owners def generate_token(column) begin self[column] = SecureRandom.urlsafe_base64 end while User.exists?(column => self[column]) end def User.new_remember_token SecureRandom.urlsafe_base64 end def User.encrypt(token) Digest::SHA1.hexdigest(token.to_s) end def send_password_reset(expiration = 2.hours.from_now) generate_token(:password_reset_token) self.password_reset_expires_at = expiration save! UserMailer.password_reset(self).deliver end def send_email_confirmation(expiration = 2.hours.from_now) generate_token(:email_confirmation_token) self.email_confirmation_expires = expiration self.email_confirmed = false save! UserMailer.email_confirm(self).deliver end def count_pages_visited User.increment_counter(:pages_visited, self) end def did_ago_in_words(timestamp) send(timestamp) ? "#{time_ago_in_words(send(timestamp), include_seconds:true)} ago" : "(never)" end def long_name @long_name ||= "#{ first_name } #{ last_name }" end def to_s @to_s ||= "#{ long_name } (#{ login })" end private def create_remember_token self.remember_token = User.encrypt(User.new_remember_token) end def create_password_reset_token self.password_reset_token = SecureRandom.urlsafe_base64 end def deny_owners raise ArgumentError("Please reassign this user's APIs before deleting them.") if self.apis.any? end def password_required? !persisted? || !password.nil? || !password_confirmation.nil? end end