2020-04-21 11:21:10 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module PersonalAccessTokens
|
|
|
|
class CreateService < BaseService
|
2020-11-09 07:09:24 -05:00
|
|
|
def initialize(current_user:, target_user:, params: {})
|
2020-04-21 11:21:10 -04:00
|
|
|
@current_user = current_user
|
2020-11-09 07:09:24 -05:00
|
|
|
@target_user = target_user
|
2020-04-21 11:21:10 -04:00
|
|
|
@params = params.dup
|
2020-11-09 07:09:24 -05:00
|
|
|
@ip_address = @params.delete(:ip_address)
|
2020-04-21 11:21:10 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
2020-11-09 07:09:24 -05:00
|
|
|
return ServiceResponse.error(message: 'Not permitted to create') unless creation_permitted?
|
2020-04-21 11:21:10 -04:00
|
|
|
|
2020-11-09 07:09:24 -05:00
|
|
|
token = target_user.personal_access_tokens.create(params.slice(*allowed_params))
|
|
|
|
|
|
|
|
if token.persisted?
|
|
|
|
log_event(token)
|
|
|
|
ServiceResponse.success(payload: { personal_access_token: token })
|
2020-04-21 11:21:10 -04:00
|
|
|
else
|
2020-11-09 07:09:24 -05:00
|
|
|
ServiceResponse.error(message: token.errors.full_messages.to_sentence, payload: { personal_access_token: token })
|
2020-04-21 11:21:10 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2020-11-09 07:09:24 -05:00
|
|
|
attr_reader :target_user, :ip_address
|
|
|
|
|
2020-04-21 11:21:10 -04:00
|
|
|
def allowed_params
|
|
|
|
[
|
|
|
|
:name,
|
|
|
|
:impersonation,
|
|
|
|
:scopes,
|
|
|
|
:expires_at
|
|
|
|
]
|
|
|
|
end
|
2020-11-09 07:09:24 -05:00
|
|
|
|
|
|
|
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
|
2020-04-21 11:21:10 -04:00
|
|
|
end
|
|
|
|
end
|
2020-11-09 07:09:24 -05:00
|
|
|
|
2021-05-11 17:10:21 -04:00
|
|
|
PersonalAccessTokens::CreateService.prepend_mod_with('PersonalAccessTokens::CreateService')
|