Files
zeekayandHanzo Dev aa87442fdd Record upstream authorship centrally in NOTICE instead of in every file header
Source files keep their SPDX-License-Identifier and Hanzo copyright line; the
Gitea, Gogs and LFS Test Server copyrights they used to repeat now live once in
NOTICE, alongside LICENSE. The header lint accepts any copyright line above the
SPDX line, so it no longer demands an upstream one.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-10 17:50:35 -07:00

89 lines
2.5 KiB
Go

// Copyright 2026 Hanzo AI, Inc. All rights reserved.
// SPDX-License-Identifier: MIT
package token
import (
"errors"
"net/http"
auth_model "github.com/hanzoai/git/models/auth"
user_model "github.com/hanzoai/git/models/user"
"github.com/hanzoai/git/modules/auth/httpauth"
api "github.com/hanzoai/git/modules/structs"
"github.com/hanzoai/git/modules/util"
"github.com/hanzoai/git/services/context"
)
// GetCurrentToken returns metadata about the currently authenticated token.
func GetCurrentToken(ctx *context.APIContext) {
// swagger:operation GET /token miscellaneous getCurrentToken
// ---
// summary: Get the currently authenticated token
// produces:
// - application/json
// responses:
// "200":
// "$ref": "#/responses/CurrentAccessToken"
accessToken, err := getToken(ctx)
if err != nil {
ctx.APIErrorAuto(err)
return
}
// Get user info
user, err := user_model.GetUserByID(ctx, accessToken.UID)
if err != nil {
ctx.APIErrorAuto(err)
return
}
ctx.JSON(http.StatusOK, &api.CurrentAccessToken{
ID: accessToken.ID,
Name: accessToken.Name,
Scopes: accessToken.Scope.StringSlice(),
CreatedAt: accessToken.CreatedUnix.AsTime(),
LastUsedAt: accessToken.UpdatedUnix.AsTime(),
User: &api.UserMeta{
ID: user.ID,
Login: user.Name,
},
})
}
// DeleteCurrentToken deletes the currently authenticated token.
func DeleteCurrentToken(ctx *context.APIContext) {
// swagger:operation DELETE /token miscellaneous deleteCurrentToken
// ---
// summary: Delete the currently authenticated token
// produces:
// - application/json
// responses:
// "204":
// description: token deleted
accessToken, err := getToken(ctx)
if err != nil {
ctx.APIErrorAuto(err)
return
}
// Delete the token
err = auth_model.DeleteAccessTokenByID(ctx, accessToken.ID, accessToken.UID)
if err != nil && !errors.Is(err, util.ErrNotExist) {
ctx.APIErrorAuto(err)
return
}
ctx.Status(http.StatusNoContent)
}
// getToken retrieves an access token from the API context's Authorization header and validates it against the database.
// Returns nil if the token is invalid and handles the response
func getToken(ctx *context.APIContext) (*auth_model.AccessToken, error) {
authHeader := ctx.Req.Header.Get("Authorization")
parsed, ok := httpauth.ParseAuthorizationHeader(authHeader)
if !ok || parsed.BearerToken == nil {
return nil, util.NewNotExistErrorf("invalid access token")
}
return auth_model.GetAccessTokenBySHA(ctx, parsed.BearerToken.Token)
}