Files
sx-fc/app/models/employee.rb
2017-04-19 18:37:07 +06:30

65 lines
1.5 KiB
Ruby

class Employee < ApplicationRecord
has_secure_password
validates_presence_of :name, :role
validates_presence_of :password, :on => [:create]
validates :emp_id, uniqueness: true, numericality: true, length: {in: 1..4}, allow_blank: true
validates :password, numericality: true, length: {in: 3..9}, allow_blank: true
def self.login(emp_id, password)
user = Employee.find_by_emp_id(emp_id)
if (user)
user.authenticate(password)
if (user)
user.generate_token
user.session_expiry = DateTime.now.utc + 30.minutes
user.session_last_login = DateTime.now.utc
user.save
return user
end
end
return nil
end
def self.authenticate_by_token(session_token)
if (session_token)
user = Employee.find_by_token_session(session_token)
if user && user.session_expiry.utc > DateTime.now.utc
#Extend the login time each time authenticatation take place
user.session_expiry = user.session_expiry.utc + 30.minutes
user.save
return true
else
return false
end
end
return false
end
def self.logout(session_token)
if (session_token)
user = Employee.find_by_token_session(session_token)
if user
user.token_session = nil
user.session_expiry = nil
user.save
end
end
end
def generate_token
update_column :token_session, SecureRandom.hex(10)
rescue ActiveRecord::RecordNotUnique
retry
end
end