277 lines
8.5 KiB
Go
277 lines
8.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
"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 validateToken(tokenString string) (*jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method")
|
|
}
|
|
return []byte(os.Getenv("JWT_SECRET")), nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
return &claims, nil
|
|
}
|
|
|
|
return nil, fmt.Errorf("invalid token")
|
|
}
|
|
|
|
func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
authHeader := c.Request().Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Authorization header required"})
|
|
}
|
|
|
|
bearerToken := strings.Split(authHeader, " ")
|
|
if len(bearerToken) != 2 || bearerToken[0] != "Bearer" {
|
|
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid authorization format"})
|
|
}
|
|
|
|
claims, err := validateToken(bearerToken[1])
|
|
if err != nil {
|
|
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "Invalid token"})
|
|
}
|
|
|
|
c.Set("user_id", int((*claims)["user_id"].(float64)))
|
|
c.Set("username", (*claims)["username"].(string))
|
|
return next(c)
|
|
}
|
|
}
|
|
|
|
func HandleSendTermail(c echo.Context) error {
|
|
var req db.SendTermailRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
|
|
}
|
|
|
|
if req.ReceiverUsername == "" || req.Subject == "" || req.Content == "" {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Receiver username, subject, and content are required"})
|
|
}
|
|
|
|
senderID := c.Get("user_id").(int)
|
|
termail, err := db.SendTermail(c.Request().Context(), senderID, req)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "user not found") {
|
|
return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
|
|
}
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to send termail"})
|
|
}
|
|
|
|
return c.JSON(http.StatusCreated, map[string]any{
|
|
"message": "Termail sent successfully",
|
|
"termail": termail,
|
|
})
|
|
}
|
|
|
|
func HandleGetInbox(c echo.Context) error {
|
|
userID := c.Get("user_id").(int)
|
|
|
|
limit := 10
|
|
if l := c.QueryParam("limit"); l != "" {
|
|
if parsed, err := strconv.Atoi(l); err == nil {
|
|
limit = parsed
|
|
}
|
|
}
|
|
|
|
offset := 0
|
|
if o := c.QueryParam("offset"); o != "" {
|
|
if parsed, err := strconv.Atoi(o); err == nil {
|
|
offset = parsed
|
|
}
|
|
}
|
|
|
|
search := c.QueryParam("search")
|
|
var termails []db.Termail
|
|
var err error
|
|
|
|
if search != "" {
|
|
termails, err = db.SearchTermails(c.Request().Context(), userID, search, limit, offset)
|
|
} else {
|
|
termails, err = db.GetInbox(c.Request().Context(), userID, limit, offset)
|
|
}
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to fetch inbox"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]any{
|
|
"termails": termails,
|
|
"count": len(termails),
|
|
})
|
|
}
|
|
|
|
func HandleGetTermail(c echo.Context) error {
|
|
userID := c.Get("user_id").(int)
|
|
termailID, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid termail ID"})
|
|
}
|
|
|
|
termail, err := db.GetTermail(c.Request().Context(), termailID, userID)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "no rows") {
|
|
return c.JSON(http.StatusNotFound, map[string]string{"error": "Termail not found"})
|
|
}
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to fetch termail"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]any{
|
|
"termail": termail,
|
|
})
|
|
}
|
|
|
|
func HandleMarkTermailRead(c echo.Context) error {
|
|
userID := c.Get("user_id").(int)
|
|
termailID, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid termail ID"})
|
|
}
|
|
|
|
err = db.MarkTermailAsRead(c.Request().Context(), termailID, userID)
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to mark termail as read"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]string{"message": "Termail marked as read"})
|
|
}
|
|
|
|
func HandleDeleteTermail(c echo.Context) error {
|
|
userID := c.Get("user_id").(int)
|
|
termailID, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid termail ID"})
|
|
}
|
|
|
|
err = db.DeleteTermail(c.Request().Context(), termailID, userID)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "not found") {
|
|
return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
|
|
}
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "Failed to delete termail"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]string{"message": "Termail deleted"})
|
|
}
|
|
|
|
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,
|
|
})
|
|
}
|