You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user_app.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package gitea
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "net/http"
  11. )
  12. // BasicAuthEncode generate base64 of basic auth head
  13. func BasicAuthEncode(user, pass string) string {
  14. return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
  15. }
  16. // AccessToken represents a API access token.
  17. // swagger:response AccessToken
  18. type AccessToken struct {
  19. ID int64 `json:"id"`
  20. Name string `json:"name"`
  21. Sha1 string `json:"sha1"`
  22. }
  23. // AccessTokenList represents a list of API access token.
  24. // swagger:response AccessTokenList
  25. type AccessTokenList []*AccessToken
  26. // ListAccessTokens lista all the access tokens of user
  27. func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) {
  28. tokens := make([]*AccessToken, 0, 10)
  29. return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user),
  30. http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens)
  31. }
  32. // CreateAccessTokenOption options when create access token
  33. // swagger:parameters userCreateToken
  34. type CreateAccessTokenOption struct {
  35. Name string `json:"name" binding:"Required"`
  36. }
  37. // CreateAccessToken create one access token with options
  38. func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) {
  39. body, err := json.Marshal(&opt)
  40. if err != nil {
  41. return nil, err
  42. }
  43. t := new(AccessToken)
  44. return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user),
  45. http.Header{
  46. "content-type": []string{"application/json"},
  47. "Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}},
  48. bytes.NewReader(body), t)
  49. }
  50. // DeleteAccessToken delete token with key id
  51. func (c *Client) DeleteAccessToken(user string, keyID int64) error {
  52. _, err := c.getResponse("DELETE", fmt.Sprintf("/user/%s/tokens/%d", user, keyID), nil, nil)
  53. return err
  54. }