Добавлен основные классы для сервиса авторизаци

This commit is contained in:
Ганеев Артем
2025-10-28 20:49:54 +03:00
parent def3552a67
commit 736b8031f8
26 changed files with 904 additions and 40 deletions

View File

@@ -0,0 +1,35 @@
package repository
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
usersTable = "users"
)
type Config struct {
Host string
Port string
Username string
Password string
DBName string
SSLMode string
}
func NewPostgresDB(cfg Config) (*sql.DB, error) {
db, err := sql.Open("postgres",
fmt.Sprintf("user=%s password=%s host=%s dbname=%s sslmode=%s",
cfg.Username, cfg.Password, cfg.Host, cfg.DBName, cfg.SSLMode))
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
return db, nil
}

View File

@@ -0,0 +1,22 @@
package repository
import (
"authorization/internal"
"database/sql"
)
type UserResository interface {
CreateUser(user internal.User) (int, error)
GetUser(username, password string) (internal.User, error)
UpdateUserRole(username string, userrole internal.UserRole) (string, error)
}
type Repository struct {
UserResository
}
func NewRepository(db *sql.DB) *Repository {
return &Repository{
UserResository: NewUserPostgres(db),
}
}

View File

@@ -0,0 +1,44 @@
package repository
import (
"authorization/internal"
"database/sql"
"fmt"
)
type UserPostgres struct {
db *sql.DB
}
func NewUserPostgres(db *sql.DB) *UserPostgres {
return &UserPostgres{db: db}
}
func (r *UserPostgres) CreateUser(user internal.User) (int, error) {
var id int
query := fmt.Sprintf("INSERT INTO %s(name,username,password_hash,role) values ($1,$2,$3,$4) RETURNING id", usersTable)
row := r.db.QueryRow(query, user.Name, user.Username, user.Password, internal.Student)
if err := row.Scan(&id); err != nil {
return 0, err
}
return id, nil
}
func (r *UserPostgres) GetUser(username, password string) (internal.User, error) {
var user internal.User
query := fmt.Sprintf("SELECT * from %s where username = $1 AND password_hash=$2", usersTable)
row := r.db.QueryRow(query, username, password)
err := row.Scan(&user.Id, &user.Name, &user.Username, &user.Password, &user.UserRole)
return user, err
}
func (r *UserPostgres) UpdateUserRole(username string, userrole internal.UserRole) (string, error) {
query := fmt.Sprintf("UPDATE %s SET role = $1 WHERE username = $2 RETURNING role", usersTable)
var newRole string
err := r.db.QueryRow(query, userrole, username).Scan(&newRole)
if err != nil {
return "", fmt.Errorf("failed to update user role: %v", err)
}
return newRole, nil
}