File: token.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (59 lines) | stat: -rw-r--r-- 1,196 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

require 'securerandom'

module JSONWebToken
  class Token
    attr_accessor :issuer, :subject, :audience, :id
    attr_accessor :issued_at, :not_before, :expire_time

    DEFAULT_NOT_BEFORE_TIME = 5
    DEFAULT_EXPIRE_TIME = 60

    def initialize
      @id = SecureRandom.uuid
      @issued_at = Time.now
      # we give a few seconds for time shift
      @not_before = issued_at - DEFAULT_NOT_BEFORE_TIME
      # default 60 seconds should be more than enough for this authentication token
      @expire_time = issued_at + DEFAULT_EXPIRE_TIME
      @custom_payload = {}
    end

    def [](key)
      @custom_payload[key]
    end

    def []=(key, value)
      @custom_payload[key] = value
    end

    def encoded
      raise NotImplementedError
    end

    def payload
      predefined_claims
        .merge(@custom_payload)
        .merge(default_payload)
    end

    private

    def predefined_claims
      {}
    end

    def default_payload
      {
        jti: id,
        aud: audience,
        sub: subject,
        iss: issuer,
        iat: issued_at.to_i,
        nbf: not_before.to_i,
        exp: expire_time.to_i
      }.compact
    end
  end
end