This commit is contained in:
2026-03-23 18:55:27 +07:00
parent 6dc0322fe5
commit 3626c12319
47 changed files with 2741 additions and 0 deletions

View File

@@ -0,0 +1 @@
package controllers

32
internal/gen/sqlc/db.go Normal file
View File

@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package sqlc
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}

View File

@@ -0,0 +1,46 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package sqlc
import (
"github.com/jackc/pgx/v5/pgtype"
)
type Role struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
IsDeleted pgtype.Bool `json:"is_deleted"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type User struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
AvatarUrl pgtype.Text `json:"avatar_url"`
IsActive pgtype.Bool `json:"is_active"`
IsVerified pgtype.Bool `json:"is_verified"`
TokenVersion int32 `json:"token_version"`
RefreshToken pgtype.Text `json:"refresh_token"`
IsDeleted pgtype.Bool `json:"is_deleted"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type UserRole struct {
UserID pgtype.UUID `json:"user_id"`
RoleID pgtype.UUID `json:"role_id"`
}
type UserToken struct {
ID pgtype.UUID `json:"id"`
UserID pgtype.UUID `json:"user_id"`
Token string `json:"token"`
TokenType int16 `json:"token_type"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}

View File

@@ -0,0 +1,208 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: roles.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const addUserRole = `-- name: AddUserRole :exec
INSERT INTO user_roles (user_id, role_id)
SELECT $1, r.id
FROM roles r
WHERE r.name = $2
ON CONFLICT DO NOTHING
`
type AddUserRoleParams struct {
UserID pgtype.UUID `json:"user_id"`
Name string `json:"name"`
}
func (q *Queries) AddUserRole(ctx context.Context, arg AddUserRoleParams) error {
_, err := q.db.Exec(ctx, addUserRole, arg.UserID, arg.Name)
return err
}
const createRole = `-- name: CreateRole :one
INSERT INTO roles (name)
VALUES ($1)
RETURNING id, name, is_deleted, created_at, updated_at
`
func (q *Queries) CreateRole(ctx context.Context, name string) (Role, error) {
row := q.db.QueryRow(ctx, createRole, name)
var i Role
err := row.Scan(
&i.ID,
&i.Name,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteRole = `-- name: DeleteRole :exec
UPDATE roles
SET
is_deleted = true,
updated_at = now()
WHERE id = $1
`
func (q *Queries) DeleteRole(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteRole, id)
return err
}
const getRoleByID = `-- name: GetRoleByID :one
SELECT id, name, is_deleted, created_at, updated_at FROM roles
WHERE id = $1 AND is_deleted = false
`
func (q *Queries) GetRoleByID(ctx context.Context, id pgtype.UUID) (Role, error) {
row := q.db.QueryRow(ctx, getRoleByID, id)
var i Role
err := row.Scan(
&i.ID,
&i.Name,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getRoleByName = `-- name: GetRoleByName :one
SELECT id, name, is_deleted, created_at, updated_at FROM roles
WHERE name = $1 AND is_deleted = false
`
func (q *Queries) GetRoleByName(ctx context.Context, name string) (Role, error) {
row := q.db.QueryRow(ctx, getRoleByName, name)
var i Role
err := row.Scan(
&i.ID,
&i.Name,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getRoles = `-- name: GetRoles :many
SELECT id, name, is_deleted, created_at, updated_at
FROM roles
WHERE is_deleted = false
`
func (q *Queries) GetRoles(ctx context.Context) ([]Role, error) {
rows, err := q.db.Query(ctx, getRoles)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Role{}
for rows.Next() {
var i Role
if err := rows.Scan(
&i.ID,
&i.Name,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const removeAllRolesFromUser = `-- name: RemoveAllRolesFromUser :exec
DELETE FROM user_roles
WHERE user_id = $1
`
func (q *Queries) RemoveAllRolesFromUser(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, removeAllRolesFromUser, userID)
return err
}
const removeAllUsersFromRole = `-- name: RemoveAllUsersFromRole :exec
DELETE FROM user_roles
WHERE role_id = $1
`
func (q *Queries) RemoveAllUsersFromRole(ctx context.Context, roleID pgtype.UUID) error {
_, err := q.db.Exec(ctx, removeAllUsersFromRole, roleID)
return err
}
const removeUserRole = `-- name: RemoveUserRole :exec
DELETE FROM user_roles ur
USING roles r
WHERE ur.role_id = r.id
AND ur.user_id = $1
AND r.name = $2
`
type RemoveUserRoleParams struct {
UserID pgtype.UUID `json:"user_id"`
Name string `json:"name"`
}
func (q *Queries) RemoveUserRole(ctx context.Context, arg RemoveUserRoleParams) error {
_, err := q.db.Exec(ctx, removeUserRole, arg.UserID, arg.Name)
return err
}
const restoreRole = `-- name: RestoreRole :exec
UPDATE roles
SET
is_deleted = false,
updated_at = now()
WHERE id = $1
`
func (q *Queries) RestoreRole(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, restoreRole, id)
return err
}
const updateRole = `-- name: UpdateRole :one
UPDATE roles
SET
name = $1,
updated_at = now()
WHERE id = $2 AND is_deleted = false
RETURNING id, name, is_deleted, created_at, updated_at
`
type UpdateRoleParams struct {
Name string `json:"name"`
ID pgtype.UUID `json:"id"`
}
func (q *Queries) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) {
row := q.db.QueryRow(ctx, updateRole, arg.Name, arg.ID)
var i Role
err := row.Scan(
&i.ID,
&i.Name,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}

View File

@@ -0,0 +1,413 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: users.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const createUser = `-- name: CreateUser :one
INSERT INTO users (
name,
email,
password_hash,
avatar_url
) VALUES (
$1, $2, $3, $4
)
RETURNING id, name, email, password_hash, avatar_url, is_active, is_verified, token_version, refresh_token, is_deleted, created_at, updated_at
`
type CreateUserParams struct {
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
AvatarUrl pgtype.Text `json:"avatar_url"`
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) {
row := q.db.QueryRow(ctx, createUser,
arg.Name,
arg.Email,
arg.PasswordHash,
arg.AvatarUrl,
)
var i User
err := row.Scan(
&i.ID,
&i.Name,
&i.Email,
&i.PasswordHash,
&i.AvatarUrl,
&i.IsActive,
&i.IsVerified,
&i.TokenVersion,
&i.RefreshToken,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteUser = `-- name: DeleteUser :exec
UPDATE users
SET
is_deleted = true,
updated_at = now()
WHERE id = $1
`
func (q *Queries) DeleteUser(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteUser, id)
return err
}
const existsUserByEmail = `-- name: ExistsUserByEmail :one
SELECT EXISTS (
SELECT 1 FROM users
WHERE email = $1
AND is_deleted = false
)
`
func (q *Queries) ExistsUserByEmail(ctx context.Context, email string) (bool, error) {
row := q.db.QueryRow(ctx, existsUserByEmail, email)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const getUserByEmail = `-- name: GetUserByEmail :one
SELECT
u.id,
u.name,
u.email,
u.password_hash,
u.avatar_url,
u.is_active,
u.is_verified,
u.token_version,
u.is_deleted,
u.created_at,
u.updated_at,
COALESCE(
json_agg(
json_build_object('id', r.id, 'name', r.name)
) FILTER (WHERE r.id IS NOT NULL),
'[]'
)::json AS roles
FROM users u
LEFT JOIN user_roles ur ON u.id = ur.user_id
LEFT JOIN roles r ON ur.role_id = r.id
WHERE u.email = $1 AND u.is_deleted = false
GROUP BY u.id
`
type GetUserByEmailRow struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
AvatarUrl pgtype.Text `json:"avatar_url"`
IsActive pgtype.Bool `json:"is_active"`
IsVerified pgtype.Bool `json:"is_verified"`
TokenVersion int32 `json:"token_version"`
IsDeleted pgtype.Bool `json:"is_deleted"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Roles []byte `json:"roles"`
}
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (GetUserByEmailRow, error) {
row := q.db.QueryRow(ctx, getUserByEmail, email)
var i GetUserByEmailRow
err := row.Scan(
&i.ID,
&i.Name,
&i.Email,
&i.PasswordHash,
&i.AvatarUrl,
&i.IsActive,
&i.IsVerified,
&i.TokenVersion,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
&i.Roles,
)
return i, err
}
const getUserByID = `-- name: GetUserByID :one
SELECT
u.id,
u.name,
u.email,
u.password_hash,
u.avatar_url,
u.is_active,
u.is_verified,
u.token_version,
u.refresh_token,
u.is_deleted,
u.created_at,
u.updated_at,
COALESCE(
json_agg(
json_build_object('id', r.id, 'name', r.name)
) FILTER (WHERE r.id IS NOT NULL),
'[]'
)::json AS roles
FROM users u
LEFT JOIN user_roles ur ON u.id = ur.user_id
LEFT JOIN roles r ON ur.role_id = r.id
WHERE u.id = $1 AND u.is_deleted = false
GROUP BY u.id
`
type GetUserByIDRow struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
AvatarUrl pgtype.Text `json:"avatar_url"`
IsActive pgtype.Bool `json:"is_active"`
IsVerified pgtype.Bool `json:"is_verified"`
TokenVersion int32 `json:"token_version"`
RefreshToken pgtype.Text `json:"refresh_token"`
IsDeleted pgtype.Bool `json:"is_deleted"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Roles []byte `json:"roles"`
}
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (GetUserByIDRow, error) {
row := q.db.QueryRow(ctx, getUserByID, id)
var i GetUserByIDRow
err := row.Scan(
&i.ID,
&i.Name,
&i.Email,
&i.PasswordHash,
&i.AvatarUrl,
&i.IsActive,
&i.IsVerified,
&i.TokenVersion,
&i.RefreshToken,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
&i.Roles,
)
return i, err
}
const getUsers = `-- name: GetUsers :many
SELECT
u.id,
u.name,
u.email,
u.password_hash,
u.avatar_url,
u.is_active,
u.is_verified,
u.token_version,
u.refresh_token,
u.is_deleted,
u.created_at,
u.updated_at,
COALESCE(
json_agg(
json_build_object('id', r.id, 'name', r.name)
) FILTER (WHERE r.id IS NOT NULL),
'[]'
)::json AS roles
FROM users u
LEFT JOIN user_roles ur ON u.id = ur.user_id
LEFT JOIN roles r ON ur.role_id = r.id
WHERE u.is_deleted = false
GROUP BY u.id
`
type GetUsersRow struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
AvatarUrl pgtype.Text `json:"avatar_url"`
IsActive pgtype.Bool `json:"is_active"`
IsVerified pgtype.Bool `json:"is_verified"`
TokenVersion int32 `json:"token_version"`
RefreshToken pgtype.Text `json:"refresh_token"`
IsDeleted pgtype.Bool `json:"is_deleted"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Roles []byte `json:"roles"`
}
func (q *Queries) GetUsers(ctx context.Context) ([]GetUsersRow, error) {
rows, err := q.db.Query(ctx, getUsers)
if err != nil {
return nil, err
}
defer rows.Close()
items := []GetUsersRow{}
for rows.Next() {
var i GetUsersRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Email,
&i.PasswordHash,
&i.AvatarUrl,
&i.IsActive,
&i.IsVerified,
&i.TokenVersion,
&i.RefreshToken,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
&i.Roles,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const restoreUser = `-- name: RestoreUser :exec
UPDATE users
SET
is_deleted = false,
updated_at = now()
WHERE id = $1
`
func (q *Queries) RestoreUser(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, restoreUser, id)
return err
}
const updateUser = `-- name: UpdateUser :one
UPDATE users
SET
name = $1,
avatar_url = $2,
is_active = $3,
is_verified = $4,
updated_at = now()
WHERE users.id = $5 AND users.is_deleted = false
RETURNING
users.id,
users.name,
users.email,
users.password_hash,
users.avatar_url,
users.is_active,
users.is_verified,
users.token_version,
users.refresh_token,
users.is_deleted,
users.created_at,
users.updated_at,
(
SELECT COALESCE(json_agg(json_build_object('id', roles.id, 'name', roles.name)), '[]')::json
FROM user_roles
JOIN roles ON user_roles.role_id = roles.id
WHERE user_roles.user_id = users.id
) AS roles
`
type UpdateUserParams struct {
Name string `json:"name"`
AvatarUrl pgtype.Text `json:"avatar_url"`
IsActive pgtype.Bool `json:"is_active"`
IsVerified pgtype.Bool `json:"is_verified"`
ID pgtype.UUID `json:"id"`
}
type UpdateUserRow struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
AvatarUrl pgtype.Text `json:"avatar_url"`
IsActive pgtype.Bool `json:"is_active"`
IsVerified pgtype.Bool `json:"is_verified"`
TokenVersion int32 `json:"token_version"`
RefreshToken pgtype.Text `json:"refresh_token"`
IsDeleted pgtype.Bool `json:"is_deleted"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Roles []byte `json:"roles"`
}
func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) (UpdateUserRow, error) {
row := q.db.QueryRow(ctx, updateUser,
arg.Name,
arg.AvatarUrl,
arg.IsActive,
arg.IsVerified,
arg.ID,
)
var i UpdateUserRow
err := row.Scan(
&i.ID,
&i.Name,
&i.Email,
&i.PasswordHash,
&i.AvatarUrl,
&i.IsActive,
&i.IsVerified,
&i.TokenVersion,
&i.RefreshToken,
&i.IsDeleted,
&i.CreatedAt,
&i.UpdatedAt,
&i.Roles,
)
return i, err
}
const updateUserPassword = `-- name: UpdateUserPassword :exec
UPDATE users
SET
password_hash = $2,
updated_at = now()
WHERE id = $1
AND is_deleted = false
`
type UpdateUserPasswordParams struct {
ID pgtype.UUID `json:"id"`
PasswordHash string `json:"password_hash"`
}
func (q *Queries) UpdateUserPassword(ctx context.Context, arg UpdateUserPasswordParams) error {
_, err := q.db.Exec(ctx, updateUserPassword, arg.ID, arg.PasswordHash)
return err
}
const verifyUser = `-- name: VerifyUser :exec
UPDATE users
SET
is_verified = true,
updated_at = now()
WHERE id = $1
AND is_deleted = false
`
func (q *Queries) VerifyUser(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, verifyUser, id)
return err
}

View File

@@ -0,0 +1,87 @@
package middlewares
import (
"history-api/pkg/config"
"history-api/pkg/constant"
"history-api/pkg/dtos/response"
"slices"
jwtware "github.com/gofiber/contrib/v3/jwt"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/extractors"
)
func JwtAccess() fiber.Handler {
jwtSecret, err := config.GetConfig("JWT_SECRET")
if err != nil {
return nil
}
return jwtware.New(jwtware.Config{
SigningKey: jwtware.SigningKey{Key: []byte(jwtSecret)},
ErrorHandler: jwtError,
SuccessHandler: jwtSuccess,
Extractor: extractors.FromAuthHeader("Bearer"),
Claims: &response.JWTClaims{},
})
}
func JwtRefresh() fiber.Handler {
jwtRefreshSecret, err := config.GetConfig("JWT_REFRESH_SECRET")
if err != nil {
return nil
}
return jwtware.New(jwtware.Config{
SigningKey: jwtware.SigningKey{Key: []byte(jwtRefreshSecret)},
ErrorHandler: jwtError,
SuccessHandler: jwtSuccess,
Extractor: extractors.FromAuthHeader("Bearer"),
Claims: &response.JWTClaims{},
})
}
func jwtSuccess(c fiber.Ctx) error {
user := jwtware.FromContext(c)
unauthorized := func() error {
return c.Status(fiber.StatusUnauthorized).JSON(response.CommonResponse{
Status: false,
Message: "Invalid or missing token",
})
}
if user == nil {
return unauthorized()
}
claims, ok := user.Claims.(*response.JWTClaims)
if !ok {
return unauthorized()
}
if slices.Contains(claims.Roles, constant.BANNED) {
return c.Status(fiber.StatusForbidden).JSON(response.CommonResponse{
Status: false,
Message: "User account is banned",
})
}
c.Locals("uid", claims.UId)
c.Locals("user_claims", claims)
return c.Next()
}
func jwtError(c fiber.Ctx, err error) error {
if err.Error() == "Missing or malformed JWT" {
return c.Status(fiber.StatusBadRequest).
JSON(response.CommonResponse{
Status: false,
Message: "Missing or malformed JWT",
})
}
return c.Status(fiber.StatusUnauthorized).
JSON(response.CommonResponse{
Status: false,
Message: "Invalid or expired JWT",
})
}

View File

@@ -0,0 +1,62 @@
package middlewares
import (
"history-api/pkg/constant"
"history-api/pkg/dtos/response"
"slices"
"github.com/gofiber/fiber/v3"
)
func getRoles(c fiber.Ctx) ([]constant.Role, error) {
claimsVal := c.Locals("user_claims")
if claimsVal == nil {
return nil, fiber.ErrUnauthorized
}
claims, ok := claimsVal.(*response.JWTClaims)
if !ok {
return nil, fiber.ErrUnauthorized
}
return claims.Roles, nil
}
func RequireAnyRole(required ...constant.Role) fiber.Handler {
return func(c fiber.Ctx) error {
userRoles, err := getRoles(c)
if err != nil {
return err
}
if len(userRoles) == 0 {
return fiber.ErrForbidden
}
for _, ur := range userRoles {
if slices.Contains(required, ur) {
return c.Next()
}
}
return fiber.ErrForbidden
}
}
func RequireAllRoles(required ...constant.Role) fiber.Handler {
return func(c fiber.Ctx) error {
userRoles, err := getRoles(c)
if err != nil {
return err
}
for _, rr := range required {
found := slices.Contains(userRoles, rr)
if !found {
return fiber.ErrForbidden
}
}
return c.Next()
}
}

View File

@@ -0,0 +1,148 @@
package repositories
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
"history-api/internal/gen/sqlc"
"history-api/pkg/models"
)
type RoleRepository interface {
GetByID(ctx context.Context, id pgtype.UUID) (*models.RoleEntity, error)
GetByname(ctx context.Context, name string) (*models.RoleEntity, error)
All(ctx context.Context) ([]*models.RoleEntity, error)
Create(ctx context.Context, name string) (*models.RoleEntity, error)
Update(ctx context.Context, params sqlc.UpdateRoleParams) (*models.RoleEntity, error)
Delete(ctx context.Context, id pgtype.UUID) error
Restore(ctx context.Context, id pgtype.UUID) error
AddUserRole(ctx context.Context, params sqlc.AddUserRoleParams) error
RemoveUserRole(ctx context.Context, params sqlc.RemoveUserRoleParams) error
RemoveAllRolesFromUser(ctx context.Context, userId pgtype.UUID) error
RemoveAllUsersFromRole(ctx context.Context, roleId pgtype.UUID) error
}
type roleRepository struct {
q *sqlc.Queries
}
func NewRoleRepository(db sqlc.DBTX) RoleRepository {
return &roleRepository{
q: sqlc.New(db),
}
}
func (r *roleRepository) GetByID(ctx context.Context, id pgtype.UUID) (*models.RoleEntity, error) {
row, err := r.q.GetRoleByID(ctx, id)
if err != nil {
return nil, err
}
role := &models.RoleEntity{
ID: row.ID,
Name: row.Name,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
return role, nil
}
func (r *roleRepository) GetByname(ctx context.Context, name string) (*models.RoleEntity, error) {
row, err := r.q.GetRoleByName(ctx, name)
if err != nil {
return nil, err
}
role := &models.RoleEntity{
ID: row.ID,
Name: row.Name,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
return role, nil
}
func (r *roleRepository) Create(ctx context.Context, name string) (*models.RoleEntity, error) {
row, err := r.q.CreateRole(ctx, name)
if err != nil {
return nil, err
}
role := &models.RoleEntity{
ID: row.ID,
Name: row.Name,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
return role, nil
}
func (r *roleRepository) Update(ctx context.Context, params sqlc.UpdateRoleParams) (*models.RoleEntity, error) {
row, err := r.q.UpdateRole(ctx, params)
if err != nil {
return nil, err
}
role := &models.RoleEntity{
ID: row.ID,
Name: row.Name,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
return role, nil
}
func (r *roleRepository) All(ctx context.Context) ([]*models.RoleEntity, error) {
rows, err := r.q.GetRoles(ctx)
if err != nil {
return nil, err
}
var users []*models.RoleEntity
for _, row := range rows {
user := &models.RoleEntity{
ID: row.ID,
Name: row.Name,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
users = append(users, user)
}
return users, nil
}
func (r *roleRepository) Delete(ctx context.Context, id pgtype.UUID) error {
err := r.q.DeleteRole(ctx, id)
return err
}
func (r *roleRepository) Restore(ctx context.Context, id pgtype.UUID) error {
err := r.q.RestoreRole(ctx, id)
return err
}
func (r *roleRepository) AddUserRole(ctx context.Context, params sqlc.AddUserRoleParams) error {
err := r.q.AddUserRole(ctx, params)
return err
}
func (r *roleRepository) RemoveUserRole(ctx context.Context, params sqlc.RemoveUserRoleParams) error {
err := r.q.RemoveUserRole(ctx, params)
return err
}
func (r *roleRepository) RemoveAllUsersFromRole(ctx context.Context, roleId pgtype.UUID) error {
err := r.q.RemoveAllUsersFromRole(ctx, roleId)
return err
}
func (r *roleRepository) RemoveAllRolesFromUser(ctx context.Context, roleId pgtype.UUID) error {
err := r.q.RemoveAllRolesFromUser(ctx, roleId)
return err
}

View File

@@ -0,0 +1,193 @@
package repositories
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
"history-api/internal/gen/sqlc"
"history-api/pkg/models"
)
type UserRepository interface {
GetByID(ctx context.Context, id pgtype.UUID) (*models.UserEntity, error)
GetByEmail(ctx context.Context, email string) (*models.UserEntity, error)
All(ctx context.Context) ([]*models.UserEntity, error)
Create(ctx context.Context, params sqlc.CreateUserParams) (*models.UserEntity, error)
Update(ctx context.Context, params sqlc.UpdateUserParams) (*models.UserEntity, error)
UpdatePassword(ctx context.Context, params sqlc.UpdateUserPasswordParams) error
ExistEmail(ctx context.Context, email string) (bool, error)
Verify(ctx context.Context, id pgtype.UUID) error
Delete(ctx context.Context, id pgtype.UUID) error
Restore(ctx context.Context, id pgtype.UUID) error
}
type userRepository struct {
q *sqlc.Queries
}
func NewUserRepository(db sqlc.DBTX) UserRepository {
return &userRepository{
q: sqlc.New(db),
}
}
func (r *userRepository) GetByID(ctx context.Context, id pgtype.UUID) (*models.UserEntity, error) {
row, err := r.q.GetUserByID(ctx, id)
if err != nil {
return nil, err
}
user := &models.UserEntity{
ID: row.ID,
Name: row.Name,
Email: row.Email,
PasswordHash: row.PasswordHash,
AvatarUrl: row.AvatarUrl,
IsActive: row.IsActive,
IsVerified: row.IsVerified,
TokenVersion: row.TokenVersion,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if err := user.ParseRoles(row.Roles); err != nil {
return nil, err
}
return user, nil
}
func (r *userRepository) GetByEmail(ctx context.Context, email string) (*models.UserEntity, error) {
row, err := r.q.GetUserByEmail(ctx, email)
if err != nil {
return nil, err
}
user := &models.UserEntity{
ID: row.ID,
Name: row.Name,
Email: row.Email,
PasswordHash: row.PasswordHash,
AvatarUrl: row.AvatarUrl,
IsActive: row.IsActive,
IsVerified: row.IsVerified,
TokenVersion: row.TokenVersion,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if err := user.ParseRoles(row.Roles); err != nil {
return nil, err
}
return user, nil
}
func (r *userRepository) Create(ctx context.Context, params sqlc.CreateUserParams) (*models.UserEntity, error) {
row, err := r.q.CreateUser(ctx, params)
if err != nil {
return nil, err
}
return &models.UserEntity{
ID: row.ID,
Name: row.Name,
Email: row.Email,
PasswordHash: row.PasswordHash,
AvatarUrl: row.AvatarUrl,
IsActive: row.IsActive,
IsVerified: row.IsVerified,
TokenVersion: row.TokenVersion,
RefreshToken: row.RefreshToken,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
Roles: make([]*models.RoleSimple, 0),
}, nil
}
func (r *userRepository) Update(ctx context.Context, params sqlc.UpdateUserParams) (*models.UserEntity, error) {
row, err := r.q.UpdateUser(ctx, params)
if err != nil {
return nil, err
}
user := &models.UserEntity{
ID: row.ID,
Name: row.Name,
Email: row.Email,
PasswordHash: row.PasswordHash,
AvatarUrl: row.AvatarUrl,
IsActive: row.IsActive,
IsVerified: row.IsVerified,
TokenVersion: row.TokenVersion,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if err := user.ParseRoles(row.Roles); err != nil {
return nil, err
}
return user, nil
}
func (r *userRepository) All(ctx context.Context) ([]*models.UserEntity, error) {
rows, err := r.q.GetUsers(ctx)
if err != nil {
return nil, err
}
var users []*models.UserEntity
for _, row := range rows {
user := &models.UserEntity{
ID: row.ID,
Name: row.Name,
Email: row.Email,
PasswordHash: row.PasswordHash,
AvatarUrl: row.AvatarUrl,
IsActive: row.IsActive,
IsVerified: row.IsVerified,
TokenVersion: row.TokenVersion,
IsDeleted: row.IsDeleted,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if err := user.ParseRoles(row.Roles); err != nil {
return nil, err
}
users = append(users, user)
}
return users, nil
}
func (r *userRepository) Verify(ctx context.Context, id pgtype.UUID) error {
err := r.q.VerifyUser(ctx, id)
return err
}
func (r *userRepository) Delete(ctx context.Context, id pgtype.UUID) error {
err := r.q.DeleteUser(ctx, id)
return err
}
func (r *userRepository) Restore(ctx context.Context, id pgtype.UUID) error {
err := r.q.RestoreUser(ctx, id)
return err
}
func (r *userRepository) UpdatePassword(ctx context.Context, params sqlc.UpdateUserPasswordParams) error {
err := r.q.UpdateUserPassword(ctx, params)
return err
}
func (r *userRepository) ExistEmail(ctx context.Context, email string) (bool, error) {
row, err := r.q.ExistsUserByEmail(ctx, email)
if err != nil {
return false, err
}
return row, nil
}

View File

@@ -0,0 +1 @@
package routers

View File

@@ -0,0 +1 @@
package services