Backend structure / login with JWT

This commit is contained in:
Leons Aleksandrovs
2025-07-06 16:46:21 +03:00
parent 3166424426
commit 3003a961b6
18 changed files with 338 additions and 126 deletions
+49
View File
@@ -0,0 +1,49 @@
package user
import (
"backend/db"
"context"
"strings"
"time"
)
type User struct {
Id int
Email string
Name string
Password string
CreatedAt time.Time
}
func Create(email string, name string, hash string) error {
// Generate background context for managing timeouts and disconnections
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// Build database query
query := `INSERT INTO users (email, name, password) VALUES ($1, $2, $3)`
_, err := db.Pool.Exec(ctx, query, strings.ToLower(email), name, hash)
// Return error if any
return err
}
// Symbol * will follow the pointer to its value
func FindByEmail(email string) (*User, error) {
// bg context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// Build query
query := `SELECT * FROM users WHERE email = $1`
row := db.Pool.QueryRow(ctx, query, strings.ToLower(email))
// Scan will map rows to User struct
var u User
if err := row.Scan(&u.Id, &u.Email, &u.Name, &u.Password, &u.CreatedAt); err != nil {
return nil, err
}
// give pointer
return &u, nil
}
-28
View File
@@ -1,28 +0,0 @@
package models
import (
"backend/db"
"context"
"time"
)
type User struct {
ID int
email string
name string
password string
createdAt string
}
func (u *User) Create(email string, name string, hash string) error {
// Generate background context for managing timeouts and disconnections
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// Build database query
query := `INSERT INTO users (email, name, password) VALUES ($1, $2, $3)`
_, err := db.Pool.Exec(ctx, query, email, name, hash)
// Return error if any
return err
}