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

17
.idea/dataSources.xml generated Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="relay@192.168.0.47" uuid="59be3690-af66-4c12-b5dd-1a8df79ef77d">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://192.168.0.47:5432/relay</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -3,6 +3,7 @@ package database
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"github.com/google/uuid"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"log" "log"
) )
@@ -34,7 +35,7 @@ func CheckUserExists(db *sql.DB, username string) (bool, error) {
err := db.QueryRow(query, username).Scan(&count) err := db.QueryRow(query, username).Scan(&count)
if err != nil { if err != nil {
return false, fmt.Errorf("error checking username exists: %v", err) return false, fmt.Errorf("error checking username exists: %w", err)
} }
return count > 0, err return count > 0, err
@@ -47,15 +48,15 @@ func InsertUser(db *sql.DB, username string, passwordHash string) (string, error
RETURNING user_id; RETURNING user_id;
` `
var userId string var userID string
err := db.QueryRow(query, username, passwordHash).Scan(&userId) err := db.QueryRow(query, username, passwordHash).Scan(&userID)
if err != nil { if err != nil {
return "", fmt.Errorf("error inserting user: %v", err) return "", fmt.Errorf("error inserting user: %w", err)
} }
log.Printf("Inserted user: %v", username) fmt.Printf("Inserted user: %w", username)
return userId, err return userID, err
} }
func GetPasswordHash(db *sql.DB, username string) (string, error) { func GetPasswordHash(db *sql.DB, username string) (string, error) {
@@ -67,24 +68,22 @@ func GetPasswordHash(db *sql.DB, username string) (string, error) {
var passwordHash string var passwordHash string
err := db.QueryRow(query, username).Scan(&passwordHash) err := db.QueryRow(query, username).Scan(&passwordHash)
if err != nil { if err != nil {
fmt.Printf("error getting password hash: %v\n", err) return "", fmt.Errorf("error getting password hash: %w", err)
return "", fmt.Errorf("error getting password hash: %v", err)
} }
return passwordHash, err return passwordHash, err
} }
func GetUserId(db *sql.DB, username string) (string, error) { func GetUserID(db *sql.DB, username string) (uuid.UUID, error) {
query := ` query := `
SELECT user_id FROM Accounts SELECT user_id FROM Accounts
WHERE LOWER(username) = $1; WHERE LOWER(username) = LOWER($1);
` `
var dbUsername string var userID uuid.UUID
err := db.QueryRow(query, username).Scan(&dbUsername) err := db.QueryRow(query, username).Scan(&userID)
if err != nil { if err != nil {
fmt.Printf("Error getting password: %v\n", err) return uuid.Nil, fmt.Errorf("error getting user id: %w", err)
return "", fmt.Errorf("error getting user id: %v", err)
} }
return dbUsername, err return userID, nil
} }

View File

@@ -5,7 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/google/uuid" "github.com/google/uuid"
"log" "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) (string, error) {
@@ -58,8 +58,6 @@ func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (stri
if rowsAffected == 0 { if rowsAffected == 0 {
return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID) return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID)
} }
log.Printf("Successfully removed user %s from group %s", userID, conversationID)
} else { } else {
// Handle direct conversation // Handle direct conversation
res, err := db.Exec( res, err := db.Exec(
@@ -68,21 +66,198 @@ func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (stri
conversationID, conversationID,
) )
if err != nil { if err != nil {
log.Printf("Error deleting contact: %v", err)
return "", fmt.Errorf("error deleting contact: %w", err) return "", fmt.Errorf("error deleting contact: %w", err)
} }
rowsAffected, err := res.RowsAffected() rowsAffected, err := res.RowsAffected()
if err != nil { if err != nil {
log.Printf("Error checking contact deletion: %v", err)
return "", fmt.Errorf("error checking contact deletion: %w", err) return "", fmt.Errorf("error checking 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 fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil
} }
log.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID) 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 := `
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
LIMIT 1;
`
err := db.QueryRow(findSelfConversationQuery, userID).Scan(&conversationID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, fmt.Errorf("error finding existing conversation: %w", err)
}
// if conversation for themselves don't exist
if conversationID == uuid.Nil {
createConversationQuery := `
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
if err != nil {
return nil, fmt.Errorf("error creating conversation for self-contact: %w", err)
}
createMembershipQuery := `
INSERT INTO Memberships (conversation_id, user_id)
VALUES ($1, $2)
ON CONFLICT (conversation_id, user_id) DO NOTHING;
`
_, 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 errors.Is(err, sql.ErrNoRows) {
conversationID = uuid.Nil
}
return nil, 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, 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, fmt.Errorf("error creating membership: %w", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("error checking membership creation: %w", err)
}
if rowsAffected == 0 {
return nil, fmt.Errorf("error creating membership %w", err)
}
}
}
}
insertedContact, err := InsertContactByID(db, contactID, conversationID)
if err != nil || insertedContact.UserID == uuid.Nil {
return nil, fmt.Errorf("error inserting contact by id: %w", err)
}
latestMessage, err := GetLatestMessage(db, conversationID)
if err != nil {
return nil, fmt.Errorf("error getting latest message: %w", err)
}
contact = model.Contact{
ID: insertedContact.ID,
ConversationID: insertedContact.ConversationID,
UserID: insertedContact.UserID,
Username: contactUsername,
Type: "direct",
LastMessageID: latestMessage.LastMessageID,
LastMessage: latestMessage.LastMessage,
LastMessageTime: latestMessage.LastMessageTime,
LastMessageSender: latestMessage.LastMessageSender,
}
return &contact, nil
}
func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (*model.Contact, error) {
// 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
err := db.QueryRow(checkQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err == nil {
return nil, fmt.Errorf("contact already exists")
} else if !errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("error checking contact existence: %w", err)
}
insertQuery := `
INSERT INTO Contacts (user_id, conversation_id)
VALUES($1, $2)
RETURNING contact_id, conversation_id, user_id
`
err = db.QueryRow(insertQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
if err != nil {
return nil, fmt.Errorf("error inserting contact: %w", err)
}
fmt.Printf("Successfully inserted contact by id: %v", conversationID)
return &contact, nil
}
func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, error) {
var latestMessage model.Contact
query := `
SELECT DISTINCT ON (m.conversation_id)
m.message_id AS last_message_id,
m.content AS last_message,
m.sent_at AS last_message_time,
a.username AS last_message_sender
FROM Messages m
JOIN Accounts a ON m.user_id = a.user_id
WHERE m.conversation_id = $1
ORDER BY m.conversation_id, m.sent_at DESC
LIMIT 1;
`
err := db.QueryRow(query, conversationId).Scan(&latestMessage.LastMessageID, &latestMessage.LastMessage, &latestMessage.LastMessageTime, &latestMessage.LastMessageSender)
if err != nil {
return nil, fmt.Errorf("error getting latest message: %w", err)
}
return &latestMessage, nil
}

View File

@@ -1,10 +1,10 @@
package handlers package handlers
import ( import (
"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"
@@ -49,20 +49,20 @@ func Signup(c *fiber.Ctx) error {
// 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 {
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"}) return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "internal server error"})
} }
// Insert username and password hash to database // 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 { 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"}) return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Internal server error"})
} }
// Generate token with user id and username // 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 // Sign token
@@ -77,7 +77,7 @@ func Signup(c *fiber.Ctx) error {
c.Cookie(tokenCookie) c.Cookie(tokenCookie)
// If everything went well sent username and user_id assigned by database // 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 { func Login(c *fiber.Ctx) error {
@@ -117,19 +117,22 @@ func Login(c *fiber.Ctx) error {
} }
// Verifies password matching // 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 { if bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(u.Password)) != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid password"}) 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 { 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"}) return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "internal server error"})
} }
// Generate token with user id and username // 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 // Sign token
@@ -140,19 +143,20 @@ func Login(c *fiber.Ctx) error {
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)
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") username := c.Locals("username").(string)
userId := c.Locals("user_id") userID := c.Locals("userID").(string)
if userId == nil || username == nil { //log.Printf("userID: %v, username: %v", userID, username)
fmt.Println("userId or username is nil") //if userID == "" || username == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid token"}) // 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": c.Locals("username").(string), "user_id": c.Locals("userId").(string)}) //}
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "authorized", "username": username, "user_id": userID})
} }

View File

@@ -1,17 +1,21 @@
package handlers package handlers
import ( import (
"database/sql"
"errors"
"fmt"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/google/uuid" "github.com/google/uuid"
"log" "log"
"relay-server/database" "relay-server/database"
"relay-server/helpers"
) )
func DeleteContact(c *fiber.Ctx) error { func DeleteContact(c *fiber.Ctx) error {
type params struct { type params struct {
ContactId uuid.UUID `params:"contact_id"` ContactID uuid.UUID `params:"contact_id"`
ConversationId uuid.UUID `params:"conversation_id"` ConversationID uuid.UUID `params:"conversation_id"`
} }
p := new(params) p := new(params)
@@ -21,22 +25,69 @@ func DeleteContact(c *fiber.Ctx) error {
db := database.DB 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"}) 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"}) 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 { if err != nil {
log.Println(err) 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 != "" { if msg != "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": 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"}) 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)
}

View File

@@ -18,7 +18,7 @@ func Protected() fiber.Handler {
user := c.Locals("user").(*jwt.Token) user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(*model.UserClaims) claims := user.Claims.(*model.UserClaims)
c.Locals("userId", claims.UserId) c.Locals("userID", claims.UserID)
c.Locals("username", claims.Username) c.Locals("username", claims.Username)
return c.Next() return c.Next()
}, },

View File

@@ -1,9 +1,23 @@
package model package model
import "github.com/golang-jwt/jwt/v5" import (
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
type UserClaims struct { type UserClaims struct {
Username string `json:"username"` Username string `json:"username"`
UserId string `json:"user_id"` UserID string `json:"user_id"`
jwt.RegisteredClaims jwt.RegisteredClaims
} }
type Contact struct {
ID int `json:"contact_id"`
ConversationID uuid.UUID `json:"conversation_id"`
UserID uuid.UUID `json:"user_id"`
Username string `json:"username"`
Type string `json:"type"`
LastMessageID int `json:"last_message_id"`
LastMessage string `json:"last_message"`
LastMessageTime string `json:"last_message_time"`
LastMessageSender string `json:"last_message_sender"`
}

View File

@@ -15,12 +15,13 @@ func SetupRoutes(app *fiber.App) {
chat := api.Group("/chat", middleware.Protected(), logger.New()) chat := api.Group("/chat", middleware.Protected(), logger.New())
// Auth group // Auth group
auth := api.Group("/auth", middleware.Protected(), handlers.ValidateToken) auth := api.Group("/auth", logger.New())
auth.Post("/signup", handlers.Signup) auth.Post("/signup", handlers.Signup)
auth.Post("/login", handlers.Login) auth.Post("/login", handlers.Login)
auth.Get("/validate", handlers.ValidateToken) auth.Get("/validate", middleware.Protected(), handlers.ValidateToken)
// Contacts group // Contacts group
contacts := chat.Group("/contacts", middleware.Protected(), logger.New()) contacts := chat.Group("/contacts", middleware.Protected(), logger.New())
contacts.Delete("/:contact_id/:conversation_id", handlers.DeleteContact) contacts.Delete("/:contact_id/:conversation_id", handlers.DeleteContact)
contacts.Post("/:contact_username", handlers.InsertContact)
} }