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"
"fmt"
"github.com/google/uuid"
"log"
"relay-server/helpers"
"relay-server/model"
)
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (string, error) {
// Check conversation type
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) error {
var conversationType string
err := db.QueryRow(
"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)
if err != nil {
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" {
// Delete from Contacts
res, err := db.Exec(
"DELETE FROM Contacts WHERE conversation_id = $1 AND user_id = $2",
conversationID,
userID,
conversationID, userID,
)
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()
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 {
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
res, err = db.Exec(
"DELETE FROM Memberships WHERE conversation_id = $1 AND user_id = $2",
conversationID,
userID,
conversationID, userID,
)
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()
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 {
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 {
// Handle direct conversation
res, err := db.Exec(
"DELETE FROM Contacts WHERE user_id = $1 AND conversation_id = $2",
userID,
conversationID,
userID, conversationID,
)
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()
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 {
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) {
isSelfContact := userID == contactID
var contact model.Contact
var conversationID uuid.UUID
if isSelfContact {
findSelfConversationQuery := `
err := db.QueryRow(`
SELECT c.conversation_id
FROM Conversations c
JOIN Memberships m ON c.conversation_id = m.conversation_id
WHERE c.conversation_type = 'direct'
AND m.user_id = $1
AND (
SELECT COUNT(*)
FROM Memberships
WHERE conversation_id = c.conversation_id
) = 1
AND (SELECT COUNT(*) FROM Memberships WHERE conversation_id = c.conversation_id) = 1
LIMIT 1;
`
`, userID).Scan(&conversationID)
err := db.QueryRow(findSelfConversationQuery, userID).Scan(&conversationID)
if err != nil {
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 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 conversation for themselves don't exist
if conversationID == uuid.Nil {
createConversationQuery := `
err := db.QueryRow(`
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
`).Scan(&conversationID)
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)
VALUES ($1, $2)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`
_, err = db.Exec(createMembershipQuery, conversationID, userID)
`, conversationID, userID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create membership: %w", err))
}
}
} else {
// For regular contacts, check if a conversation already exists between the two users
findConversationQuery := `
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)
)
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 errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
`, 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))
}
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 := `
if conversationID == uuid.Nil {
err := db.QueryRow(`
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
`).Scan(&conversationID)
if err != nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating conversation: %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)
VALUES ($1, $2), ($1, $3)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`
res, err := db.Exec(createMembershipQuery, conversationID, userID, contactID)
`, 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))
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to create memberships: %w", err))
}
}
}
}
insertedContact, err := InsertContactByID(db, contactID, conversationID)
if err != nil || insertedContact.UserID == uuid.Nil {
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
if err != nil {
return nil, err
}
latestMessage, err := GetLatestMessage(db, conversationID)
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,
ConversationID: insertedContact.ConversationID,
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) {
// First check if contact already exists
checkQuery := `
var contact model.Contact
err := db.QueryRow(`
SELECT contact_id, conversation_id, user_id
FROM Contacts
WHERE user_id = $1 AND conversation_id = $2
`
var contact model.Contact
err := db.QueryRow(checkQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
`, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
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) {
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
err = db.QueryRow(`
INSERT INTO Contacts (user_id, conversation_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 {
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
}
@@ -244,7 +207,7 @@ func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (
func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, error) {
var latestMessage model.Contact
query := `
err := db.QueryRow(`
SELECT DISTINCT ON (m.conversation_id)
m.message_id AS last_message_id,
m.content AS last_message,
@@ -255,12 +218,20 @@ func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, err
WHERE m.conversation_id = $1
ORDER BY m.conversation_id, m.sent_at DESC
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 {
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
}
@@ -315,21 +286,21 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
rows, err := db.Query(contactsQuery, userID)
if err != nil {
log.Println("Failed to get contacts:", err)
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting contacts: %w", err))
return nil, helpers.NewError(helpers.ErrInternal, "Failed to get contacts", err)
}
var contacts []*model.Contact
for rows.Next() {
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 {
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)
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
@@ -341,7 +312,7 @@ func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
}
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

View File

@@ -1,11 +1,10 @@
package handlers
import (
"errors"
"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"
@@ -14,154 +13,162 @@ import (
)
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
return helpers.NewError(helpers.ErrInvalidInput, "Invalid request body", err)
}
// Checks if username or passwords are empty
// Validate input
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 == "" {
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) {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid password"})
return helpers.NewError(helpers.ErrInvalidInput, "Invalid password", nil)
}
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
exist, _ := database.CheckUserExists(db, u.Username)
// Check if user exists
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 {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "user already exists"})
return helpers.NewError(helpers.ErrInvalidInput, "User already exists", nil)
}
// 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"})
return helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("failed to generate password hash: %w", err))
}
// Insert username and password hash to database
userID, err := database.InsertUser(db, u.Username, string(passwordHash))
// Insert user
userID, err := database.InsertUser(database.DB, u.Username, string(passwordHash))
if err != nil {
log.Print(err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Internal server error"})
return helpers.NewError(helpers.ErrInternal, "Failed to create user", err)
}
// Generate token with user id and username
// Generate token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID,
"username": u.Username,
})
// Sign token
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.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})
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 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
}
// 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
// Generate token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID,
"username": u.Username,
})
// Sign token
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.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})
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})
username, ok := c.Locals("username").(string)
if !ok {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid token: missing username", nil)
}
userID, ok := c.Locals("userID").(string)
if !ok {
return helpers.NewError(helpers.ErrInvalidInput, "Invalid token: missing user ID", nil)
}
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)
}
msg, err := database.DeleteContact(database.DB, p.ContactID, p.ConversationID)
err := database.DeleteContact(database.DB, p.ContactID, p.ConversationID)
if err != nil {
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"})
}