termbox/internal/handlers/handlers.go
Keiran b2c7dcae83 move auth commands to subcommands underneath auth
add tokens stored on the local device for persisting auth
2025-08-06 06:26:42 +01:00

118 lines
3.8 KiB
Go

package handlers
import (
"net/http"
"os"
"strings"
"time"
"git.keircn.com/keiran/termbox/internal/db"
"git.keircn.com/keiran/termbox/internal/email"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
)
var emailService *email.Service
func InitEmailService() {
emailService = email.NewService()
}
func generateToken(userID int, username string) (string, error) {
claims := jwt.MapClaims{
"user_id": userID,
"username": username,
"exp": time.Now().Add(time.Hour * 24 * 7).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(os.Getenv("JWT_SECRET")))
}
func HandleRoot(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}
func HandleRegister(c echo.Context) error {
if err := db.CleanupUnverifiedUsers(c.Request().Context()); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to cleanup old accounts"})
}
var req db.CreateUserRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
}
if req.Username == "" || req.Email == "" || req.Password == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Username, email, and password are required"})
}
user, err := db.CreateUser(c.Request().Context(), req)
if err != nil {
if strings.Contains(err.Error(), "duplicate") || strings.Contains(err.Error(), "unique") {
return c.JSON(http.StatusConflict, map[string]string{"error": "Username or email already exists"})
}
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to create user: " + err.Error()})
}
verificationCode, err := db.CreateVerificationCode(c.Request().Context(), user.ID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to create verification code"})
}
err = emailService.SendVerificationCode(c.Request().Context(), user.Email, user.Username, verificationCode.Code)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to send verification email"})
}
return c.JSON(http.StatusCreated, map[string]any{
"message": "User created successfully. Please check your email for verification code.",
"user": user,
})
}
func HandleVerifyCode(c echo.Context) error {
var req db.VerifyCodeRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
}
if req.Email == "" || req.Code == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Email and code are required"})
}
err := db.VerifyCode(c.Request().Context(), req.Email, req.Code)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
return c.JSON(http.StatusOK, map[string]string{"message": "Account verified successfully"})
}
func HandleLogin(c echo.Context) error {
var req db.LoginRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
}
if req.Username == "" || req.Password == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Username and password are required"})
}
user, err := db.ValidateUserCredentials(c.Request().Context(), req.Username, req.Password)
if err != nil {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid credentials or account not verified"})
}
token, err := generateToken(user.ID, user.Username)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to generate token"})
}
return c.JSON(http.StatusOK, map[string]any{
"message": "Login successful",
"user": user,
"token": token,
})
}