Init
This commit is contained in:
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
.history
|
||||
pg_data
|
||||
.idea
|
||||
*.log
|
||||
*.env
|
||||
25
Makefile
Normal file
25
Makefile
Normal file
@@ -0,0 +1,25 @@
|
||||
DB_URL ?= postgres://history:secret@localhost:5432/history_map?sslmode=disable
|
||||
APP = cmd/history-api/
|
||||
|
||||
.PHONY: postgres createdb dropdb migrate-up migrate-down migrate-reset sqlc run build dev
|
||||
|
||||
migrate-up:
|
||||
migrate -path db/migrations -database "$(DB_URL)" up
|
||||
|
||||
migrate-down:
|
||||
migrate -path db/migrations -database "$(DB_URL)" down 1
|
||||
|
||||
migrate-reset:
|
||||
migrate -path db/migrations -database "$(DB_URL)" drop -f
|
||||
migrate -path db/migrations -database "$(DB_URL)" up
|
||||
|
||||
sqlc:
|
||||
sqlc generate
|
||||
|
||||
run:
|
||||
go run $(APP)
|
||||
|
||||
build:
|
||||
go build -o app $(APP)
|
||||
|
||||
dev: sqlc migrate-up run
|
||||
14
assets/embed.go
Normal file
14
assets/embed.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package assets
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed resources/*
|
||||
var files embed.FS
|
||||
|
||||
func GetFileContent(path string) (string, error) {
|
||||
data, err := files.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
104
cmd/history-api/main.go
Normal file
104
cmd/history-api/main.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
// _ "history-api/docs"
|
||||
"history-api/internal/gen/sqlc"
|
||||
"history-api/pkg/cache"
|
||||
"history-api/pkg/config"
|
||||
_ "history-api/pkg/log"
|
||||
|
||||
"fmt"
|
||||
"history-api/pkg/database"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func gracefulShutdown(fiberServer *FiberServer, done chan bool) {
|
||||
// Create context that listens for the interrupt signal from the OS.
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// Listen for the interrupt signal.
|
||||
<-ctx.Done()
|
||||
|
||||
log.Info().Msg("shutting down gracefully, press Ctrl+C again to force")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := fiberServer.App.ShutdownWithContext(ctx); err != nil {
|
||||
log.Info().Msgf("Server forced to shutdown with error: %v", err)
|
||||
}
|
||||
|
||||
log.Info().Msg("Server exiting")
|
||||
|
||||
done <- true
|
||||
}
|
||||
|
||||
//export StartServer
|
||||
func StartServer() {
|
||||
err := config.LoadEnv()
|
||||
if err != nil {
|
||||
log.Error().Msg(err.Error())
|
||||
panic(err)
|
||||
}
|
||||
pool, err := database.Connect()
|
||||
if err != nil {
|
||||
log.Error().Msg(err.Error())
|
||||
panic(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
queries := sqlc.New(pool)
|
||||
|
||||
err = cache.Connect()
|
||||
if err != nil {
|
||||
log.Error().Msg(err.Error())
|
||||
panic(err)
|
||||
}
|
||||
|
||||
serverIp, _ := config.GetConfig("SERVER_IP")
|
||||
if serverIp == "" {
|
||||
serverIp = "127.0.0.1"
|
||||
}
|
||||
|
||||
httpPort, _ := config.GetConfig("SERVER_PORT")
|
||||
if httpPort == "" {
|
||||
httpPort = "3434"
|
||||
}
|
||||
|
||||
serverHttp := NewHttpServer()
|
||||
serverHttp.RegisterFiberRoutes()
|
||||
Singleton = serverHttp
|
||||
|
||||
done := make(chan bool, 1)
|
||||
|
||||
err = serverHttp.App.Listen(fmt.Sprintf("%s:%s", serverIp, httpPort))
|
||||
if err != nil {
|
||||
log.Error().Msgf("Error: app failed to start on port %s, %v", httpPort, err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Run graceful shutdown in a separate goroutine
|
||||
go gracefulShutdown(serverHttp, done)
|
||||
|
||||
// Wait for the graceful shutdown to complete
|
||||
<-done
|
||||
log.Info().Msg("Graceful shutdown complete.")
|
||||
}
|
||||
|
||||
// @title Firefly Manager API
|
||||
// @version 1.0
|
||||
// @description API to update Firefly Manager data
|
||||
// @host localhost:3344
|
||||
// @BasePath /
|
||||
|
||||
// @securityDefinitions.apikey BearerAuth
|
||||
// @in header
|
||||
// @name Authorization
|
||||
func main() {
|
||||
StartServer()
|
||||
}
|
||||
55
cmd/history-api/server.go
Normal file
55
cmd/history-api/server.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
// "history-api/internal/routes"
|
||||
// "history-api/internal/services"
|
||||
|
||||
swagger "github.com/gofiber/contrib/v3/swaggerui"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/cors"
|
||||
"github.com/gofiber/fiber/v3/middleware/logger"
|
||||
)
|
||||
|
||||
var (
|
||||
Singleton *FiberServer
|
||||
)
|
||||
|
||||
type FiberServer struct {
|
||||
App *fiber.App
|
||||
}
|
||||
|
||||
func NewHttpServer() *FiberServer {
|
||||
server := &FiberServer{
|
||||
App: fiber.New(fiber.Config{
|
||||
ServerHeader: "http-server",
|
||||
AppName: "http-server",
|
||||
}),
|
||||
}
|
||||
cfg := swagger.Config{
|
||||
BasePath: "/",
|
||||
FilePath: "./docs/swagger.json",
|
||||
Path: "swagger",
|
||||
Title: "Swagger API Docs",
|
||||
}
|
||||
|
||||
server.App.Use(swagger.New(cfg))
|
||||
server.App.Use(logger.New())
|
||||
return server
|
||||
}
|
||||
|
||||
func (s *FiberServer) RegisterFiberRoutes() {
|
||||
// Apply CORS middleware
|
||||
s.App.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
|
||||
AllowHeaders: []string{"Accept", "Authorization", "Content-Type", "Origin"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 300,
|
||||
}))
|
||||
|
||||
// routes.UserRoutes(s.App)
|
||||
// routes.AuthRoutes(s.App)
|
||||
// routes.MediaRoute(s.App)
|
||||
// routes.NotFoundRoute(s.App)
|
||||
|
||||
}
|
||||
3
db/migrations/000001_init_schema.down.sql
Normal file
3
db/migrations/000001_init_schema.down.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
DROP TABLE IF EXISTS user_roles;
|
||||
DROP TABLE IF EXISTS roles;
|
||||
DROP TABLE IF EXISTS users;
|
||||
121
db/migrations/000001_init_schema.up.sql
Normal file
121
db/migrations/000001_init_schema.up.sql
Normal file
@@ -0,0 +1,121 @@
|
||||
CREATE EXTENSION IF NOT EXISTS postgis;
|
||||
|
||||
-- CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
google_id VARCHAR(255) UNIQUE,
|
||||
auth_provider VARCHAR(50) NOT NULL DEFAULT 'local',
|
||||
is_verified BOOLEAN NOT NULL DEFAULT false,
|
||||
is_deleted BOOLEAN NOT NULL DEFAULT false,
|
||||
token_version INT NOT NULL DEFAULT 1,
|
||||
refresh_token TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_profiles (
|
||||
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
display_name TEXT,
|
||||
full_name TEXT,
|
||||
avatar_url TEXT,
|
||||
bio TEXT,
|
||||
location TEXT,
|
||||
website TEXT,
|
||||
country_code CHAR(2),
|
||||
phone TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_verifications (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||
verify_type SMALLINT NOT NULL, -- 1 = ID_CARD, 2 = EDUCATION, 3 = EXPERT
|
||||
document_url TEXT NOT NULL,
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- 1 pending, 2 approved, 3 rejected
|
||||
reviewed_by UUID REFERENCES users(id),
|
||||
reviewed_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
is_deleted BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_roles (
|
||||
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||
role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, role_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_users_active_created_at
|
||||
ON users (created_at DESC)
|
||||
WHERE is_deleted = false;
|
||||
|
||||
CREATE INDEX idx_users_email_active
|
||||
ON users (email)
|
||||
WHERE is_deleted = false;
|
||||
|
||||
CREATE INDEX idx_users_active_verified
|
||||
ON users (is_active, is_verified)
|
||||
WHERE is_deleted = false;
|
||||
|
||||
CREATE INDEX idx_user_roles_user_id
|
||||
ON user_roles (user_id);
|
||||
|
||||
CREATE INDEX idx_user_roles_role_id
|
||||
ON user_roles (role_id);
|
||||
|
||||
CREATE INDEX idx_roles_active
|
||||
ON roles (name)
|
||||
WHERE is_deleted = false;
|
||||
|
||||
INSERT INTO roles (name) VALUES
|
||||
('USER'),
|
||||
('ADMIN'),
|
||||
('MOD'),
|
||||
('HISTORIAN'),
|
||||
('BANNED')
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
CREATE OR REPLACE FUNCTION update_updated_at()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = NOW();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER trigger_users_updated_at
|
||||
BEFORE UPDATE ON users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at();
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_tokens (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token VARCHAR(255) NOT NULL UNIQUE,
|
||||
token_type SMALLINT NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_tokens_token
|
||||
ON user_tokens(token);
|
||||
|
||||
CREATE INDEX idx_user_tokens_user_id
|
||||
ON user_tokens(user_id);
|
||||
|
||||
CREATE INDEX idx_user_tokens_type
|
||||
ON user_tokens(token_type);
|
||||
|
||||
CREATE INDEX idx_user_tokens_expires_at
|
||||
ON user_tokens(expires_at);
|
||||
61
db/query/roles.sql
Normal file
61
db/query/roles.sql
Normal file
@@ -0,0 +1,61 @@
|
||||
-- name: CreateRole :one
|
||||
INSERT INTO roles (name)
|
||||
VALUES ($1)
|
||||
RETURNING *;
|
||||
|
||||
-- name: GetRoleByName :one
|
||||
SELECT id, name, is_deleted, created_at, updated_at FROM roles
|
||||
WHERE name = $1 AND is_deleted = false;
|
||||
|
||||
-- name: GetRoleByID :one
|
||||
SELECT id, name, is_deleted, created_at, updated_at FROM roles
|
||||
WHERE id = $1 AND is_deleted = false;
|
||||
|
||||
-- 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;
|
||||
|
||||
-- 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;
|
||||
|
||||
-- name: RemoveAllRolesFromUser :exec
|
||||
DELETE FROM user_roles
|
||||
WHERE user_id = $1;
|
||||
|
||||
-- name: RemoveAllUsersFromRole :exec
|
||||
DELETE FROM user_roles
|
||||
WHERE role_id = $1;
|
||||
|
||||
-- name: GetRoles :many
|
||||
SELECT *
|
||||
FROM roles
|
||||
WHERE is_deleted = false;
|
||||
|
||||
-- name: UpdateRole :one
|
||||
UPDATE roles
|
||||
SET
|
||||
name = $1,
|
||||
updated_at = now()
|
||||
WHERE id = $2 AND is_deleted = false
|
||||
RETURNING *;
|
||||
|
||||
-- name: DeleteRole :exec
|
||||
UPDATE roles
|
||||
SET
|
||||
is_deleted = true,
|
||||
updated_at = now()
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: RestoreRole :exec
|
||||
UPDATE roles
|
||||
SET
|
||||
is_deleted = false,
|
||||
updated_at = now()
|
||||
WHERE id = $1;
|
||||
157
db/query/users.sql
Normal file
157
db/query/users.sql
Normal file
@@ -0,0 +1,157 @@
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users (
|
||||
name,
|
||||
email,
|
||||
password_hash,
|
||||
avatar_url
|
||||
) VALUES (
|
||||
$1, $2, $3, $4
|
||||
)
|
||||
RETURNING *;
|
||||
|
||||
-- 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;
|
||||
|
||||
-- name: UpdateUserPassword :exec
|
||||
UPDATE users
|
||||
SET
|
||||
password_hash = $2
|
||||
WHERE id = $1
|
||||
AND is_deleted = false;
|
||||
|
||||
-- name: UpdateUserRefreshToken :exec
|
||||
UPDATE users
|
||||
SET
|
||||
refresh_token = $2
|
||||
WHERE id = $1
|
||||
AND is_deleted = false;
|
||||
|
||||
|
||||
-- name: VerifyUser :exec
|
||||
UPDATE users
|
||||
SET
|
||||
is_verified = true
|
||||
WHERE id = $1
|
||||
AND is_deleted = false;
|
||||
|
||||
-- name: DeleteUser :exec
|
||||
UPDATE users
|
||||
SET
|
||||
is_deleted = true
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: RestoreUser :exec
|
||||
UPDATE users
|
||||
SET
|
||||
is_deleted = false
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: ExistsUserByEmail :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM users
|
||||
WHERE email = $1
|
||||
AND is_deleted = false
|
||||
);
|
||||
|
||||
-- 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;
|
||||
|
||||
-- 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;
|
||||
|
||||
-- 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;
|
||||
61
db/schema.sql
Normal file
61
db/schema.sql
Normal file
@@ -0,0 +1,61 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
google_id VARCHAR(255) UNIQUE,
|
||||
auth_provider VARCHAR(50) NOT NULL DEFAULT 'local',
|
||||
is_verified BOOLEAN DEFAULT false,
|
||||
token_version INT NOT NULL DEFAULT 1,
|
||||
refresh_token TEXT,
|
||||
is_deleted BOOLEAN DEFAULT false,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_profiles (
|
||||
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
display_name TEXT,
|
||||
full_name TEXT,
|
||||
avatar_url TEXT,
|
||||
bio TEXT,
|
||||
location TEXT,
|
||||
website TEXT,
|
||||
country_code CHAR(2),
|
||||
phone TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_verifications (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||
verify_type SMALLINT NOT NULL, -- 1 = ID_CARD, 2 = EDUCATION, 3 = EXPERT
|
||||
document_url TEXT NOT NULL,
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- 1 pending, 2 approved, 3 rejected
|
||||
reviewed_by UUID REFERENCES users(id),
|
||||
reviewed_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
is_deleted BOOLEAN DEFAULT false,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_roles (
|
||||
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
|
||||
role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, role_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_tokens (
|
||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token VARCHAR(255) NOT NULL UNIQUE, --1 = PasswordReset, 2 = EmailVerify, 3 = MagicLink, 4 = RefreshToken
|
||||
token_type SMALLINT NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
29
docker-compose.yml
Normal file
29
docker-compose.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
services:
|
||||
db:
|
||||
image: postgis/postgis:18-3.6
|
||||
container_name: history_db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: history
|
||||
POSTGRES_PASSWORD: secret
|
||||
POSTGRES_DB: history_map
|
||||
PGDATA: /var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- ./pg_data:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U history -d history_map"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
cache:
|
||||
image: redis:8.6.1-alpine
|
||||
container_name: history_redis
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6379:6379"
|
||||
|
||||
volumes:
|
||||
pg_data:
|
||||
69
go.mod
Normal file
69
go.mod
Normal file
@@ -0,0 +1,69 @@
|
||||
module history-api
|
||||
|
||||
go 1.26.1
|
||||
|
||||
require (
|
||||
github.com/go-playground/validator/v10 v10.30.1
|
||||
github.com/gofiber/contrib/v3/jwt v1.1.0
|
||||
github.com/gofiber/contrib/v3/swaggerui v1.0.1
|
||||
github.com/gofiber/fiber/v3 v3.1.0
|
||||
github.com/jackc/pgx/v5 v5.8.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/redis/go-redis/v9 v9.18.0
|
||||
github.com/rs/zerolog v1.34.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0 // indirect
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/go-openapi/analysis v0.24.2 // indirect
|
||||
github.com/go-openapi/errors v0.22.6 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.22.4 // indirect
|
||||
github.com/go-openapi/jsonreference v0.21.4 // indirect
|
||||
github.com/go-openapi/loads v0.23.2 // indirect
|
||||
github.com/go-openapi/runtime v0.29.2 // indirect
|
||||
github.com/go-openapi/spec v0.22.3 // indirect
|
||||
github.com/go-openapi/strfmt v0.25.0 // indirect
|
||||
github.com/go-openapi/swag/conv v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/fileutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/jsonutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/loading v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/mangling v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/stringutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4 // indirect
|
||||
github.com/go-openapi/validate v0.25.1 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/gofiber/schema v1.7.0 // indirect
|
||||
github.com/gofiber/utils/v2 v2.0.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.18.4 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/oklog/ulid v1.3.1 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.3 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.69.0 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.9 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
178
go.sum
Normal file
178
go.sum
Normal file
@@ -0,0 +1,178 @@
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k=
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0/go.mod h1:rW42fi+xgLJ2FRRXAfNx9ZA8WpD4OeE/yHVMteCkw9k=
|
||||
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
|
||||
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/go-openapi/analysis v0.24.2 h1:6p7WXEuKy1llDgOH8FooVeO+Uq2za9qoAOq4ZN08B50=
|
||||
github.com/go-openapi/analysis v0.24.2/go.mod h1:x27OOHKANE0lutg2ml4kzYLoHGMKgRm1Cj2ijVOjJuE=
|
||||
github.com/go-openapi/errors v0.22.6 h1:eDxcf89O8odEnohIXwEjY1IB4ph5vmbUsBMsFNwXWPo=
|
||||
github.com/go-openapi/errors v0.22.6/go.mod h1:z9S8ASTUqx7+CP1Q8dD8ewGH/1JWFFLX/2PmAYNQLgk=
|
||||
github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4=
|
||||
github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80=
|
||||
github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8=
|
||||
github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4=
|
||||
github.com/go-openapi/loads v0.23.2 h1:rJXAcP7g1+lWyBHC7iTY+WAF0rprtM+pm8Jxv1uQJp4=
|
||||
github.com/go-openapi/loads v0.23.2/go.mod h1:IEVw1GfRt/P2Pplkelxzj9BYFajiWOtY2nHZNj4UnWY=
|
||||
github.com/go-openapi/runtime v0.29.2 h1:UmwSGWNmWQqKm1c2MGgXVpC2FTGwPDQeUsBMufc5Yj0=
|
||||
github.com/go-openapi/runtime v0.29.2/go.mod h1:biq5kJXRJKBJxTDJXAa00DOTa/anflQPhT0/wmjuy+0=
|
||||
github.com/go-openapi/spec v0.22.3 h1:qRSmj6Smz2rEBxMnLRBMeBWxbbOvuOoElvSvObIgwQc=
|
||||
github.com/go-openapi/spec v0.22.3/go.mod h1:iIImLODL2loCh3Vnox8TY2YWYJZjMAKYyLH2Mu8lOZs=
|
||||
github.com/go-openapi/strfmt v0.25.0 h1:7R0RX7mbKLa9EYCTHRcCuIPcaqlyQiWNPTXwClK0saQ=
|
||||
github.com/go-openapi/strfmt v0.25.0/go.mod h1:nNXct7OzbwrMY9+5tLX4I21pzcmE6ccMGXl3jFdPfn8=
|
||||
github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4=
|
||||
github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU=
|
||||
github.com/go-openapi/swag/fileutils v0.25.4 h1:2oI0XNW5y6UWZTC7vAxC8hmsK/tOkWXHJQH4lKjqw+Y=
|
||||
github.com/go-openapi/swag/fileutils v0.25.4/go.mod h1:cdOT/PKbwcysVQ9Tpr0q20lQKH7MGhOEb6EwmHOirUk=
|
||||
github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI=
|
||||
github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag=
|
||||
github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA=
|
||||
github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM=
|
||||
github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s=
|
||||
github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE=
|
||||
github.com/go-openapi/swag/mangling v0.25.4 h1:2b9kBJk9JvPgxr36V23FxJLdwBrpijI26Bx5JH4Hp48=
|
||||
github.com/go-openapi/swag/mangling v0.25.4/go.mod h1:6dxwu6QyORHpIIApsdZgb6wBk/DPU15MdyYj/ikn0Hg=
|
||||
github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8=
|
||||
github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0=
|
||||
github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw=
|
||||
github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE=
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw=
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg=
|
||||
github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=
|
||||
github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
|
||||
github.com/go-openapi/validate v0.25.1 h1:sSACUI6Jcnbo5IWqbYHgjibrhhmt3vR6lCzKZnmAgBw=
|
||||
github.com/go-openapi/validate v0.25.1/go.mod h1:RMVyVFYte0gbSTaZ0N4KmTn6u/kClvAFp+mAVfS/DQc=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/gofiber/contrib/v3/jwt v1.1.0 h1:RmQHJGNlOF+1hy69AJo+YiVcLTUKA2bXy/yjAzT6UOI=
|
||||
github.com/gofiber/contrib/v3/jwt v1.1.0/go.mod h1:THoVk0kTAkLJFunaNxk8fRO5WYfrwV4k/8oFAoa7UCM=
|
||||
github.com/gofiber/contrib/v3/swaggerui v1.0.1 h1:o3EdD0VQjeL4rq1gBxQB5bUEYMNT3eGKxpg2hjPIigI=
|
||||
github.com/gofiber/contrib/v3/swaggerui v1.0.1/go.mod h1:tIqJ2SDnY7AfqsJHllyaF2vuhkKeBBCHtwWsZrFLCkk=
|
||||
github.com/gofiber/fiber/v3 v3.1.0 h1:1p4I820pIa+FGxfwWuQZ5rAyX0WlGZbGT6Hnuxt6hKY=
|
||||
github.com/gofiber/fiber/v3 v3.1.0/go.mod h1:n2nYQovvL9z3Too/FGOfgtERjW3GQcAUqgfoezGBZdU=
|
||||
github.com/gofiber/schema v1.7.0 h1:yNM+FNRZjyYEli9Ey0AXRBrAY9jTnb+kmGs3lJGPvKg=
|
||||
github.com/gofiber/schema v1.7.0/go.mod h1:A/X5Ffyru4p9eBdp99qu+nzviHzQiZ7odLT+TwxWhbk=
|
||||
github.com/gofiber/utils/v2 v2.0.2 h1:ShRRssz0F3AhTlAQcuEj54OEDtWF7+HJDwEi/aa6QLI=
|
||||
github.com/gofiber/utils/v2 v2.0.2/go.mod h1:+9Ub4NqQ+IaJoTliq5LfdmOJAA/Hzwf4pXOxOa3RrJ0=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
|
||||
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
|
||||
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
github.com/shamaton/msgpack/v3 v3.1.0 h1:jsk0vEAqVvvS9+fTZ5/EcQ9tz860c9pWxJ4Iwecz8gU=
|
||||
github.com/shamaton/msgpack/v3 v3.1.0/go.mod h1:DcQG8jrdrQCIxr3HlMYkiXdMhK+KfN2CitkyzsQV4uc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tinylib/msgp v1.6.3 h1:bCSxiTz386UTgyT1i0MSCvdbWjVW+8sG3PjkGsZQt4s=
|
||||
github.com/tinylib/msgp v1.6.3/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.69.0 h1:fNLLESD2SooWeh2cidsuFtOcrEi4uB4m1mPrkJMZyVI=
|
||||
github.com/valyala/fasthttp v1.69.0/go.mod h1:4wA4PfAraPlAsJ5jMSqCE2ug5tqUPwKXxVj8oNECGcw=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
|
||||
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
1
internal/controllers/authController.go
Normal file
1
internal/controllers/authController.go
Normal file
@@ -0,0 +1 @@
|
||||
package controllers
|
||||
32
internal/gen/sqlc/db.go
Normal file
32
internal/gen/sqlc/db.go
Normal 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,
|
||||
}
|
||||
}
|
||||
46
internal/gen/sqlc/models.go
Normal file
46
internal/gen/sqlc/models.go
Normal 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"`
|
||||
}
|
||||
208
internal/gen/sqlc/roles.sql.go
Normal file
208
internal/gen/sqlc/roles.sql.go
Normal 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
|
||||
}
|
||||
413
internal/gen/sqlc/users.sql.go
Normal file
413
internal/gen/sqlc/users.sql.go
Normal 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
|
||||
}
|
||||
87
internal/middlewares/jwtMiddleware.go
Normal file
87
internal/middlewares/jwtMiddleware.go
Normal 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",
|
||||
})
|
||||
}
|
||||
62
internal/middlewares/roleMiddleware.go
Normal file
62
internal/middlewares/roleMiddleware.go
Normal 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()
|
||||
}
|
||||
}
|
||||
148
internal/repositories/roleRepository.go
Normal file
148
internal/repositories/roleRepository.go
Normal 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
|
||||
}
|
||||
|
||||
|
||||
193
internal/repositories/userRepository.go
Normal file
193
internal/repositories/userRepository.go
Normal 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
|
||||
}
|
||||
1
internal/routers/authRoutes.go
Normal file
1
internal/routers/authRoutes.go
Normal file
@@ -0,0 +1 @@
|
||||
package routers
|
||||
1
internal/services/authService.go
Normal file
1
internal/services/authService.go
Normal file
@@ -0,0 +1 @@
|
||||
package services
|
||||
32
pkg/cache/redis.go
vendored
Normal file
32
pkg/cache/redis.go
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"history-api/pkg/config"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var RI *redis.Client
|
||||
|
||||
func Connect() error {
|
||||
connectionURI, err := config.GetConfig("REDIS_CONNECTION_URI")
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: connectionURI,
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
if err := rdb.Ping(context.Background()).Err(); err != nil {
|
||||
return fmt.Errorf("Could not connect to Redis: %v", err)
|
||||
}
|
||||
|
||||
RI = rdb
|
||||
return nil
|
||||
}
|
||||
36
pkg/config/config.go
Normal file
36
pkg/config/config.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"history-api/assets"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
func LoadEnv() error {
|
||||
envData, err := assets.GetFileContent("resources/.env")
|
||||
if err != nil {
|
||||
return errors.New("error read .env file")
|
||||
}
|
||||
envMap, err := godotenv.Parse(strings.NewReader(envData))
|
||||
if err != nil {
|
||||
return errors.New("error parsing .env content")
|
||||
}
|
||||
|
||||
for key, value := range envMap {
|
||||
os.Setenv(key, value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetConfig(config string) (string, error) {
|
||||
var data string = os.Getenv(config)
|
||||
if data == "" {
|
||||
return "", fmt.Errorf("config (%s) dose not exit", config)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
27
pkg/constant/role.go
Normal file
27
pkg/constant/role.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package constant
|
||||
|
||||
type Role string
|
||||
|
||||
const (
|
||||
ADMIN Role = "ADMIN"
|
||||
MOD Role = "MOD"
|
||||
USER Role = "USER"
|
||||
HISTORIAN Role = "HISTORIAN"
|
||||
BANNED Role = "BANNED"
|
||||
)
|
||||
|
||||
func (r Role) String() string {
|
||||
return string(r)
|
||||
}
|
||||
|
||||
func (r Role) Compare(other Role) bool {
|
||||
return r == other
|
||||
}
|
||||
|
||||
func CheckValidRole(r Role) bool {
|
||||
return r == ADMIN || r == MOD || r == HISTORIAN || r == USER || r == BANNED
|
||||
}
|
||||
|
||||
func (r Role) ToSlice() []string {
|
||||
return []string{r.String()}
|
||||
}
|
||||
35
pkg/constant/status.go
Normal file
35
pkg/constant/status.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package constant
|
||||
|
||||
type StatusType int16
|
||||
|
||||
const (
|
||||
StatusPending StatusType = 1
|
||||
StatusApproved StatusType = 2
|
||||
StatusRejected StatusType = 3
|
||||
)
|
||||
|
||||
func (t StatusType) String() string {
|
||||
switch t {
|
||||
case StatusPending:
|
||||
return "PENDING"
|
||||
case StatusApproved:
|
||||
return "APPROVED"
|
||||
case StatusRejected:
|
||||
return "REJECT"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
func ParseStatusType(v int16) StatusType {
|
||||
switch v {
|
||||
case 1:
|
||||
return StatusPending
|
||||
case 2:
|
||||
return StatusApproved
|
||||
case 3:
|
||||
return StatusRejected
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
40
pkg/constant/token.go
Normal file
40
pkg/constant/token.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package constant
|
||||
|
||||
type TokenType int16
|
||||
|
||||
const (
|
||||
TokenPasswordReset TokenType = 1
|
||||
TokenEmailVerify TokenType = 2
|
||||
TokenMagicLink TokenType = 3
|
||||
TokenRefreshToken TokenType = 4
|
||||
)
|
||||
|
||||
func (t TokenType) String() string {
|
||||
switch t {
|
||||
case TokenPasswordReset:
|
||||
return "PASSWORD_RESET"
|
||||
case TokenEmailVerify:
|
||||
return "EMAIL_VERIFY"
|
||||
case TokenMagicLink:
|
||||
return "LOGIN_MAGIC_LINK"
|
||||
case TokenRefreshToken:
|
||||
return "REFRESH_TOKEN"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
func ParseTokenType(v int16) TokenType {
|
||||
switch v {
|
||||
case 1:
|
||||
return TokenPasswordReset
|
||||
case 2:
|
||||
return TokenEmailVerify
|
||||
case 3:
|
||||
return TokenMagicLink
|
||||
case 4:
|
||||
return TokenRefreshToken
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
35
pkg/constant/verify.go
Normal file
35
pkg/constant/verify.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package constant
|
||||
|
||||
type VerifyType int16
|
||||
|
||||
const (
|
||||
VerifyIdCard VerifyType = 1
|
||||
VerifyEducation VerifyType = 2
|
||||
VerifyExpert VerifyType = 3
|
||||
)
|
||||
|
||||
func (t VerifyType) String() string {
|
||||
switch t {
|
||||
case VerifyIdCard:
|
||||
return "ID_CARD"
|
||||
case VerifyEducation:
|
||||
return "EDUCATION"
|
||||
case VerifyExpert:
|
||||
return "EXPERT"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
func ParseVerifyType(v int16) VerifyType {
|
||||
switch v {
|
||||
case 1:
|
||||
return VerifyIdCard
|
||||
case 2:
|
||||
return VerifyEducation
|
||||
case 3:
|
||||
return VerifyExpert
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
32
pkg/convert/convert.go
Normal file
32
pkg/convert/convert.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package convert
|
||||
|
||||
import "github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
func UUIDToString(v pgtype.UUID) string {
|
||||
if v.Valid {
|
||||
return v.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TextToString(v pgtype.Text) string {
|
||||
if v.Valid {
|
||||
return v.String
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func BoolVal(v pgtype.Bool) bool {
|
||||
if v.Valid {
|
||||
return v.Bool
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TimeToPtr(v pgtype.Timestamptz) *string {
|
||||
if v.Valid {
|
||||
t := v.Time.Format("2006-01-02T15:04:05Z07:00")
|
||||
return &t
|
||||
}
|
||||
return nil
|
||||
}
|
||||
32
pkg/database/db.go
Normal file
32
pkg/database/db.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"history-api/pkg/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Connect() (*pgxpool.Pool, error) {
|
||||
ctx := context.Background()
|
||||
connectionURI, err := config.GetConfig("PGX_CONNECTION_URI")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(connectionURI)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
13
pkg/dtos/request/auth.go
Normal file
13
pkg/dtos/request/auth.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package request
|
||||
|
||||
type SignUpDto struct {
|
||||
Password string `json:"password" validate:"required"`
|
||||
DiscordUserId string `json:"discord_user_id" validate:"required"`
|
||||
Username string `json:"username" validate:"required"`
|
||||
}
|
||||
|
||||
type LoginDto struct {
|
||||
Username string `json:"username" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
21
pkg/dtos/request/media.go
Normal file
21
pkg/dtos/request/media.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package request
|
||||
|
||||
type PreSignedDto struct {
|
||||
FileName string `json:"fileName" validate:"required"`
|
||||
ContentType string `json:"contentType" validate:"required"`
|
||||
}
|
||||
|
||||
type PreSignedCompleteDto struct {
|
||||
FileName string `json:"fileName" validate:"required"`
|
||||
MediaId string `json:"mediaId" validate:"required"`
|
||||
PublicUrl string `json:"publicUrl" validate:"required"`
|
||||
}
|
||||
|
||||
type SearchMediaDto struct {
|
||||
MediaId string `query:"media_id" validate:"omitempty"`
|
||||
FileName string `query:"file_name" validate:"omitempty"`
|
||||
SortBy string `query:"sort_by" default:"created_at" validate:"oneof=created_at updated_at"`
|
||||
Order string `query:"order" default:"desc" validate:"oneof=asc desc"`
|
||||
Page int `query:"page" default:"1" validate:"min=1"`
|
||||
Limit int `query:"limit" default:"10" validate:"min=1,max=100"`
|
||||
}
|
||||
26
pkg/dtos/request/user.go
Normal file
26
pkg/dtos/request/user.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package request
|
||||
|
||||
import "history-api/pkg/constant"
|
||||
|
||||
type CreateUserDto struct {
|
||||
Username string `json:"username" validate:"required"`
|
||||
Password string `json:"password" validate:"required"`
|
||||
DiscordUserId string `json:"discord_user_id" validate:"required"`
|
||||
Role []constant.Role `json:"role" validate:"required"`
|
||||
}
|
||||
|
||||
type UpdateUserDto struct {
|
||||
Password *string `json:"password" validate:"omitempty"`
|
||||
DiscordUserId *string `json:"discord_user_id" validate:"omitempty"`
|
||||
Role *[]constant.Role `json:"role" validate:"omitempty"`
|
||||
}
|
||||
|
||||
type SearchUserDto struct {
|
||||
Username *string `query:"username" validate:"omitempty"`
|
||||
DiscordUserId *string `query:"discord_user_id" validate:"omitempty"`
|
||||
Role *[]constant.Role `query:"role" validate:"omitempty"`
|
||||
SortBy string `query:"sort_by" default:"created_at" validate:"oneof=created_at updated_at"`
|
||||
Order string `query:"order" default:"desc" validate:"oneof=asc desc"`
|
||||
Page int `query:"page" default:"1" validate:"min=1"`
|
||||
Limit int `query:"limit" default:"10" validate:"min=1,max=100"`
|
||||
}
|
||||
6
pkg/dtos/response/auth.go
Normal file
6
pkg/dtos/response/auth.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package response
|
||||
|
||||
type AuthResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
19
pkg/dtos/response/common.go
Normal file
19
pkg/dtos/response/common.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"history-api/pkg/constant"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type CommonResponse struct {
|
||||
Status bool `json:"status"`
|
||||
Data any `json:"data"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type JWTClaims struct {
|
||||
UId string `json:"uid"`
|
||||
Roles []constant.Role `json:"roles"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
9
pkg/dtos/response/media.go
Normal file
9
pkg/dtos/response/media.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package response
|
||||
|
||||
type PreSignedResponse struct {
|
||||
UploadUrl string `json:"uploadUrl"`
|
||||
PublicUrl string `json:"publicUrl"`
|
||||
FileName string `json:"fileName"`
|
||||
MediaId string `json:"mediaId"`
|
||||
SignedHeaders map[string]string `json:"signedHeaders"`
|
||||
}
|
||||
14
pkg/dtos/response/role.go
Normal file
14
pkg/dtos/response/role.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package response
|
||||
|
||||
type RoleSimpleResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type RoleResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsDeleted bool `json:"is_deleted"`
|
||||
CreatedAt *string `json:"created_at"`
|
||||
UpdatedAt *string `json:"updated_at"`
|
||||
}
|
||||
9
pkg/dtos/response/token.go
Normal file
9
pkg/dtos/response/token.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package response
|
||||
|
||||
type TokenResponse struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
TokenType int16 `json:"token_type"`
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
CreatedAt *string `json:"created_at"`
|
||||
}
|
||||
15
pkg/dtos/response/user.go
Normal file
15
pkg/dtos/response/user.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package response
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
AvatarUrl string `json:"avatar_url"`
|
||||
IsActive bool `json:"is_active"`
|
||||
IsVerified bool `json:"is_verified"`
|
||||
TokenVersion int32 `json:"token_version"`
|
||||
IsDeleted bool `json:"is_deleted"`
|
||||
CreatedAt *string `json:"created_at"`
|
||||
UpdatedAt *string `json:"updated_at"`
|
||||
Roles []*RoleSimpleResponse `json:"roles"`
|
||||
}
|
||||
17
pkg/log/log.go
Normal file
17
pkg/log/log.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func init() {
|
||||
output := zerolog.ConsoleWriter{
|
||||
Out: os.Stdout,
|
||||
PartsOrder: []string{"level", "message"},
|
||||
}
|
||||
|
||||
log.Logger = zerolog.New(output).With().Logger()
|
||||
}
|
||||
54
pkg/models/role.go
Normal file
54
pkg/models/role.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"history-api/pkg/dtos/response"
|
||||
"history-api/pkg/convert"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type RoleSimple struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (r *RoleSimple) ToResponse() *response.RoleSimpleResponse {
|
||||
return &response.RoleSimpleResponse{
|
||||
ID: convert.UUIDToString(r.ID),
|
||||
Name: r.Name,
|
||||
}
|
||||
}
|
||||
|
||||
func RolesToResponse(rs []*RoleSimple) []*response.RoleSimpleResponse {
|
||||
out := make([]*response.RoleSimpleResponse, len(rs))
|
||||
for i := range rs {
|
||||
out[i] = rs[i].ToResponse()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type RoleEntity 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"`
|
||||
}
|
||||
|
||||
func (r *RoleEntity) ToResponse() *response.RoleResponse {
|
||||
return &response.RoleResponse{
|
||||
ID: convert.UUIDToString(r.ID),
|
||||
Name: r.Name,
|
||||
IsDeleted: convert.BoolVal(r.IsDeleted),
|
||||
CreatedAt: convert.TimeToPtr(r.CreatedAt),
|
||||
UpdatedAt: convert.TimeToPtr(r.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func RolesEntityToResponse(rs []*RoleEntity) []*response.RoleResponse {
|
||||
out := make([]*response.RoleResponse, len(rs))
|
||||
for i := range rs {
|
||||
out[i] = rs[i].ToResponse()
|
||||
}
|
||||
return out
|
||||
}
|
||||
35
pkg/models/token.go
Normal file
35
pkg/models/token.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"history-api/pkg/convert"
|
||||
"history-api/pkg/dtos/response"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type TokenEntity 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"`
|
||||
}
|
||||
|
||||
func (t *TokenEntity) ToResponse() *response.TokenResponse {
|
||||
return &response.TokenResponse{
|
||||
ID: convert.UUIDToString(t.ID),
|
||||
UserID: convert.UUIDToString(t.UserID),
|
||||
TokenType: t.TokenType,
|
||||
ExpiresAt: convert.TimeToPtr(t.ExpiresAt),
|
||||
CreatedAt: convert.TimeToPtr(t.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func TokensEntityToResponse(ts []*TokenEntity) []*response.TokenResponse {
|
||||
out := make([]*response.TokenResponse, len(ts))
|
||||
for i := range ts {
|
||||
out[i] = ts[i].ToResponse()
|
||||
}
|
||||
return out
|
||||
}
|
||||
58
pkg/models/user.go
Normal file
58
pkg/models/user.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"history-api/pkg/convert"
|
||||
"history-api/pkg/dtos/response"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type UserEntity 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 []*RoleSimple `json:"roles"`
|
||||
}
|
||||
|
||||
func (u *UserEntity) ParseRoles(data []byte) error {
|
||||
if len(data) == 0 {
|
||||
u.Roles = []*RoleSimple{}
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(data, &u.Roles)
|
||||
}
|
||||
|
||||
func (u *UserEntity) ToResponse() *response.UserResponse {
|
||||
return &response.UserResponse{
|
||||
ID: convert.UUIDToString(u.ID),
|
||||
Name: u.Name,
|
||||
Email: u.Email,
|
||||
AvatarUrl: convert.TextToString(u.AvatarUrl),
|
||||
IsActive: convert.BoolVal(u.IsActive),
|
||||
IsVerified: convert.BoolVal(u.IsVerified),
|
||||
TokenVersion: u.TokenVersion,
|
||||
IsDeleted: convert.BoolVal(u.IsDeleted),
|
||||
CreatedAt: convert.TimeToPtr(u.CreatedAt),
|
||||
UpdatedAt: convert.TimeToPtr(u.UpdatedAt),
|
||||
Roles: RolesToResponse(u.Roles),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func UsersEntityToResponse(rs []*UserEntity) []*response.UserResponse {
|
||||
out := make([]*response.UserResponse, len(rs))
|
||||
for i := range rs {
|
||||
out[i] = rs[i].ToResponse()
|
||||
}
|
||||
return out
|
||||
}
|
||||
82
pkg/validator/validator.go
Normal file
82
pkg/validator/validator.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
var validate = validator.New()
|
||||
|
||||
func init() {
|
||||
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
|
||||
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
|
||||
if name == "-" {
|
||||
return ""
|
||||
}
|
||||
if name == "" {
|
||||
name = strings.SplitN(fld.Tag.Get("query"), ",", 2)[0]
|
||||
}
|
||||
return name
|
||||
})
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
FailedField string `json:"failed_field"`
|
||||
Tag string `json:"tag"`
|
||||
Value string `json:"value"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func formatValidationError(err error) []ErrorResponse {
|
||||
var validationErrors validator.ValidationErrors
|
||||
var errorsList []ErrorResponse
|
||||
|
||||
if errors.As(err, &validationErrors) {
|
||||
for _, fieldError := range validationErrors {
|
||||
var element ErrorResponse
|
||||
element.FailedField = fieldError.Field()
|
||||
element.Tag = fieldError.Tag()
|
||||
element.Value = fieldError.Param()
|
||||
element.Message = "Field " + fieldError.Field() + " failed validation on tag '" + fieldError.Tag() + "'"
|
||||
|
||||
errorsList = append(errorsList, element)
|
||||
}
|
||||
}
|
||||
return errorsList
|
||||
}
|
||||
|
||||
func ValidateQueryDto(c fiber.Ctx, dto any) error {
|
||||
if err := c.Bind().Query(dto); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"error": "Failed to parse query parameters: " + err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
if err := validate.Struct(dto); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"errors": formatValidationError(err),
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateBodyDto(c fiber.Ctx, dto any) error {
|
||||
if err := c.Bind().Body(dto); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"error": "Invalid request body: " + err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
if err := validate.Struct(dto); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"errors": formatValidationError(err),
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
20
sqlc.yaml
Normal file
20
sqlc.yaml
Normal file
@@ -0,0 +1,20 @@
|
||||
version: "2"
|
||||
sql:
|
||||
- engine: "postgresql"
|
||||
schema: "db/schema.sql"
|
||||
queries: "db/query/"
|
||||
gen:
|
||||
go:
|
||||
package: "sqlc"
|
||||
out: "internal/gen/sqlc"
|
||||
sql_package: "pgx/v5"
|
||||
emit_json_tags: true
|
||||
emit_prepared_queries: true
|
||||
emit_interface: false
|
||||
emit_exact_table_names: false
|
||||
emit_empty_slices: true
|
||||
overrides:
|
||||
- column: "users_with_roles.roles"
|
||||
go_type:
|
||||
import: "history-api/models"
|
||||
type: "[]Role"
|
||||
Reference in New Issue
Block a user