Class: UserManagement::ApplicationController

Inherits:
ActionController::API
  • Object
show all
Defined in:
app/controllers/user_management/application_controller.rb

Direct Known Subclasses

AuthenticationController, UsersController

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.authorized(token) ⇒ Object



33
34
35
36
37
# File 'app/controllers/user_management/application_controller.rb', line 33

def self.authorized(token)
    return render json: {message: 'Token not provided',status: 403}.symbolize_keys unless token
    return render json: { message: 'Please log in', status: 403 }.symbolize_keys unless logged_in?(token)
    render json: {status: 200, message: 'Authorised User'}
end

.decode_token(token) ⇒ Object



12
13
14
15
16
17
18
19
# File 'app/controllers/user_management/application_controller.rb', line 12

def self.decode_token(token)
    begin
        token = token.split(' ')[1]
        JWT.decode(token, SETTINGS['secret_key'], true, algorithm: 'HS256')
    rescue JWT::DecodeError
        nil
    end
end

.logged_in?(token) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'app/controllers/user_management/application_controller.rb', line 29

def self.logged_in?(token)
    !!logged_in_user(token)
end

.logged_in_user(token) ⇒ Object



21
22
23
24
25
26
27
# File 'app/controllers/user_management/application_controller.rb', line 21

def self.logged_in_user(token)
    decoded_token = decode_token(token)[0].symbolize_keys rescue return
    if decoded_token
      user_id = decoded_token[:user_id]
      @user = User.find(user_id) if decoded_token[:exp] > Time.now.to_i
    end
end

Instance Method Details

#encode_token(payload) ⇒ Object

protect_from_forgery with: :exception



7
8
9
10
# File 'app/controllers/user_management/application_controller.rb', line 7

def encode_token(payload)
    payload[:exp] = 8.hours.from_now.to_i
    JWT.encode(payload, SETTINGS['secret_key'])
end