fix(auth): return proper error when a jwt claim contains wrong data

Resolves https://vikunja.sentry.io/share/issue/69b578ccc3794de58cecfc7b8291ae64/
This commit is contained in:
kolaente
2025-01-14 16:38:49 +01:00
parent 33b9917c7d
commit 2522cffa61
2 changed files with 59 additions and 10 deletions

View File

@@ -534,9 +534,7 @@ func (err *ErrUsernameMustNotContainSpaces) HTTPError() web.HTTPError {
}
// ErrMustNotBeLinkShare represents a "MustNotBeLinkShare" kind of error.
type ErrMustNotBeLinkShare struct {
Username string
}
type ErrMustNotBeLinkShare struct{}
// IsErrMustNotBeLinkShare checks if an error is a ErrMustNotBeLinkShare.
func IsErrMustNotBeLinkShare(err error) bool {
@@ -559,3 +557,31 @@ func (err *ErrMustNotBeLinkShare) HTTPError() web.HTTPError {
Message: "You can't do that as a link share.",
}
}
// ErrInvalidClaimData represents a "InvalidClaimData" kind of error.
type ErrInvalidClaimData struct {
Field string
Type string
}
// IsErrInvalidClaimData checks if an error is a ErrInvalidClaimData.
func IsErrInvalidClaimData(err error) bool {
_, ok := err.(*ErrInvalidClaimData)
return ok
}
func (err *ErrInvalidClaimData) Error() string {
return fmt.Sprintf("invalid claim data for field %s of type %s", err.Field, err.Type)
}
// ErrCodeInvalidClaimData holds the unique world-error code of this error
const ErrCodeInvalidClaimData = 1024
// HTTPError holds the http error description
func (err *ErrInvalidClaimData) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeInvalidClaimData,
Message: fmt.Sprintf("Invalid claim data for field %s of type %s", err.Field, err.Type),
}
}

View File

@@ -446,16 +446,39 @@ func GetCurrentUser(c echo.Context) (user *User, err error) {
func GetUserFromClaims(claims jwt.MapClaims) (user *User, err error) {
userID, ok := claims["id"].(float64)
if !ok {
return user, ErrCouldNotGetUserID{}
return user, &ErrInvalidClaimData{
Field: "id",
Type: reflect.TypeOf(claims["id"]).String(),
}
}
user = &User{
ID: int64(userID),
Email: claims["email"].(string),
Username: claims["username"].(string),
Name: claims["name"].(string),
email, ok := claims["email"].(string)
if !ok {
return nil, &ErrInvalidClaimData{
Field: "email",
Type: reflect.TypeOf(claims["email"]).String(),
}
}
username, ok := claims["username"].(string)
if !ok {
return nil, &ErrInvalidClaimData{
Field: "username",
Type: reflect.TypeOf(claims["username"]).String(),
}
}
name, ok := claims["name"].(string)
if !ok {
return nil, &ErrInvalidClaimData{
Field: "name",
Type: reflect.TypeOf(claims["name"]).String(),
}
}
return
return &User{
ID: int64(userID),
Email: email,
Username: username,
Name: name,
}, nil
}
// UpdateUser updates a user