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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

54 lines
1.5 KiB
Ruby
Raw Normal View History

2020-04-22 19:07:51 +05:30
# frozen_string_literal: true
module PersonalAccessTokens
class CreateService < BaseService
2023-05-27 22:25:52 +05:30
def initialize(current_user:, target_user:, params: {}, concatenate_errors: true)
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)
2023-05-27 22:25:52 +05:30
@concatenate_errors = concatenate_errors
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)
2022-05-07 20:08:51 +05:30
notification_service.access_token_created(target_user, token.name)
2021-01-29 00:20:46 +05:30
ServiceResponse.success(payload: { personal_access_token: token })
2020-04-22 19:07:51 +05:30
else
2023-05-27 22:25:52 +05:30
message = token.errors.full_messages
message = message.to_sentence if @concatenate_errors
ServiceResponse.error(message: message, 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')