Gogs.pm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package Gogs;
  2. # ABSTRACT: Subclass of Pithub
  3. use strict;
  4. use warnings;
  5. use Moo;
  6. use Mime::Base64;
  7. extends 'Pithub';
  8. =head1 DESCRIPTION
  9. L<Pithub> is an acceptable API client for Gogs, since their APIs are compatible.
  10. However the two have a number of differences, so they must be accounted for.
  11. The most important of which being that all requests require an API token.
  12. =head1 SUBROUTINES
  13. =head2 get_token(%options)
  14. Gogs has no user-facing means of creating tokens like github does.
  15. You have to POST against the API using HTTP simple auth to acquire them.
  16. Requires that the object is instantiated with a username,
  17. that you pass a password, and that the api_uri is secure unless you pass the 'insecure' option.
  18. Will either fetch (if it exists) or create the named token.
  19. =cut
  20. # All API access requires a token on Gogs EXCEPT users/$user/tokens.
  21. # As such, I'm restricting every call not ending in /tokens
  22. my @TOKEN_REQUIRED_REGEXP = (qr{(?!/tokens$)});
  23. sub get_token {
  24. my ($self, %options) = @_;
  25. die "Must instantiate with username" unless $self->user;
  26. die "Must pass token name" unless $options{name};
  27. die "Refuse to operate over insecure connections" if !$options{insecure} && _insecure($uri);
  28. die "Must provide password to fetch tokens" unless $options{password};
  29. my %auth_headers = (
  30. 'Authorization' => "Basic ".encode_base64("$self->user:$options{password}"),
  31. 'Content-type' => "application/json",
  32. );
  33. my $token_endpoint = "/api/v1/users/$self->user/tokens";
  34. my %req = (
  35. method => 'GET',
  36. path => $tokens_endpoint,
  37. headers => \%auth_headers,
  38. );
  39. my $result = $self->request(%req);
  40. my $content = $result->content();
  41. die "Got bad response from server" unless ref $content eq "ARRAY";
  42. my $token_actual;
  43. foreach my $token (@$content) {
  44. next unless $token->{name} eq $options{name};
  45. return $token->{sha1};
  46. }
  47. # No such token named, so let's just make one.
  48. $req{method} = 'POST';
  49. my $result = $self->request(%req);
  50. my $content = $result->content();
  51. die "Got bad response from server" unless ref $content eq "HASH";
  52. return $content->{sha1};
  53. }
  54. sub _insecure {
  55. my $uri = shift;
  56. return m/^http:\/\//;
  57. }
  58. 1;