package v1 import ( "net/http" "strings" "time" "git.jamestombleson.com/jtom38/newsbot-api/domain" "git.jamestombleson.com/jtom38/newsbot-api/internal/repository" "github.com/google/uuid" "github.com/labstack/echo/v4" ) const ( ErrUserNotFound = "requested user does not exist" ErrUsernameAlreadyExists = "the requested username already exists" ) // @Summary Creates a new user // @Router /v1/users/register [post] // @Param request formData domain.LoginFormRequest true "form" // @Accepts x-www-form-urlencoded // @Produce json // @Tags Users // @Success 201 {object} domain.BaseResponse // @Failure 400 {object} domain.BaseResponse // @Failure 500 {object} domain.BaseResponse func (h *Handler) AuthRegister(c echo.Context) error { p := domain.BaseResponse{ Message: ResponseMessageSuccess, IsError: true, } 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 { p.Message = err.Error() return c.JSON(http.StatusBadRequest, p) } } if exists.Username == username { p.Message = ErrUsernameAlreadyExists return c.JSON(http.StatusInternalServerError, p) } //password := c.QueryParam("password") err = h.repo.Users.CheckPasswordForRequirements(password) if err != nil { p.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } _, err = h.repo.Users.Create(c.Request().Context(), username, password, domain.ScopeArticleRead) if err != nil { p.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } return c.JSON(http.StatusCreated, p) } // @Summary Logs into the API and returns a bearer token if successful // @Router /v1/users/login [post] // @Param request formData domain.LoginFormRequest true "form" // @Accepts x-www-form-urlencoded // @Produce json // @Tags Users // @Success 200 {object} domain.LoginResponse // @Failure 400 {object} domain.LoginResponse // @Failure 500 {object} domain.LoginResponse func (h *Handler) AuthLogin(c echo.Context) error { p := domain.LoginResponse{ BaseResponse: domain.BaseResponse{ Message: ResponseMessageSuccess, IsError: true, }, //Token: jwt, Type: "Bearer", //RefreshToken: refresh, } 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.createAdminToken(c, password) } // check if the user exists user, err := h.repo.Users.GetUser(c.Request().Context(), username) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } // make sure the hash matches err = h.repo.Users.DoesPasswordMatchHash(c.Request().Context(), username, password) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } // TODO think about moving this down some? expiresAt := time.Now().Add(time.Hour * 48) userScopes := strings.Split(user.Scopes, ",") jwt, err := h.generateJwtWithExp(username, h.config.ServerAddress, user.SessionToken, userScopes, user.ID, expiresAt) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } refresh, err := h.repo.RefreshTokens.Create(c.Request().Context(), username) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } p.Token = jwt p.RefreshToken = refresh p.BaseResponse.IsError = false return c.JSON(http.StatusOK, p) } func (h *Handler) createAdminToken(c echo.Context, password string) error { p := domain.LoginResponse{ BaseResponse: domain.BaseResponse{ Message: ResponseMessageSuccess, IsError: true, }, //Token: token, Type: "Bearer", } // if the admin token is blank, then the admin wanted this disabled. // this will fail right away and not progress. if h.config.AdminSecret == "" { p.BaseResponse.Message = ErrUserNotFound return c.JSON(http.StatusBadRequest, p) } if h.config.AdminSecret != password { p.BaseResponse.Message = ErrUserNotFound return c.JSON(http.StatusBadRequest, p) } var userScopes []string userScopes = append(userScopes, domain.ScopeAll) sessionToken, err := uuid.NewV7() if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } token, err := h.generateJwt("admin", h.config.ServerAddress, sessionToken.String(), userScopes, -1) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } p.Token = token p.BaseResponse.IsError = false return c.JSON(http.StatusOK, p) } // This will take collect some information about the requested refresh, validate and then return a new jwt token if approved. // Register // @Summary Generates a new token // @Router /v1/users/refresh/token [post] // @Param request body domain.RefreshTokenRequest true "body" // @Tags Users // @Success 200 {object} domain.LoginResponse // @Failure 400 {object} domain.BaseResponse // @Failure 500 {object} domain.BaseResponse // @Security Bearer func (h *Handler) RefreshJwtToken(c echo.Context) error { p := domain.LoginResponse{ BaseResponse: domain.BaseResponse{ Message: "OK", }, //Token: jwt, Type: "Bearer", //RefreshToken: newRefreshToken, } _, err := h.ValidateJwtToken(c, domain.ScopeDiscordWebHookCreate) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusUnauthorized, p) } // Check the context for the refresh token var request domain.RefreshTokenRequest err = (&echo.DefaultBinder{}).BindBody(c, &request) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } err = h.repo.RefreshTokens.IsRequestValid(c.Request().Context(), request.Username, request.RefreshToken) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } user, err := h.repo.Users.GetUser(c.Request().Context(), request.Username) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } userScopes := strings.Split(user.Scopes, ",") jwt, err := h.generateJwtWithExp(request.Username, h.config.ServerAddress, user.SessionToken, userScopes, user.ID, time.Now().Add(time.Hour*48)) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } newRefreshToken, err := h.repo.RefreshTokens.Create(c.Request().Context(), request.Username) if err != nil { p.BaseResponse.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } p.Token = jwt p.RefreshToken = newRefreshToken p.BaseResponse.IsError = false return c.JSON(http.StatusOK, p) } // @Summary Adds a new scope to a user account // @Router /v1/users/scopes/add [post] // @Param request body domain.UpdateScopesRequest true "body" // @Tags Users // @Accept json // @Produce json // @Success 200 {object} domain.BaseResponse // @Failure 400 {object} domain.BaseResponse // @Failure 500 {object} domain.BaseResponse // @Security Bearer func (h *Handler) AddScopes(c echo.Context) error { p := domain.BaseResponse{ Message: ResponseMessageSuccess, IsError: true, } _, err := h.ValidateJwtToken(c, domain.ScopeAll) if err != nil { p.Message = err.Error() return c.JSON(http.StatusUnauthorized, p) } request := domain.UpdateScopesRequest{} err = (&echo.DefaultBinder{}).BindBody(c, &request) if err != nil { p.Message = err.Error() return c.JSON(http.StatusBadRequest, p) } err = h.repo.Users.AddScopes(c.Request().Context(), request.Username, request.Scopes) if err != nil { p.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } p.IsError = false return c.JSON(http.StatusOK, p) } // @Summary Adds a new scope to a user account // @Router /v1/users/scopes/remove [post] // @Param request body domain.UpdateScopesRequest true "body" // @Tags Users // @Accept json // @Produce json // @Success 200 {object} domain.BaseResponse // @Failure 400 {object} domain.BaseResponse // @Failure 500 {object} domain.BaseResponse // @Security Bearer func (h *Handler) RemoveScopes(c echo.Context) error { p := domain.BaseResponse{ Message: ResponseMessageSuccess, IsError: true, } token, err := h.getJwtTokenFromContext(c) if err != nil { p.Message = err.Error() return c.JSON(http.StatusUnauthorized, p) } err = token.IsValid(domain.ScopeAll) if err != nil { p.Message = err.Error() return c.JSON(http.StatusBadRequest, p) } request := domain.UpdateScopesRequest{} err = (&echo.DefaultBinder{}).BindBody(c, &request) if err != nil { p.Message = err.Error() return c.JSON(http.StatusBadRequest, p) } err = h.repo.Users.RemoveScopes(c.Request().Context(), request.Username, request.Scopes) if err != nil { p.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } p.IsError = false return c.JSON(http.StatusOK, p) } // @Summary Revokes the current session token and replaces it with a new one. // @Router /v1/users/refresh/sessionToken [post] // @Tags Users // @Accept json // @Produce json // @Success 200 {object} domain.BaseResponse // @Failure 400 {object} domain.BaseResponse // @Failure 500 {object} domain.BaseResponse // @Security Bearer func (h *Handler) NewSessionToken(c echo.Context) error { p := domain.BaseResponse{ Message: ResponseMessageSuccess, IsError: true, } token, err := h.getJwtTokenFromContext(c) if err != nil { p.Message = err.Error() return c.JSON(http.StatusUnauthorized, p) } _, err = h.repo.Users.NewSessionToken(c.Request().Context(), token.UserName) if err != nil { p.Message = err.Error() return c.JSON(http.StatusInternalServerError, p) } p.IsError = false return c.JSON(http.StatusInternalServerError, p) }