Module: RailsJwtAuth::Authenticatable

Defined in:
app/models/concerns/rails_jwt_auth/authenticatable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'app/models/concerns/rails_jwt_auth/authenticatable.rb', line 55

def self.included(base)
  base.extend(ClassMethods)

  base.class_eval do
    if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
      field RailsJwtAuth.auth_field_name, type: String
      field :password_digest,             type: String
      field :auth_tokens,                 type: Array
    elsif defined?(ActiveRecord) && ancestors.include?(ActiveRecord::Base)
      serialize :auth_tokens, Array
    end

    validates RailsJwtAuth.auth_field_name, presence: true, uniqueness: true
    validates RailsJwtAuth.auth_field_name, email: true if RailsJwtAuth.auth_field_email

    has_secure_password

    before_validation do
      self.email = email.downcase if email
    end
  end
end

Instance Method Details

#destroy_auth_token(token) ⇒ Object



18
19
20
21
22
23
24
25
# File 'app/models/concerns/rails_jwt_auth/authenticatable.rb', line 18

def destroy_auth_token(token)
  if RailsJwtAuth.simultaneous_sessions > 1
    tokens = auth_tokens || []
    update_attribute(:auth_tokens, tokens - [token])
  else
    update_attribute(:auth_tokens, [])
  end
end

#regenerate_auth_token(token = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'app/models/concerns/rails_jwt_auth/authenticatable.rb', line 5

def regenerate_auth_token(token = nil)
  new_token = SecureRandom.base58(24)

  if RailsJwtAuth.simultaneous_sessions > 1
    tokens = ((auth_tokens || []) - [token]).last(RailsJwtAuth.simultaneous_sessions - 1)
    update_attribute(:auth_tokens, (tokens + [new_token]).uniq)
  else
    update_attribute(:auth_tokens, [new_token])
  end

  new_token
end

#to_token_payload(_request) ⇒ Object



41
42
43
# File 'app/models/concerns/rails_jwt_auth/authenticatable.rb', line 41

def to_token_payload(_request)
  {auth_token: regenerate_auth_token}
end

#update_with_password(params) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/models/concerns/rails_jwt_auth/authenticatable.rb', line 27

def update_with_password(params)
  if (current_password = params.delete(:current_password)).blank?
    errors.add(:current_password, I18n.t('rails_jwt_auth.errors.current_password.blank'))
  elsif !authenticate(current_password)
    errors.add(:current_password, I18n.t('rails_jwt_auth.errors.current_password.invalid'))
  end

  if params[:password].blank?
    errors.add(:password, I18n.t('rails_jwt_auth.errors.password.blank'))
  end

  errors.empty? ? update_attributes(params) : false
end