Files
auth-service/internal/repository/user_postgres.go

45 lines
1.3 KiB
Go

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
}