code refactor, added contact post route

This commit is contained in:
slawk0
2025-02-04 19:53:43 +01:00
parent cd83870ab4
commit ca2debca31
9 changed files with 319 additions and 52 deletions

View File

@@ -1,10 +1,10 @@
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"
@@ -49,20 +49,20 @@ func Signup(c *fiber.Ctx) error {
// Create password hash
passwordHash, err := bcrypt.GenerateFromPassword([]byte(u.Password), config.BCRYPT_COST)
if err != nil {
fmt.Printf("error hashing password: %v\n", err)
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))
userID, err := database.InsertUser(db, u.Username, string(passwordHash))
if err != nil {
fmt.Printf("error inserting user: %v\n", err)
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,
"user_id": userID,
"username": u.Username,
})
// Sign token
@@ -77,7 +77,7 @@ func Signup(c *fiber.Ctx) error {
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})
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Successfully signed up", "username": u.Username, "user_id": userID})
}
func Login(c *fiber.Ctx) error {
@@ -117,19 +117,22 @@ func Login(c *fiber.Ctx) error {
}
// Verifies password matching
passwordHash, _ := database.GetPasswordHash(db, u.Username)
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)
userID, err := database.GetUserID(db, u.Username)
if err != nil {
fmt.Printf("error getting user id: %v\n", err)
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,
"user_id": userID,
"username": u.Username,
})
// Sign token
@@ -140,19 +143,20 @@ func Login(c *fiber.Ctx) error {
tokenCookie.Name = "token"
tokenCookie.Value = signedToken
tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour)
//tokenCookie.HTTPOnly = true
c.Cookie(tokenCookie)
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Successfully logged in", "username": u.Username, "user_id": userId})
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")
userId := c.Locals("user_id")
username := c.Locals("username").(string)
userID := c.Locals("userID").(string)
if userId == nil || username == nil {
fmt.Println("userId or username is nil")
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid token"})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "authorized", "username": c.Locals("username").(string), "user_id": 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})
}

View File

@@ -1,17 +1,21 @@
package handlers
import (
"database/sql"
"errors"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"log"
"relay-server/database"
"relay-server/helpers"
)
func DeleteContact(c *fiber.Ctx) error {
type params struct {
ContactId uuid.UUID `params:"contact_id"`
ConversationId uuid.UUID `params:"conversation_id"`
ContactID uuid.UUID `params:"contact_id"`
ConversationID uuid.UUID `params:"conversation_id"`
}
p := new(params)
@@ -21,22 +25,69 @@ func DeleteContact(c *fiber.Ctx) error {
db := database.DB
if p.ContactId == uuid.Nil {
if p.ContactID == uuid.Nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "contact_id is empty"})
}
if p.ConversationId == uuid.Nil {
if p.ConversationID == uuid.Nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "conversation_id is empty"})
}
msg, err := database.DeleteContact(db, p.ContactId, p.ConversationId)
msg, err := database.DeleteContact(db, p.ContactID, p.ConversationID)
if err != nil {
log.Println(err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to delete contact"})
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Internal server error"})
}
if msg != "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": msg})
}
log.Println("Contact deleted")
fmt.Println("Contact deleted")
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Contact deleted"})
}
func InsertContact(c *fiber.Ctx) error {
userID, err := uuid.Parse(c.Locals("userID").(string))
if err != nil {
log.Println(err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Internal server error"})
}
type params struct {
ContactUsername string `params:"contact_username"`
}
p := new(params)
if err := c.ParamsParser(p); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid params"})
}
db := database.DB
if p.ContactUsername == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "contact_username is empty"})
}
if !helpers.IsValidUsername(p.ContactUsername) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "username is invalid"})
}
contactID, err := database.GetUserID(db, p.ContactUsername)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
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"})
}
newContacts, err := database.InsertContact(db, userID, contactID, p.ContactUsername)
if err != nil {
log.Println(err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Internal server error"})
}
log.Println("Contact added")
return c.Status(fiber.StatusOK).JSON(newContacts)
}