Files
relay-server/handlers/auth.go

168 lines
5.3 KiB
Go

package handlers
import (
"errors"
"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"
"time"
)
func Signup(c *fiber.Ctx) error {
type SignupStruct struct {
Username string `json:"username" xml:"username" form:"username"`
Password string `json:"password" xml:"password" form:"password"`
}
db := database.DB
u := new(SignupStruct)
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"})
}
if u.Password == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "password is empty"})
}
// 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"})
}
if !helpers.IsValidUsername(u.Username) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid username"})
}
// Checks if username already exist in database
exist, _ := database.CheckUserExists(db, u.Username)
if exist {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "user already exists"})
}
// Create password hash
passwordHash, err := bcrypt.GenerateFromPassword([]byte(u.Password), config.BCRYPT_COST)
if err != nil {
log.Printf("error hashing password: %w\n", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "internal server error"})
}
// Insert username and password hash to database
userID, err := database.InsertUser(db, u.Username, string(passwordHash))
if err != nil {
log.Print(err)
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
tokenCookie := new(fiber.Cookie)
tokenCookie.Name = "token"
tokenCookie.Value = signedToken
tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour)
//tokenCookie.HTTPOnly = true
c.Cookie(tokenCookie)
// 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 {
type loginStruct struct {
Username string `json:"username" xml:"username" form:"username"`
Password string `json:"password" xml:"password" form:"password"`
}
db := database.DB
u := new(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"})
}
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"})
}
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, err := database.GetPasswordHash(db, u.Username)
if err != nil {
log.Printf("error getting password: %w\n", err)
}
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 {
var e *helpers.Error
if errors.As(err, &e) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "user does not exist"})
}
log.Println(err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "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
tokenCookie := new(fiber.Cookie)
tokenCookie.Name = "token"
tokenCookie.Value = signedToken
tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour)
c.Cookie(tokenCookie)
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Successfully logged in", "username": u.Username, "user_id": userID})
}
func ValidateToken(c *fiber.Ctx) error {
username := c.Locals("username").(string)
userID := c.Locals("userID").(string)
//log.Printf("userID: %v, username: %v", userID, username)
//if userID == "" || username == "" {
// log.Printf("userID or username is empty %v", c.Locals("username"))
// return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid token"})
//}
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "authorized", "username": username, "user_id": userID})
}