blob: 31ba88af46ca1b20143e7261930b5b984c0a0dc9 (
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
49
50
51
52
53
54
55
56
57
|
# frozen_string_literal: true
module PersonalAccessTokens
class CreateService < BaseService
def initialize(current_user:, target_user:, params: {}, concatenate_errors: true)
@current_user = current_user
@target_user = target_user
@params = params.dup
@ip_address = @params.delete(:ip_address)
@concatenate_errors = concatenate_errors
end
def execute
return ServiceResponse.error(message: 'Not permitted to create') unless creation_permitted?
token = target_user.personal_access_tokens.create(personal_access_token_params)
if token.persisted?
log_event(token)
notification_service.access_token_created(target_user, token.name)
ServiceResponse.success(payload: { personal_access_token: token })
else
message = token.errors.full_messages
message = message.to_sentence if @concatenate_errors
ServiceResponse.error(message: message, payload: { personal_access_token: token })
end
end
private
attr_reader :target_user, :ip_address
def personal_access_token_params
{
name: params[:name],
impersonation: params[:impersonation] || false,
scopes: params[:scopes],
expires_at: pat_expiration
}
end
def pat_expiration
params[:expires_at].presence || PersonalAccessToken::MAX_PERSONAL_ACCESS_TOKEN_LIFETIME_IN_DAYS.days.from_now
end
def creation_permitted?
Ability.allowed?(current_user, :create_user_personal_access_token, target_user)
end
def log_event(token)
log_info("PAT CREATION: created_by: '#{current_user.username}', created_for: '#{token.user.username}', token_id: '#{token.id}'")
end
end
end
PersonalAccessTokens::CreateService.prepend_mod_with('PersonalAccessTokens::CreateService')
|