package v1 import ( "net/http" "time" "git.jamestombleson.com/jtom38/newsbot-api/internal/domain" "git.jamestombleson.com/jtom38/newsbot-api/internal/repository" "github.com/labstack/echo/v4" ) const ( ErrUserNotFound = "requested user does not exist" ErrUsernameAlreadyExists = "the requested username already exists" ) // Register // @Summary Creates a new user // @Tags Users // @Success 200 {object} domain.BaseResponse // @Failure 400 {object} domain.BaseResponse // @Failure 500 {object} domain.BaseResponse func (h *Handler) AuthRegister(c echo.Context) error { username := c.FormValue("username") password := c.FormValue("password") //username := c.QueryParam("username") exists, err := h.repo.Users.GetUser(c.Request().Context(), 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() != repository.ErrUserNotFound { return h.WriteError(c, err, http.StatusBadRequest) } } if exists.Username == username { return h.InternalServerErrorResponse(c, ErrUsernameAlreadyExists) } //password := c.QueryParam("password") err = h.repo.Users.CheckPasswordForRequirements(password) if err != nil { return h.WriteError(c, err, http.StatusInternalServerError) } _, err = h.repo.Users.Create(c.Request().Context(), username, password, domain.ScopeRead) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } return c.JSON(http.StatusCreated, domain.BaseResponse{ Message: "OK", }) } 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.repo.Users.DoesUserExist(c.Request().Context(), username) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } // make sure the hash matches err = h.repo.Users.DoesPasswordMatchHash(c.Request().Context(), 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.ServerAddress, expiresAt) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } refresh, err := h.repo.RefreshTokens.Create(c.Request().Context(), username) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } return c.JSON(http.StatusOK, domain.LoginResponse{ BaseResponse: domain.BaseResponse{ 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.AdminSecret == "" { return h.InternalServerErrorResponse(c, ErrUserNotFound) } if h.config.AdminSecret != password { return h.UnauthorizedResponse(c, ErrUserNotFound) } token, err := h.generateJwt("admin", h.config.ServerAddress) 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.repo.RefreshTokens.IsRequestValid(c.Request().Context(), request.Username, request.RefreshToken) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } jwt, err := h.generateJwtWithExp(request.Username, h.config.ServerAddress, time.Now().Add(time.Hour*48)) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } newRefreshToken, err := h.repo.RefreshTokens.Create(c.Request().Context(), request.Username) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } return c.JSON(http.StatusOK, domain.LoginResponse{ BaseResponse: domain.BaseResponse{ 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.UnauthorizedResponse(c, err.Error()) } err = token.IsValid(domain.ScopeAll) if err != nil { return h.UnauthorizedResponse(c, err.Error()) } request := domain.UpdateScopesRequest{} err = (&echo.DefaultBinder{}).BindBody(c, &request) if err != nil { h.WriteError(c, err, http.StatusBadRequest) } err = h.repo.Users.AddScopes(c.Request().Context(), request.Username, request.Scopes) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } return c.JSON(http.StatusOK, domain.BaseResponse{ Message: "OK", }) } func (h *Handler) RemoveScopes(c echo.Context) error { token, err := h.getJwtToken(c) if err != nil { return h.WriteError(c, err, http.StatusUnauthorized) } err = token.IsValid(domain.ScopeAll) if err != nil { return h.WriteError(c, err, http.StatusUnauthorized) } request := domain.UpdateScopesRequest{} err = (&echo.DefaultBinder{}).BindBody(c, &request) if err != nil { h.WriteError(c, err, http.StatusBadRequest) } err = h.repo.Users.RemoveScopes(c.Request().Context(), request.Username, request.Scopes) if err != nil { return h.InternalServerErrorResponse(c, err.Error()) } return c.JSON(http.StatusOK, domain.BaseResponse{ Message: "OK", }) }