Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor token-related endpoints #26323

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions routers/api/v1/admin/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"

"code.gitea.io/gitea/models"
Expand Down Expand Up @@ -530,3 +531,183 @@ func RenameUser(ctx *context.APIContext) {
log.Trace("User name changed: %s -> %s", oldName, newName)
ctx.Status(http.StatusOK)
}

// ListAccessTokens list all the access tokens
func ListAccessTokens(ctx *context.APIContext) {
// swagger:operation GET /admin/users/{username}/tokens admin listAccessTokens
// ---
// summary: List the user's access tokens of {username} by admin
// produces:
// - application/json
// parameters:
// - name: username
// in: path
// description: username of user
// type: string
// required: true
// - name: page
// in: query
// description: page number of results to return (1-based)
// type: integer
// - name: limit
// in: query
// description: page size of results
// type: integer
// responses:
// "200":
// "$ref": "#/responses/AccessTokenList"

opts := auth.ListAccessTokensOptions{UserID: ctx.ContextUser.ID, ListOptions: utils.GetListOptions(ctx)}

count, err := auth.CountAccessTokens(opts)
if err != nil {
ctx.InternalServerError(err)
return
}
tokens, err := auth.ListAccessTokens(opts)
if err != nil {
ctx.InternalServerError(err)
return
}

apiTokens := make([]*api.AccessToken, len(tokens))
for i := range tokens {
apiTokens[i] = &api.AccessToken{
ID: tokens[i].ID,
Name: tokens[i].Name,
TokenLastEight: tokens[i].TokenLastEight,
Scopes: tokens[i].Scope.StringSlice(),
}
}
Comment on lines +573 to +581
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can add ToTokens and ToToken in services/convert package
Same to the others.


ctx.SetTotalCountHeader(count)
ctx.JSON(http.StatusOK, &apiTokens)
}

// CreateAccessToken create access tokens
func CreateAccessToken(ctx *context.APIContext) {
// swagger:operation POST /admin/users/{username}/tokens admin adminCreateAccessToken
// ---
// summary: Create an access token for {username} by admin
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - name: username
// in: path
// description: username of user
// type: string
// required: true
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/CreateAccessTokenOption"
// responses:
// "201":
// "$ref": "#/responses/AccessToken"
// "400":
// "$ref": "#/responses/error"

form := web.GetForm(ctx).(*api.CreateAccessTokenOption)

t := &auth.AccessToken{
UID: ctx.ContextUser.ID,
Name: form.Name,
}

exist, err := auth.AccessTokenByNameExists(t)
if err != nil {
ctx.InternalServerError(err)
return
}
if exist {
ctx.Error(http.StatusBadRequest, "AccessTokenByNameExists", errors.New("access token name has been used already"))
return
}

scope, err := auth.AccessTokenScope(strings.Join(form.Scopes, ",")).Normalize()
if err != nil {
ctx.Error(http.StatusBadRequest, "AccessTokenScope.Normalize", fmt.Errorf("invalid access token scope provided: %w", err))
return
}
t.Scope = scope

if err := auth.NewAccessToken(t); err != nil {
ctx.Error(http.StatusInternalServerError, "NewAccessToken", err)
return
}
ctx.JSON(http.StatusCreated, &api.AccessToken{
Name: t.Name,
Token: t.Token,
ID: t.ID,
TokenLastEight: t.TokenLastEight,
})
}

// DeleteAccessToken delete access tokens
func DeleteAccessToken(ctx *context.APIContext) {
// swagger:operation DELETE /admin/users/{username}/tokens/{token} admin adminDeleteAccessToken
// ---
// summary: delete an access token of {username} by admin
// produces:
// - application/json
// parameters:
// - name: username
// in: path
// description: username of user
// type: string
// required: true
// - name: token
// in: path
// description: token to be deleted, identified by ID and if not available by name
// type: string
// required: true
// responses:
// "204":
// "$ref": "#/responses/empty"
// "404":
// "$ref": "#/responses/notFound"
// "422":
// "$ref": "#/responses/error"

token := ctx.Params(":id")
tokenID, _ := strconv.ParseInt(token, 0, 64)

if tokenID == 0 {
tokens, err := auth.ListAccessTokens(auth.ListAccessTokensOptions{
Name: token,
UserID: ctx.ContextUser.ID,
})
if err != nil {
ctx.Error(http.StatusInternalServerError, "ListAccessTokens", err)
return
}

switch len(tokens) {
case 0:
ctx.NotFound()
return
case 1:
tokenID = tokens[0].ID
default:
ctx.Error(http.StatusUnprocessableEntity, "DeleteAccessTokenByID", fmt.Errorf("multiple matches for token name '%s'", token))
return
}
}
if tokenID == 0 {
ctx.Error(http.StatusInternalServerError, "Invalid TokenID", nil)
return
}

if err := auth.DeleteAccessTokenByID(tokenID, ctx.Doer.ID); err != nil {
if auth.IsErrAccessTokenNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "DeleteAccessTokenByID", err)
}
return
}

ctx.Status(http.StatusNoContent)
}
28 changes: 24 additions & 4 deletions routers/api/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -797,11 +797,10 @@ func Routes() *web.Route {

m.Get("/repos", tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository), reqExploreSignIn(), user.ListUserRepos)
m.Group("/tokens", func() {
m.Combo("").Get(user.ListAccessTokens).
Post(bind(api.CreateAccessTokenOption{}), reqToken(), user.CreateAccessToken)
m.Combo("/{id}").Delete(reqToken(), user.DeleteAccessToken)
m.Combo("").Get(user.ListAccessTokensDeprecated).
Post(bind(api.CreateAccessTokenOption{}), reqToken(), user.CreateAccessTokenDeprecated)
m.Combo("/{id}").Delete(reqToken(), user.DeleteAccessTokenDeprecated)
}, reqBasicAuth())

m.Get("/activities/feeds", user.ListUserActivityFeeds)
}, context_service.UserAssignmentAPI())
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser))
Expand All @@ -824,6 +823,15 @@ func Routes() *web.Route {
}, context_service.UserAssignmentAPI())
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser), reqToken())

// User (requires user scope)
m.Group("user", func() {
m.Group("/tokens", func() {
m.Combo("").Get(user.ListAccessTokens).
Post(bind(api.CreateAccessTokenOption{}), reqToken(), user.CreateAccessToken)
m.Combo("/{id}").Delete(reqToken(), user.DeleteAccessToken)
}, reqBasicAuth())
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser))

// Users (requires user scope)
m.Group("/user", func() {
m.Get("", user.GetAuthenticatedUser)
Expand Down Expand Up @@ -1350,6 +1358,18 @@ func Routes() *web.Route {
m.Get("/activities/feeds", org.ListTeamActivityFeeds)
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization), orgAssignment(false, true), reqToken(), reqTeamMembership())

m.Group("/admin", func() {
m.Group("/users", func() {
m.Group("/{username}", func() {
m.Group("/tokens", func() {
m.Combo("").Get(admin.ListAccessTokens).
Post(bind(api.CreateAccessTokenOption{}), reqToken(), admin.CreateAccessToken)
m.Combo("/{id}").Delete(reqToken(), admin.DeleteAccessToken)
})
}, context_service.UserAssignmentAPI())
})
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryAdmin), reqBasicAuth(), reqSiteAdmin())

m.Group("/admin", func() {
m.Group("/cron", func() {
m.Get("", admin.ListCronTasks)
Expand Down
Loading