Use AbortWithStatusJSON instead of AbortWithError
All checks were successful
continuous-integration/drone/pr Build is passing
ci/woodpecker/push/woodpecker Pipeline was successful
continuous-integration/drone/push Build is passing
ci/woodpecker/pr/woodpecker Pipeline was successful

This commit is contained in:
2022-02-20 20:42:57 +00:00
parent 36b2f12183
commit ca51ac5e27
4 changed files with 23 additions and 16 deletions

View File

@ -11,16 +11,21 @@ import (
"github.com/google/uuid"
)
func (h *Handler) verifyLogin(c *gin.Context) (budgeteer.Token, error) {
tokenString := c.GetHeader("Authorization")
if len(tokenString) < 8 {
return nil, fmt.Errorf("no authorization header supplied")
const (
HeaderName = "Authorization"
Bearer = "Bearer "
)
func (h *Handler) verifyLogin(c *gin.Context) (budgeteer.Token, *ErrorResponse) { //nolint:ireturn
tokenString := c.GetHeader(HeaderName)
if len(tokenString) <= len(Bearer) {
return nil, &ErrorResponse{"no authorization header supplied"}
}
tokenString = tokenString[7:]
token, err := h.TokenVerifier.VerifyToken(tokenString)
if err != nil {
return nil, fmt.Errorf("verify token '%s': %w", tokenString, err)
return nil, &ErrorResponse{fmt.Sprintf("verify token '%s': %s", tokenString, err)}
}
return token, nil
@ -29,8 +34,8 @@ func (h *Handler) verifyLogin(c *gin.Context) (budgeteer.Token, error) {
func (h *Handler) verifyLoginWithForbidden(c *gin.Context) {
token, err := h.verifyLogin(c)
if err != nil {
//c.Header("WWW-Authenticate", "Bearer")
c.AbortWithError(http.StatusForbidden, err)
// c.Header("WWW-Authenticate", "Bearer")
c.AbortWithStatusJSON(http.StatusForbidden, err)
return
}
@ -104,18 +109,18 @@ func (h *Handler) registerPost(c *gin.Context) {
var register registerInformation
err := c.BindJSON(&register)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("parse body: %w", err))
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"error parsing body"})
return
}
if register.Email == "" || register.Password == "" || register.Name == "" {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("e-mail, password and name are required"))
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"e-mail, password and name are required"})
return
}
_, err = h.Service.GetUserByUsername(c.Request.Context(), register.Email)
if err == nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("email is already taken"))
c.AbortWithStatusJSON(http.StatusBadRequest, ErrorResponse{"email is already taken"})
return
}