2014-11-18 16:06:47 +00:00
|
|
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
2019-04-19 07:53:46 +01:00
|
|
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
2014-11-18 16:06:47 +00:00
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2015-08-26 14:34:27 +01:00
|
|
|
package gitea
|
2014-11-18 16:06:47 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2019-05-11 16:38:52 +01:00
|
|
|
|
|
|
|
"code.gitea.io/gitea/modules/structs"
|
2014-11-18 16:06:47 +00:00
|
|
|
)
|
|
|
|
|
2016-11-10 09:44:00 +00:00
|
|
|
// BasicAuthEncode generate base64 of basic auth head
|
2014-11-18 16:06:47 +00:00
|
|
|
func BasicAuthEncode(user, pass string) string {
|
|
|
|
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
|
|
|
}
|
|
|
|
|
2019-05-11 16:38:52 +01:00
|
|
|
// AccessToken is equal to structs.AccessToken
|
|
|
|
type AccessToken = structs.AccessToken
|
2017-04-30 16:33:16 +01:00
|
|
|
|
2016-11-10 09:44:00 +00:00
|
|
|
// ListAccessTokens lista all the access tokens of user
|
2014-11-18 16:06:47 +00:00
|
|
|
func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) {
|
|
|
|
tokens := make([]*AccessToken, 0, 10)
|
|
|
|
return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user),
|
|
|
|
http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens)
|
|
|
|
}
|
|
|
|
|
2016-11-10 09:44:00 +00:00
|
|
|
// CreateAccessToken create one access token with options
|
2019-05-11 16:38:52 +01:00
|
|
|
func (c *Client) CreateAccessToken(user, pass string, opt structs.CreateAccessTokenOption) (*AccessToken, error) {
|
2014-11-18 16:06:47 +00:00
|
|
|
body, err := json.Marshal(&opt)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
t := new(AccessToken)
|
|
|
|
return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user),
|
|
|
|
http.Header{
|
|
|
|
"content-type": []string{"application/json"},
|
|
|
|
"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}},
|
|
|
|
bytes.NewReader(body), t)
|
|
|
|
}
|
2018-06-20 10:04:31 +01:00
|
|
|
|
|
|
|
// DeleteAccessToken delete token with key id
|
|
|
|
func (c *Client) DeleteAccessToken(user string, keyID int64) error {
|
|
|
|
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/%s/tokens/%d", user, keyID), nil, nil)
|
|
|
|
return err
|
|
|
|
}
|