newsbot-portal/internal/handlers/users.go

90 lines
2.3 KiB
Go

package handlers
import (
"fmt"
"net/http"
"git.jamestombleson.com/jtom38/newsbot-portal/internal/domain"
"git.jamestombleson.com/jtom38/newsbot-portal/internal/models"
"git.jamestombleson.com/jtom38/newsbot-portal/internal/views/users"
"github.com/labstack/echo/v4"
)
func (h *Handler) UserLogin(c echo.Context) error {
return Render(c, http.StatusOK, users.Login())
}
func (h *Handler) UserAfterLogin(c echo.Context) error {
user := c.FormValue("username")
password := c.FormValue("password")
resp, err := h.api.Users.Login(user, password)
if err != nil {
return Render(c, http.StatusBadRequest, users.AfterLogin(models.AfterLoginViewModel{
Success: false,
Message: err.Error(),
}))
}
if user == "" {
user = "admin"
}
SetCookie(c, domain.CookieToken, resp.Token, "/")
SetCookie(c, domain.CookieRefreshToken, resp.RefreshToken, "/")
SetCookie(c, domain.CookieUser, user, "/")
vm := models.AfterLoginViewModel{
Success: true,
Message: "Login Successful!",
}
return Render(c, http.StatusOK, users.AfterLogin(vm))
}
func (h *Handler) UserSignUp(c echo.Context) error {
return Render(c, http.StatusOK, users.SignUp())
}
func (h *Handler) UserAfterSignUp(c echo.Context) error {
user := c.FormValue("username")
password := c.FormValue("password")
resp, err := h.api.Users.SignUp(user, password)
if err != nil {
return Render(c, http.StatusBadRequest, users.AfterLogin(models.AfterLoginViewModel{
Success: false,
Message: err.Error(),
}))
}
if resp.Message != "OK" {
msg := fmt.Sprintf("Failed to create account. Message: %s", resp.Message)
return Render(c, http.StatusBadRequest, users.AfterLogin(models.AfterLoginViewModel{
Message: msg,
Success: false,
}))
}
return Render(c, http.StatusOK, users.AfterSignUp("Registration Successful!", true))
}
func (h *Handler) UserProfile(c echo.Context) error {
return Render(c, http.StatusOK, users.Profile())
}
func (h *Handler) ForceLogout(c echo.Context) error {
err := IsLoggedIn(c)
if err != nil {
return RenderError(c, err)
}
h.api.Users.RefreshSessionToken(GetJwtToken(c))
return nil
}
func (h *Handler) UsersLogout(c echo.Context) error {
SetCookie(c, domain.CookieUser, "", "/")
SetCookie(c, domain.CookieRefreshToken, "", "/")
SetCookie(c, domain.CookieToken, "", "/")
return Render(c, http.StatusOK, users.Logout())
}