Module: Authify::API::Helpers::JWTEncryption

Includes:
Core::Helpers::JWTSSL
Defined in:
lib/authify/api/helpers/jwt_encryption.rb

Overview

Helper methods for working with JWT encryption

Instance Method Summary collapse

Instance Method Details

#jwt_optionsObject



33
34
35
36
37
38
39
40
# File 'lib/authify/api/helpers/jwt_encryption.rb', line 33

def jwt_options
  {
    algorithm: CONFIG[:jwt][:algorithm],
    verify_iss: true,
    verify_iat: true,
    iss: CONFIG[:jwt][:issuer]
  }
end

#jwt_payload(user, custom_data, metadata = nil) ⇒ Object

rubocop:disable Metrics/AbcSize



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/authify/api/helpers/jwt_encryption.rb', line 14

def jwt_payload(user, custom_data,  = nil)
  data = {
    exp: Time.now.to_i + 60 * CONFIG[:jwt][:expiration].to_i,
    iat: Time.now.to_i,
    iss: CONFIG[:jwt][:issuer],
    scopes: Core::Constants::JWTSCOPES.dup.tap do |scopes|
      scopes << :admin_access if user.admin?
    end,
    user: {
      username: user.email,
      uid: user.id,
      organizations: simple_orgs_by_user(user)
    }
  }
  data[:custom] = custom_data if custom_data && !custom_data.empty?
  data[:meta] =  if  && .is_a?(Hash) && !.empty?
  data
end

#jwt_token(user: nil, custom_data: {}, meta: nil) ⇒ Object



8
9
10
11
# File 'lib/authify/api/helpers/jwt_encryption.rb', line 8

def jwt_token(user: nil, custom_data: {}, meta: nil)
  user ||= current_user
  JWT.encode jwt_payload(user, custom_data, meta), private_key, CONFIG[:jwt][:algorithm]
end

#process_token(token) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/authify/api/helpers/jwt_encryption.rb', line 42

def process_token(token)
  results = {}

  begin
    decoded = JWT.decode(token, public_key, true, jwt_options)

    results[:valid] = true
    results[:payload] = decoded[0]
    results[:type] = decoded[1]['typ']
    results[:algorithm] = decoded[1]['alg']
  rescue JWT::DecodeError => e
    results[:valid] = false
    results[:errors] = Array[e]
    results[:reason] = 'Corrupt or invalid JWT'
  end
  results
end

#simple_orgs_by_user(user) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/authify/api/helpers/jwt_encryption.rb', line 60

def simple_orgs_by_user(user)
  user.organizations.map do |o|
    {
      name: o.name,
      oid: o.id,
      admin: o.admins.include?(user),
      memberships: o.groups.select { |g| g.users.include?(user) }.map do |g|
        { name: g.name, gid: g.id }
      end
    }
  end
end

#with_jwt(req, scope) ⇒ Object



73
74
75
76
77
78
79
80
81
82
# File 'lib/authify/api/helpers/jwt_encryption.rb', line 73

def with_jwt(req, scope)
  scopes, user = req.env.values_at :scopes, :user
  set_current_user Models::User.from_username(user['username'])

  if scopes.include?(scope) && current_user
    yield req
  else
    halt 403
  end
end