added login api

This commit is contained in:
2025-01-25 17:39:13 +01:00
parent 57acac6dae
commit b6b92d38be
6 changed files with 124 additions and 31 deletions

View File

@@ -1,11 +1,12 @@
package handlers
import (
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"log"
"os"
"relay-server/config"
"relay-server/database"
"relay-server/helpers"
"relay-server/models"
@@ -25,12 +26,10 @@ func Signup(c *fiber.Ctx) error {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "password is empty"})
}
// Checks if passwords have valid length and characters
// Checks if passwords or username have valid length and characters
if !helpers.IsValidPassword(u.Password) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid password"})
}
// Checks if username have valid length and characters
if !helpers.IsValidUsername(u.Username) {
} else if !helpers.IsValidUsername(u.Username) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid username"})
}
@@ -41,9 +40,9 @@ func Signup(c *fiber.Ctx) error {
}
// Create password hash
passwordHash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
passwordHash, err := bcrypt.GenerateFromPassword([]byte(u.Password), config.BCRYPT_COST)
if err != nil {
log.Printf("error hashing password: %v", err)
fmt.Printf("error hashing password: %v", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "internal server error"})
}
@@ -70,5 +69,60 @@ func Signup(c *fiber.Ctx) error {
// If everything went well sent username and user_id assigned by database
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Successfully signed up", "username": u.Username, "user_id": userId})
}
func Login(c *fiber.Ctx) error {
db, _ := database.InitDatabase()
u := new(models.LoginStruct)
if err := c.BodyParser(u); err != nil {
return err
}
// Checks if username or passwords are empty
if u.Username == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "username is empty"})
} else if u.Password == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "password is empty"})
}
// Checks if username or passwords have valid length and characters
if !helpers.IsValidUsername(u.Username) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid username"})
} else if !helpers.IsValidPassword(u.Password) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid password"})
}
// Checks if username exist in database
exist, _ := database.CheckUserExists(db, u.Username)
if !exist {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "user does not exists"})
}
// Verifies password matching
passwordHash, _ := database.GetPasswordHash(db, u.Password)
if bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(u.Password)) != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid password"})
}
userId, err := database.GetUserId(db, u.Username)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "internal server error"})
}
// Generate token with user id and username
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userId,
"username": u.Username,
})
// Sign token
signedToken, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
// Set token to cookies
cookie := new(fiber.Cookie)
cookie.Name = "token"
cookie.Value = signedToken
cookie.Expires = time.Now().Add(30 * 24 * time.Hour)
cookie.HTTPOnly = true
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Successfully signed up", "username": u.Username, "user_id": userId})
}