zrok/controller/regenerateToken.go

64 lines
2.1 KiB
Go
Raw Normal View History

2024-01-25 16:55:45 +01:00
package controller
import (
"github.com/go-openapi/runtime/middleware"
"github.com/openziti/zrok/rest_model_zrok"
2024-01-25 16:55:45 +01:00
"github.com/openziti/zrok/rest_server_zrok/operations/account"
"github.com/sirupsen/logrus"
)
2024-02-20 17:40:11 +01:00
type regenerateTokenHandler struct{}
2024-01-25 16:55:45 +01:00
2024-02-20 17:40:11 +01:00
func newRegenerateTokenHandler() *regenerateTokenHandler {
return &regenerateTokenHandler{}
2024-01-25 16:55:45 +01:00
}
2024-02-20 17:40:11 +01:00
func (handler *regenerateTokenHandler) Handle(params account.RegenerateTokenParams, principal *rest_model_zrok.Principal) middleware.Responder {
2024-02-16 22:35:42 +01:00
logrus.Infof("received token regeneration request for email '%v'", principal.Email)
2024-01-25 16:55:45 +01:00
if params.Body.EmailAddress != principal.Email {
logrus.Errorf("mismatched account '%v' for '%v'", params.Body.EmailAddress, principal.Email)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenNotFound()
}
2024-01-25 16:55:45 +01:00
tx, err := str.Begin()
if err != nil {
logrus.Errorf("error starting transaction for '%v': %v", params.Body.EmailAddress, err)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenInternalServerError()
2024-01-25 16:55:45 +01:00
}
defer tx.Rollback()
a, err := str.FindAccountWithEmail(params.Body.EmailAddress, tx)
if err != nil {
logrus.Errorf("error finding account for '%v': %v", params.Body.EmailAddress, err)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenNotFound()
2024-01-25 16:55:45 +01:00
}
if a.Deleted {
logrus.Errorf("account '%v' for '%v' deleted", a.Email, a.Token)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenNotFound()
2024-01-25 16:55:45 +01:00
}
// Need to create new token and invalidate all other resources
token, err := CreateToken()
2024-01-31 21:35:28 +01:00
if err != nil {
logrus.Errorf("error creating token for request '%v': %v", params.Body.EmailAddress, err)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenInternalServerError()
2024-01-31 21:35:28 +01:00
}
a.Token = token
if _, err := str.UpdateAccount(a, tx); err != nil {
logrus.Errorf("error updating account for request '%v': %v", params.Body.EmailAddress, err)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenInternalServerError()
2024-01-31 21:35:28 +01:00
}
2024-01-25 16:55:45 +01:00
if err := tx.Commit(); err != nil {
logrus.Errorf("error committing '%v' (%v): %v", params.Body.EmailAddress, a.Email, err)
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenInternalServerError()
2024-01-25 16:55:45 +01:00
}
2024-02-16 22:35:42 +01:00
logrus.Infof("regenerated token '%v' for '%v'", a.Token, a.Email)
2024-01-25 16:55:45 +01:00
2024-02-20 17:40:11 +01:00
return account.NewRegenerateTokenOK().WithPayload(&account.RegenerateTokenOKBody{Token: token})
2024-01-25 16:55:45 +01:00
}