# -*- coding: binary -*-

module Msf::Exploit::Remote::HTTP::Gitea::Login
  # performs a gitea login
  #
  # @param user [String] Username
  # @param pass [String] Password
  # @param timeout [Integer] The maximum number of seconds to wait before the
  #   request times out
  # @raise [CsrfError] if the CSRF could not be retrieved
  # @raise [AuthenticationError] if the authentication fails
  # @return [Rex::Proto::Http::Response,AuthenticationError] the HTTP response
  #   on successful login, raise AuthenticationError otherwise
  def gitea_login(user, pass, timeout = 20)
    res = send_request_cgi({
      'uri' => gitea_url_login,
      'keep_cookies' => true
    }, timeout)
    return nil unless res

    csrf = gitea_get_csrf(res)
    raise Msf::Exploit::Remote::HTTP::Gitea::Error::CsrfError.new unless csrf

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => gitea_url_login,
      'vars_post' => gitea_helper_login_post_data(user, pass, csrf),
      'keep_cookies' => true
    )

    raise Msf::Exploit::Remote::HTTP::Gitea::Error::AuthenticationError.new if res&.code != 302

    store_valid_credential(user: user, private: pass)
    return res
  end
end
