Top Level Namespace

Defined Under Namespace

Modules: JwtAuthToken

Constant Summary collapse

ROUTES =
{}

Instance Method Summary collapse

Instance Method Details

#authenticate_user?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
# File 'lib/jwt_auth_token.rb', line 22

def authenticate_user?
  if is_valid_token?
    return true
  else
    render json: {"error" => "User Authentication Failed", :status => 401}, :status => 401 and return
  end
end

#current_userObject



30
31
32
# File 'lib/jwt_auth_token.rb', line 30

def current_user
  @_current_user ||= OpenStruct.new(@decoded_token) if is_valid_token?
end

#get_routersObject



59
60
61
62
63
64
65
66
67
68
# File 'lib/jwt_auth_token.rb', line 59

def get_routers
  Rails.application.routes.routes.map do |route|
    path = route.path.spec.to_s.gsub(/\(\.:format\)/, "").gsub(/:[a-zA-Z_]+/, "1")
    next if path.include?("rails")
    port = ":#{route.defaults[:port]}" if route.defaults[:port]
    complete_url = "#{route.defaults[:host]}#{port}#{path}"
    verb = %W{ GET POST PUT PATCH DELETE }.grep(route.verb).first.downcase.to_sym rescue nil
    ROUTES["#{route.name}_url"] = { path: path, verb: verb, url: complete_url}
  end
end

#header_nameObject



13
14
15
# File 'lib/jwt_auth_token.rb', line 13

def header_name
  @_header_name ||= "embibe-token"
end

#header_tokenObject



34
35
36
# File 'lib/jwt_auth_token.rb', line 34

def header_token
  @_header_token ||= request.headers[header_name] rescue nil
end

#is_valid_token?Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
# File 'lib/jwt_auth_token.rb', line 38

def is_valid_token?
  begin
    @decoded_token = JSON.parse(JWT.decode(header_token, jwt_hmac_secret, true, { :algorithm => jwt_algorithm })[0])
    return validate_keys
  rescue Exception => e
    return false
  end  
end

#jwt_algorithmObject



9
10
11
# File 'lib/jwt_auth_token.rb', line 9

def jwt_algorithm
  @_jwt_algorithm ||= 'HS512'
end

#jwt_hmac_secretObject



5
6
7
# File 'lib/jwt_auth_token.rb', line 5

def jwt_hmac_secret
  @_jwt_hmac_secret ||= Rails.application.secrets[:secret_key_base]
end

#jwt_set_header(data) ⇒ Object



17
18
19
20
# File 'lib/jwt_auth_token.rb', line 17

def jwt_set_header(data)
  encoded_token = JWT.encode(data,jwt_hmac_secret,jwt_algorithm)
  response.set_header(header_name, encoded_token)
end

#restClientUrl(url, payload = {}) ⇒ Object



52
53
54
55
56
57
# File 'lib/jwt_auth_token.rb', line 52

def restClientUrl(url, payload = {})
  @_get_routers ||= get_routers
  _req = OpenStruct.new(ROUTES[url])
  data = RestClient::Request.execute(method: _req.verb, url: _req.url, payload: payload, headers: { "#{header_name}" => header_token})
  {code: data.code, data: JSON.parse(data.body), headers: data.headers, cookies: data.cookies}
end

#validate_keysObject



47
48
49
# File 'lib/jwt_auth_token.rb', line 47

def validate_keys
  !!@_validate_keys ||= (@decoded_token.keys && ["id", "email"]).any?
end