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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/models/concerns/rails_jwt_auth/authenticatable.rb', line 49

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

  base.send(:validates, RailsJwtAuth.auth_field_name, presence: true, uniqueness: true)
  base.send(:validates, RailsJwtAuth.auth_field_name, email: true) if RailsJwtAuth.auth_field_email

  base.send(:has_secure_password)

  base.extend(ClassMethods)
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

#update_with_password(params) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# 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.blank'))
    false
  elsif authenticate(current_password)
    update_attributes(params)
  else
    errors.add(:current_password, I18n.t('rails_jwt_auth.errors.invalid'))
    false
  end
end