Add renew-route, shorten token lifetime

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2024-06-13 16:38:59 +02:00
parent 0e9027fa3f
commit bb46ba5d0e
Signed by: luzifer
SSH key fingerprint: SHA256:/xtE5lCgiRDQr8SLxHMS92ZBlACmATUmF1crK16Ks4E
2 changed files with 49 additions and 4 deletions

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"net/http"
"regexp"
"strings"
"time"
log "github.com/sirupsen/logrus"
@ -14,6 +15,14 @@ import (
const frontendNotifyTypeReload = "configReload"
type (
configEditorLoginResponse struct {
ExpiresAt time.Time `json:"expiresAt"`
Token string `json:"token"`
User string `json:"user"`
}
)
var frontendNotifyHooks = newHooker()
//nolint:funlen // Just contains a collection of objects
@ -73,6 +82,16 @@ func registerEditorGlobalMethods() {
Path: "/notify-config",
ResponseType: plugins.HTTPRouteResponseTypeTextPlain,
},
{
Description: "Takes the authorization token present in the request and returns a new one for the same user",
HandlerFunc: configEditorGlobalRefreshToken,
Method: http.MethodGet,
Module: moduleConfigEditor,
Name: "Refresh Auth-Token",
Path: "/refreshToken",
RequiresEditorsAuth: true,
ResponseType: plugins.HTTPRouteResponseTypeJSON,
},
{
Description: "Validate a cron expression and return the next executions",
HandlerFunc: configEditorGlobalValidateCron,
@ -187,9 +206,35 @@ func configEditorGlobalLogin(w http.ResponseWriter, r *http.Request) {
return
}
if err := json.NewEncoder(w).Encode(map[string]any{
"expiresAt": expiresAt,
"token": tok,
if err := json.NewEncoder(w).Encode(configEditorLoginResponse{
ExpiresAt: expiresAt,
Token: tok,
User: user,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func configEditorGlobalRefreshToken(w http.ResponseWriter, r *http.Request) {
tokenType, token, found := strings.Cut(r.Header.Get("Authorization"), " ")
if !found || !strings.EqualFold(tokenType, "bearer") {
http.Error(w, "invalid renew request", http.StatusBadRequest)
}
id, user, _, err := editorTokenService.ValidateLoginToken(token)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
tok, expiresAt, err := editorTokenService.CreateLoginToken(id, user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := json.NewEncoder(w).Encode(configEditorLoginResponse{
ExpiresAt: expiresAt,
Token: tok,
User: user,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}

View file

@ -15,7 +15,7 @@ import (
const (
coreMetaSigningKey = "editortoken:signing-key"
tokenValidity = 24 * time.Hour
tokenValidity = time.Hour
)
type (