user_app.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 gogs
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "net/http"
  11. )
  12. func BasicAuthEncode(user, pass string) string {
  13. return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
  14. }
  15. // AccessToken represents a API access token.
  16. type AccessToken struct {
  17. Name string `json:"name"`
  18. Sha1 string `json:"sha1"`
  19. }
  20. func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) {
  21. tokens := make([]*AccessToken, 0, 10)
  22. return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user),
  23. http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens)
  24. }
  25. type CreateAccessTokenOption struct {
  26. Name string `json:"name" binding:"Required"`
  27. }
  28. func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) {
  29. body, err := json.Marshal(&opt)
  30. if err != nil {
  31. return nil, err
  32. }
  33. t := new(AccessToken)
  34. return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user),
  35. http.Header{
  36. "content-type": []string{"application/json"},
  37. "Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}},
  38. bytes.NewReader(body), t)
  39. }