# -*- coding: binary -*-

# Create a Gitlab Access Token via form
module Msf::Exploit::Remote::HTTP::Gitlab::Form::AccessTokens
  # Create Gitlab access access token
  #
  # @return [String,nil] Gitlab personal access token if created, nil otherwise
  def gitlab_create_personal_access_token
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/-/profile/personal_access_tokens'),
      'keep_cookies' => true,
      'vars_post' => {
        'personal_access_token[name]' => Rex::Text.rand_text_alphanumeric(8),
        'personal_access_token[expires_at]' => '',
        'personal_access_token[scopes][]' => 'api',
        'commit' => 'Create personal access token'
      },
      'headers' => {
        'X-CSRF-Token' => gitlab_helper_extract_csrf_token(path: '/-/profile/personal_access_tokens', regex: /name="csrf-token" content="(.*)"/)
      }
    })

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError.new message: 'Request timed out' unless res

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError, "Failed to create access token. Unexpected HTTP #{res.code} response." unless res.code == 200

    token = JSON.parse(res.body)['new_token']

    return token if token

    nil
  end
end
