finished implementing new error handler

This commit is contained in:
slawk0
2025-02-06 21:08:51 +01:00
parent 79357c8ae2
commit 915cc0c830
3 changed files with 210 additions and 235 deletions

View File

@@ -5,13 +5,11 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/google/uuid" "github.com/google/uuid"
"log"
"relay-server/helpers" "relay-server/helpers"
"relay-server/model" "relay-server/model"
) )
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (string, error) { func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) error {
// Check conversation type
var conversationType string var conversationType string
err := db.QueryRow( err := db.QueryRow(
"SELECT conversation_type FROM Conversations WHERE conversation_id = $1", "SELECT conversation_type FROM Conversations WHERE conversation_id = $1",
@@ -19,185 +17,151 @@ func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (stri
).Scan(&conversationType) ).Scan(&conversationType)
if err != nil { if err != nil {
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return "no conversation found for this id", nil return helpers.NewError(helpers.ErrNotFound, "no contacts found for this id", fmt.Errorf("no conversation found with id: %s", conversationID))
} }
return "", fmt.Errorf("error checking conversation type: %w", err) return helpers.NewError(helpers.ErrInternal, "Failed to check conversation", err)
} }
if conversationType == "group" { if conversationType == "group" {
// Delete from Contacts // Delete from Contacts
res, err := db.Exec( res, err := db.Exec(
"DELETE FROM Contacts WHERE conversation_id = $1 AND user_id = $2", "DELETE FROM Contacts WHERE conversation_id = $1 AND user_id = $2",
conversationID, conversationID, userID,
userID,
) )
if err != nil { if err != nil {
return "", fmt.Errorf("error deleting contact: %w", err) return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err)
} }
rowsAffected, err := res.RowsAffected() rowsAffected, err := res.RowsAffected()
if err != nil { if err != nil {
return "", fmt.Errorf("error checking contact deletion: %w", err) return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to verify contact deletion: %w", err))
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Sprintf("no matching contact found with conversation id: %s, user id: %s", conversationID, userID), nil return helpers.NewError(helpers.ErrNotFound, fmt.Sprintf("no matching contact found with conversation id: %s, user id: %s", conversationID, userID), nil)
} }
// Delete from Memberships // Delete from Memberships
res, err = db.Exec( res, err = db.Exec(
"DELETE FROM Memberships WHERE conversation_id = $1 AND user_id = $2", "DELETE FROM Memberships WHERE conversation_id = $1 AND user_id = $2",
conversationID, conversationID, userID,
userID,
) )
if err != nil { if err != nil {
return "", fmt.Errorf("error deleting membership: %w", err) return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to delete membership: %w", err))
} }
rowsAffected, err = res.RowsAffected() rowsAffected, err = res.RowsAffected()
if err != nil { if err != nil {
return "", fmt.Errorf("error checking membership deletion: %w", err) return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to verify membership deletion: %w", err))
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID) return helpers.NewError(helpers.ErrNotFound, "No membership found", err)
} }
} else { } else {
// Handle direct conversation
res, err := db.Exec( res, err := db.Exec(
"DELETE FROM Contacts WHERE user_id = $1 AND conversation_id = $2", "DELETE FROM Contacts WHERE user_id = $1 AND conversation_id = $2",
userID, userID, conversationID,
conversationID,
) )
if err != nil { if err != nil {
return "", fmt.Errorf("error deleting contact: %w", err) return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err)
} }
rowsAffected, err := res.RowsAffected() rowsAffected, err := res.RowsAffected()
if err != nil { if err != nil {
return "", fmt.Errorf("error checking contact deletion: %w", err) return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to verify contact deletion: %w", err))
} }
if rowsAffected == 0 { if rowsAffected == 0 {
return fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil return helpers.NewError(helpers.ErrNotFound, fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil)
} }
fmt.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID)
} }
return "", nil return nil
} }
func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUsername string) (*model.Contact, error) { func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUsername string) (*model.Contact, error) {
isSelfContact := userID == contactID isSelfContact := userID == contactID
var contact model.Contact
var conversationID uuid.UUID var conversationID uuid.UUID
if isSelfContact { if isSelfContact {
findSelfConversationQuery := ` err := db.QueryRow(`
SELECT c.conversation_id SELECT c.conversation_id
FROM Conversations c FROM Conversations c
JOIN Memberships m ON c.conversation_id = m.conversation_id JOIN Memberships m ON c.conversation_id = m.conversation_id
WHERE c.conversation_type = 'direct' WHERE c.conversation_type = 'direct'
AND m.user_id = $1 AND m.user_id = $1
AND ( AND (SELECT COUNT(*) FROM Memberships WHERE conversation_id = c.conversation_id) = 1
SELECT COUNT(*) LIMIT 1;
FROM Memberships `, userID).Scan(&conversationID)
WHERE conversation_id = c.conversation_id
) = 1
LIMIT 1;
`
err := db.QueryRow(findSelfConversationQuery, userID).Scan(&conversationID) if err != nil && !errors.Is(err, sql.ErrNoRows) {
if err != nil { return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check existing conversation: %w", err))
if errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
} }
// if conversation for themselves don't exist
if conversationID == uuid.Nil { if conversationID == uuid.Nil {
createConversationQuery := ` err := db.QueryRow(`
INSERT INTO Conversations (conversation_type) INSERT INTO Conversations (conversation_type)
VALUES ('direct') VALUES ('direct')
RETURNING conversation_id; RETURNING conversation_id;
` `).Scan(&conversationID)
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
if err != nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "Internal server error", fmt.Errorf("error creating conversation for self-contact: %w", err)) return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create conversation: %w", err))
} }
createMembershipQuery := ` _, err = db.Exec(`
INSERT INTO Memberships (conversation_id, user_id) INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2) VALUES ($1, $2)
ON CONFLICT (conversation_id, user_id) DO NOTHING; ON CONFLICT (conversation_id, user_id) DO NOTHING;
` `, conversationID, userID)
_, err = db.Exec(createMembershipQuery, conversationID, userID)
} else {
// For regular contacts, check if a conversation already exists between the two users
findConversationQuery := `
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m1 ON c.conversation_id = m1.conversation_id
JOIN Memberships m2 ON c.conversation_id = m2.conversation_id
WHERE c.conversation_type = 'direct'
AND (
(m1.user_id = $1 AND m2.user_id = $2)
OR
(m1.user_id = $2 AND m2.user_id = $1)
)
LIMIT 1;
`
err := db.QueryRow(findConversationQuery, userID, contactID).Scan(&conversationID)
if err != nil { if err != nil {
if errors.Is(err, sql.ErrNoRows) { return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create membership: %w", err))
conversationID = uuid.Nil
}
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
}
if conversationID != uuid.Nil {
// Create a new conversation between user and contact
createConversationQuery := `
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating conversation: %w", err))
}
createMembershipQuery := `
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2), ($1, $3)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`
res, err := db.Exec(createMembershipQuery, conversationID, userID, contactID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership: %w", err))
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking membership creation: %w", err))
}
if rowsAffected == 0 {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership %w", err))
}
} }
} }
} else {
err := db.QueryRow(`
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m1 ON c.conversation_id = m1.conversation_id
JOIN Memberships m2 ON c.conversation_id = m2.conversation_id
WHERE c.conversation_type = 'direct'
AND ((m1.user_id = $1 AND m2.user_id = $2) OR (m1.user_id = $2 AND m2.user_id = $1))
LIMIT 1;
`, userID, contactID).Scan(&conversationID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check existing conversation %w", err))
}
if conversationID == uuid.Nil {
err := db.QueryRow(`
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`).Scan(&conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create conversation: %w", err))
}
_, err = db.Exec(`
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2), ($1, $3)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`, conversationID, userID, contactID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create memberships: %w", err))
}
}
} }
insertedContact, err := InsertContactByID(db, contactID, conversationID) insertedContact, err := InsertContactByID(db, contactID, conversationID)
if err != nil || insertedContact.UserID == uuid.Nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err) return nil, err
} }
latestMessage, err := GetLatestMessage(db, conversationID) latestMessage, err := GetLatestMessage(db, conversationID)
if err != nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err) return nil, err
} }
contact = model.Contact{ contact := model.Contact{
ID: insertedContact.ID, ID: insertedContact.ID,
ConversationID: insertedContact.ConversationID, ConversationID: insertedContact.ConversationID,
UserID: insertedContact.UserID, UserID: insertedContact.UserID,
@@ -213,30 +177,29 @@ func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUse
func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (*model.Contact, error) { func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (*model.Contact, error) {
// First check if contact already exists // First check if contact already exists
checkQuery := `
SELECT contact_id, conversation_id, user_id
FROM Contacts
WHERE user_id = $1 AND conversation_id = $2
`
var contact model.Contact var contact model.Contact
err := db.QueryRow(checkQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID) err := db.QueryRow(`
SELECT contact_id, conversation_id, user_id
FROM Contacts
WHERE user_id = $1 AND conversation_id = $2
`, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err == nil { if err == nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("contact already exists")) return nil, helpers.NewError(helpers.ErrInvalidInput, "Contact already exists", nil)
} else if !errors.Is(err, sql.ErrNoRows) { } else if !errors.Is(err, sql.ErrNoRows) {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking contact existence: %w", err)) return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check contact existence: %w", err))
} }
insertQuery := ` // Insert new contact
INSERT INTO Contacts (user_id, conversation_id) err = db.QueryRow(`
VALUES($1, $2) INSERT INTO Contacts (user_id, conversation_id)
RETURNING contact_id, conversation_id, user_id VALUES($1, $2)
` RETURNING contact_id, conversation_id, user_id
`, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
err = db.QueryRow(insertQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err != nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error inserting contact: %w", err)) return nil, helpers.NewError(helpers.ErrInternal, "Failed to create contact", err)
} }
fmt.Printf("Successfully inserted contact by id: %v", conversationID)
return &contact, nil return &contact, nil
} }
@@ -244,23 +207,31 @@ func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (
func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, error) { func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, error) {
var latestMessage model.Contact var latestMessage model.Contact
query := ` err := db.QueryRow(`
SELECT DISTINCT ON (m.conversation_id) SELECT DISTINCT ON (m.conversation_id)
m.message_id AS last_message_id, m.message_id AS last_message_id,
m.content AS last_message, m.content AS last_message,
m.sent_at AS last_message_time, m.sent_at AS last_message_time,
a.username AS last_message_sender a.username AS last_message_sender
FROM Messages m FROM Messages m
JOIN Accounts a ON m.user_id = a.user_id JOIN Accounts a ON m.user_id = a.user_id
WHERE m.conversation_id = $1 WHERE m.conversation_id = $1
ORDER BY m.conversation_id, m.sent_at DESC ORDER BY m.conversation_id, m.sent_at DESC
LIMIT 1; LIMIT 1;
` `, conversationId).Scan(
&latestMessage.LastMessageID,
&latestMessage.LastMessage,
&latestMessage.LastMessageTime,
&latestMessage.LastMessageSender,
)
err := db.QueryRow(query, conversationId).Scan(&latestMessage.LastMessageID, &latestMessage.LastMessage, &latestMessage.LastMessageTime, &latestMessage.LastMessageSender)
if err != nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err)) if errors.Is(err, sql.ErrNoRows) {
return &model.Contact{}, nil // Return empty contact if no messages
}
return nil, helpers.NewError(helpers.ErrInternal, "Failed to get latest message", err)
} }
return &latestMessage, nil return &latestMessage, nil
} }
@@ -315,21 +286,21 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
rows, err := db.Query(contactsQuery, userID) rows, err := db.Query(contactsQuery, userID)
if err != nil { if err != nil {
log.Println("Failed to get contacts:", err) return nil, helpers.NewError(helpers.ErrInternal, "Failed to get contacts", err)
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting contacts: %w", err))
} }
var contacts []*model.Contact var contacts []*model.Contact
for rows.Next() { for rows.Next() {
contact := &model.Contact{} contact := &model.Contact{}
err := rows.Scan(&contact.ID, &contact.UserID, &contact.Username, &contact.ConversationID, &contact.Type) err := rows.Scan(&contact.ID, &contact.UserID, &contact.Username,
&contact.ConversationID, &contact.Type)
if err != nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error scanning contact: %w", err)) return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
} }
latestMessage, err := GetLatestMessage(db, contact.ConversationID) latestMessage, err := GetLatestMessage(db, contact.ConversationID)
if err != nil { if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err)) return nil, err
} }
contact.LastMessageID = latestMessage.LastMessageID contact.LastMessageID = latestMessage.LastMessageID
@@ -341,7 +312,7 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error iterating over contacts: %w", err)) return nil, helpers.NewError(helpers.ErrInternal, "Failed to process contacts", err)
} }
return contacts, nil return contacts, nil

View File

@@ -1,11 +1,10 @@
package handlers package handlers
import ( import (
"errors" "fmt"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"log"
"os" "os"
"relay-server/config" "relay-server/config"
"relay-server/database" "relay-server/database"
@@ -14,154 +13,162 @@ import (
) )
func Signup(c *fiber.Ctx) error { func Signup(c *fiber.Ctx) error {
type SignupStruct struct { type SignupStruct struct {
Username string `json:"username" xml:"username" form:"username"` Username string `json:"username" xml:"username" form:"username"`
Password string `json:"password" xml:"password" form:"password"` Password string `json:"password" xml:"password" form:"password"`
} }
db := database.DB
u := new(SignupStruct) u := new(SignupStruct)
if err := c.BodyParser(u); err != nil { if err := c.BodyParser(u); err != nil {
return err return helpers.NewError(helpers.ErrInvalidInput, "Invalid request body", err)
} }
// Checks if username or passwords are empty
// Validate input
if u.Username == "" { if u.Username == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "username is empty"}) return helpers.NewError(helpers.ErrInvalidInput, "Username is empty", nil)
} }
if u.Password == "" { if u.Password == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "password is empty"}) return helpers.NewError(helpers.ErrInvalidInput, "Password is empty", nil)
} }
// Checks if passwords or username have valid length and characters
if !helpers.IsValidPassword(u.Password) { if !helpers.IsValidPassword(u.Password) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid password"}) return helpers.NewError(helpers.ErrInvalidInput, "Invalid password", nil)
} }
if !helpers.IsValidUsername(u.Username) { if !helpers.IsValidUsername(u.Username) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid username"}) return helpers.NewError(helpers.ErrInvalidInput, "Invalid username", nil)
} }
// Checks if username already exist in database // Check if user exists
exist, _ := database.CheckUserExists(db, u.Username) exist, err := database.CheckUserExists(database.DB, u.Username)
if err != nil {
return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to check user existance: %w", err))
}
if exist { if exist {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "user already exists"}) return helpers.NewError(helpers.ErrInvalidInput, "User already exists", nil)
} }
// Create password hash // Create password hash
passwordHash, err := bcrypt.GenerateFromPassword([]byte(u.Password), config.BCRYPT_COST) passwordHash, err := bcrypt.GenerateFromPassword([]byte(u.Password), config.BCRYPT_COST)
if err != nil { if err != nil {
log.Printf("error hashing password: %w\n", err) return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to generate password hash: %w", err))
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "internal server error"})
} }
// Insert username and password hash to database // Insert user
userID, err := database.InsertUser(db, u.Username, string(passwordHash)) userID, err := database.InsertUser(database.DB, u.Username, string(passwordHash))
if err != nil { if err != nil {
log.Print(err) return helpers.NewError(helpers.ErrInternal, "Failed to create user", err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Internal server error"})
} }
// Generate token with user id and username // Generate token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID, "user_id": userID,
"username": u.Username, "username": u.Username,
}) })
// Sign token
signedToken, err := token.SignedString([]byte(os.Getenv("JWT_SECRET"))) signedToken, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
if err != nil {
return helpers.NewError(helpers.ErrInternal, "Failed to generate auth token", err)
}
// Set token to cookies // Set token cookie
tokenCookie := new(fiber.Cookie) tokenCookie := new(fiber.Cookie)
tokenCookie.Name = "token" tokenCookie.Name = "token"
tokenCookie.Value = signedToken tokenCookie.Value = signedToken
tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour) tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour)
//tokenCookie.HTTPOnly = true
c.Cookie(tokenCookie) c.Cookie(tokenCookie)
// If everything went well sent username and user_id assigned by database return c.Status(fiber.StatusOK).JSON(fiber.Map{
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Successfully signed up", "username": u.Username, "user_id": userID}) "message": "Successfully signed up",
"username": u.Username,
"user_id": userID,
})
} }
func Login(c *fiber.Ctx) error { func Login(c *fiber.Ctx) error {
type loginStruct struct { type loginStruct struct {
Username string `json:"username" xml:"username" form:"username"` Username string `json:"username" xml:"username" form:"username"`
Password string `json:"password" xml:"password" form:"password"` Password string `json:"password" xml:"password" form:"password"`
} }
db := database.DB
u := new(loginStruct) u := new(loginStruct)
if err := c.BodyParser(u); err != nil { if err := c.BodyParser(u); err != nil {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid request body", err)
}
// Validate input
if u.Username == "" {
return helpers.NewError(helpers.ErrInvalidInput, "Username is empty", nil)
}
if u.Password == "" {
return helpers.NewError(helpers.ErrInvalidInput, "Password is empty", nil)
}
if !helpers.IsValidUsername(u.Username) {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid username", nil)
}
if !helpers.IsValidPassword(u.Password) {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid password", nil)
}
// Check if user exists
exist, err := database.CheckUserExists(database.DB, u.Username)
if err != nil {
return err
}
if !exist {
return helpers.NewError(helpers.ErrNotFound, "User does not exist", nil)
}
// Verify password
passwordHash, err := database.GetPasswordHash(database.DB, u.Username)
if err != nil {
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(u.Password)); err != nil {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid password", nil)
}
// Get user ID
userID, err := database.GetUserID(database.DB, u.Username)
if err != nil {
return err return err
} }
// Checks if username or passwords are empty // Generate token
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{ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID, "user_id": userID,
"username": u.Username, "username": u.Username,
}) })
// Sign token
signedToken, err := token.SignedString([]byte(os.Getenv("JWT_SECRET"))) signedToken, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
if err != nil {
return helpers.NewError(helpers.ErrInternal, "Failed to generate token", err)
}
// Set token to cookies // Set token cookie
tokenCookie := new(fiber.Cookie) tokenCookie := new(fiber.Cookie)
tokenCookie.Name = "token" tokenCookie.Name = "token"
tokenCookie.Value = signedToken tokenCookie.Value = signedToken
tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour) tokenCookie.Expires = time.Now().Add(30 * 24 * time.Hour)
c.Cookie(tokenCookie) 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 { func ValidateToken(c *fiber.Ctx) error {
username := c.Locals("username").(string) username, ok := c.Locals("username").(string)
userID := c.Locals("userID").(string) if !ok {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid token: missing username", nil)
}
//log.Printf("userID: %v, username: %v", userID, username) userID, ok := c.Locals("userID").(string)
//if userID == "" || username == "" { if !ok {
// log.Printf("userID or username is empty %v", c.Locals("username")) return helpers.NewError(helpers.ErrInvalidInput, "Invalid token: missing user ID", nil)
// 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}) return c.Status(fiber.StatusOK).JSON(fiber.Map{
"message": "authorized",
"username": username,
"user_id": userID,
})
} }

View File

@@ -25,13 +25,10 @@ func DeleteContact(c *fiber.Ctx) error {
return helpers.NewError(helpers.ErrInvalidInput, "conversation ID is empty", nil) return helpers.NewError(helpers.ErrInvalidInput, "conversation ID is empty", nil)
} }
msg, err := database.DeleteContact(database.DB, p.ContactID, p.ConversationID) err := database.DeleteContact(database.DB, p.ContactID, p.ConversationID)
if err != nil { if err != nil {
return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err) return helpers.NewError(helpers.ErrInternal, "Failed to delete contact", err)
} }
if msg != "" {
return helpers.NewError(helpers.ErrInvalidInput, msg, nil)
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Contact deleted"}) return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Contact deleted"})
} }