go-cook/internal/handlers/v1/auth.go

240 lines
6.2 KiB
Go

package v1
import (
"errors"
"net/http"
"time"
"git.jamestombleson.com/jtom38/go-cook/internal/domain"
"git.jamestombleson.com/jtom38/go-cook/internal/repositories"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
)
const (
ErrJwtMissing = "auth token is missing"
ErrJwtClaimsMissing = "claims missing on token"
ErrJwtExpired = "auth token has expired"
ErrJwtScopeMissing = "required scope is missing"
ErrUserNotFound = "requested user does not exist"
ErrUsernameAlreadyExists = "the requested username already exists"
)
func (h *Handler) AuthRegister(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")
//username := c.QueryParam("username")
exists, err := h.users.GetUser(username)
if err != nil {
// if we have an err, validate that if its not user not found.
// if the user is not found, we can use that name
if err.Error() != repositories.ErrUserNotFound {
return c.JSON(http.StatusInternalServerError, domain.ErrorResponse{
Message: err.Error(),
Success: true,
})
}
}
if exists.Name == username {
return h.InternalServerErrorResponse(c, ErrUsernameAlreadyExists)
}
//password := c.QueryParam("password")
err = h.users.CheckPasswordForRequirements(password)
if err != nil {
return c.JSON(http.StatusInternalServerError, domain.ErrorResponse{
Success: false,
Message: err.Error(),
})
}
_, err = h.users.Create(username, password, domain.ScopeRecipeRead)
if err != nil {
return c.JSON(http.StatusInternalServerError, domain.ErrorResponse{
Success: false,
Message: err.Error(),
})
}
return c.JSON(http.StatusCreated, domain.ErrorResponse{
Success: true,
})
}
func (h *Handler) AuthLogin(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")
// Check to see if they are trying to login with the admin token
if username == "" {
return h.validateAdminToken(c, password)
}
// check if the user exists
err := h.users.DoesUserExist(username)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
// make sure the hash matches
err = h.users.DoesPasswordMatchHash(username, password)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
// TODO think about moving this down some?
expiresAt := time.Now().Add(time.Hour * 48)
jwt, err := h.generateJwtWithExp(username, h.Config.ApiUri, expiresAt)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
refresh, err := h.refreshTokens.Create(username)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
return c.JSON(http.StatusOK, domain.LoginResponse{
BaseResponse: domain.BaseResponse{
Success: true,
Message: "OK",
},
Token: jwt,
Type: "Bearer",
RefreshToken: refresh,
})
}
func (h *Handler) validateAdminToken(c echo.Context, password string) error {
// if the admin token is blank, then the admin wanted this disabled.
// this will fail right away and not progress.
if h.Config.AdminToken == "" {
return h.InternalServerErrorResponse(c, ErrUserNotFound)
}
if h.Config.AdminToken != password {
return h.ReturnUnauthorizedResponse(c, ErrUserNotFound)
}
token, err := h.generateJwt("admin", h.Config.ApiUri)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
return c.JSON(http.StatusOK, token)
}
// This will take collect some information about the requested refresh, validate and then return a new jwt token if approved.
func (h *Handler) RefreshJwtToken(c echo.Context) error {
// Check the context for the refresh token
var request domain.RefreshTokenRequest
err := (&echo.DefaultBinder{}).BindBody(c, &request)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
err = h.refreshTokens.IsRequestValid(request.Username, request.RefreshToken)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
jwt, err := h.generateJwtWithExp(request.Username, h.Config.ApiUri, time.Now().Add(time.Hour * 48))
if err!= nil {
return h.InternalServerErrorResponse(c, err.Error())
}
newRefreshToken, err := h.refreshTokens.Create(request.Username)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
return c.JSON(http.StatusOK, domain.LoginResponse{
BaseResponse: domain.BaseResponse{
Success: true,
Message: "OK",
},
Token: jwt,
Type: "Bearer",
RefreshToken: newRefreshToken,
})
}
func (h *Handler) AddScopes(c echo.Context) error {
token, err := h.getJwtToken(c)
if err != nil {
return h.ReturnUnauthorizedResponse(c, err.Error())
}
err = token.IsValid(domain.ScopeAll)
if err != nil {
return h.ReturnUnauthorizedResponse(c, err.Error())
}
request := domain.UpdateScopesRequest{}
err = (&echo.DefaultBinder{}).BindBody(c, &request)
if err != nil {
return c.JSON(http.StatusBadRequest, domain.ErrorResponse{
Success: false,
Message: err.Error(),
})
}
err = h.users.AddScopes(request.Username, request.Scopes)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
return c.JSON(http.StatusOK, domain.ErrorResponse{
Success: true,
})
}
func (h *Handler) RemoveScopes(c echo.Context) error {
token, err := h.getJwtToken(c)
if err != nil {
return h.ReturnUnauthorizedResponse(c, err.Error())
}
err = token.IsValid(domain.ScopeAll)
if err != nil {
return h.ReturnUnauthorizedResponse(c, err.Error())
}
request := domain.UpdateScopesRequest{}
err = (&echo.DefaultBinder{}).BindBody(c, &request)
if err != nil {
return c.JSON(http.StatusBadRequest, domain.ErrorResponse{
Success: false,
Message: err.Error(),
})
}
err = h.users.RemoveScopes(request.Username, request.Scopes)
if err != nil {
return h.InternalServerErrorResponse(c, err.Error())
}
return c.JSON(http.StatusOK, domain.ErrorResponse{
Success: true,
})
}
func (h *Handler) getJwtToken(c echo.Context) (JwtToken, error) {
// Make sure that the request came with a jwtToken
token, ok := c.Get("user").(*jwt.Token)
if !ok {
return JwtToken{}, errors.New(ErrJwtMissing)
}
// Generate the claims from the token
claims, ok := token.Claims.(*JwtToken)
if !ok {
return JwtToken{}, errors.New(ErrJwtClaimsMissing)
}
return *claims, nil
}