summaryrefslogtreecommitdiff
path: root/lib/gitlab/lfs_token.rb
blob: 5f67e97fa2a718ad0ff8e004c281834d2b7d94f7 (plain)
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
module Gitlab
  class LfsToken
    attr_accessor :actor

    TOKEN_LENGTH = 50
    EXPIRY_TIME = 1800

    def initialize(actor)
      @actor =
        case actor
        when DeployKey, User
          actor
        when Key
          actor.user
        else
          raise 'Bad Actor'
        end
    end

    def token
      Gitlab::Redis.with do |redis|
        token = redis.get(redis_key)
        token ||= Devise.friendly_token(TOKEN_LENGTH)
        redis.set(redis_key, token, ex: EXPIRY_TIME)

        token
      end
    end

    def user?
      actor.is_a?(User)
    end

    def type
      actor.is_a?(User) ? :lfs_token : :lfs_deploy_token
    end

    def actor_name
      actor.is_a?(User) ? actor.username : "lfs+deploy-key-#{actor.id}"
    end

    private

    def redis_key
      "gitlab:lfs_token:#{actor.class.name.underscore}_#{actor.id}" if actor
    end
  end
end