Class: Trainmaster::User

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Repia::Support::UUIDModel
Defined in:
app/models/trainmaster/user.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ User

Initializes the user. User is not verified initially. The user has one hour to get verified. After that, a PATCH request must be made to re-issue the verification token.



51
52
53
54
# File 'app/models/trainmaster/user.rb', line 51

def initialize(attributes = {})
  attributes[:api_key] = SecureRandom.hex(32)
  super
end

Class Method Details

.from_omniauth_hash(auth_hash) ⇒ Object

Create a user from oauth.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/models/trainmaster/user.rb', line 30

def self.from_omniauth_hash(auth_hash)
  params = {
    oauth_provider: auth_hash.provider,
    oauth_uid: auth_hash.uid
  }
  where(params).first_or_initialize(attributes={}) do |user|
    user.oauth_provider = auth_hash.provider
    user.oauth_uid = auth_hash.uid
    user.oauth_name = auth_hash.info.name
    user.oauth_token = auth_hash.credentials.token
    user.oauth_expires_at = Time.at(auth_hash.credentials.expires_at)
    user.verified = true
    user.save!
  end
end

Instance Method Details

#default_roleObject

Sets the default the role for the user if not set.



59
60
61
# File 'app/models/trainmaster/user.rb', line 59

def default_role
  self.role ||= Roles::USER
end

#issue_token(kind) ⇒ Object

This method will generate a reset token that lasts for an hour.



66
67
68
69
70
71
72
73
74
# File 'app/models/trainmaster/user.rb', line 66

def issue_token(kind)
  session = Session.new(user: self, seconds: 3600)
  session.save
  if kind == :reset_token
    self.reset_token = session.token
  elsif kind == :verification_token
    self.verification_token = session.token
  end
end

#valid_userObject

This method validates if the user object is valid. A user is valid if username and password exist OR oauth integration exists.



20
21
22
23
24
25
# File 'app/models/trainmaster/user.rb', line 20

def valid_user
  if (self.username.blank? || self.password_digest.blank?) &&
      (self.oauth_provider.blank? || self.oauth_uid.blank?)
    errors.add(:username, " and password OR oauth must be specified")
  end
end