debian-mirror-gitlab/app/services/personal_access_tokens/create_service.rb

49 lines
1.3 KiB
Ruby
Raw Normal View History

2020-04-22 19:07:51 +05:30
# frozen_string_literal: true
module PersonalAccessTokens
class CreateService < BaseService
2021-01-29 00:20:46 +05:30
def initialize(current_user:, target_user:, params: {})
2020-04-22 19:07:51 +05:30
@current_user = current_user
2021-01-29 00:20:46 +05:30
@target_user = target_user
2020-04-22 19:07:51 +05:30
@params = params.dup
2021-01-29 00:20:46 +05:30
@ip_address = @params.delete(:ip_address)
2020-04-22 19:07:51 +05:30
end
def execute
2021-01-29 00:20:46 +05:30
return ServiceResponse.error(message: 'Not permitted to create') unless creation_permitted?
2020-04-22 19:07:51 +05:30
2021-01-29 00:20:46 +05:30
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-22 19:07:51 +05:30
else
2021-01-29 00:20:46 +05:30
ServiceResponse.error(message: token.errors.full_messages.to_sentence, payload: { personal_access_token: token })
2020-04-22 19:07:51 +05:30
end
end
private
2021-01-29 00:20:46 +05:30
attr_reader :target_user, :ip_address
2020-04-22 19:07:51 +05:30
def allowed_params
[
:name,
:impersonation,
:scopes,
:expires_at
]
end
2021-01-29 00:20:46 +05:30
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-22 19:07:51 +05:30
end
end
2021-01-29 00:20:46 +05:30
2021-06-08 01:23:25 +05:30
PersonalAccessTokens::CreateService.prepend_mod_with('PersonalAccessTokens::CreateService')