This commit is contained in:
2026-04-18 10:21:51 +03:00
commit 90d027025b
37 changed files with 6493 additions and 0 deletions

0
.codex Normal file
View File

36
.env.example Normal file
View File

@@ -0,0 +1,36 @@
COMPOSE_RESTART_POLICY=unless-stopped
MYSQL_IMAGE=mysql:8.4
MYSQL_CONTAINER_NAME=social-raiting-mysql
MYSQL_HOST_PORT=3306
MYSQL_VOLUME_NAME=mysql_data
MYSQL_HEALTHCHECK_INTERVAL=10s
MYSQL_HEALTHCHECK_TIMEOUT=5s
MYSQL_HEALTHCHECK_RETRIES=10
MYSQL_DATABASE=social_raiting
MYSQL_USER=social_raiting
MYSQL_PASSWORD=change-db-password
MYSQL_ROOT_PASSWORD=change-root-password
BACKEND_BUILD_CONTEXT=./backend
BACKEND_DOCKERFILE=Dockerfile
BACKEND_CONTAINER_NAME=social-raiting-backend
BACKEND_HOST_PORT=8080
SWAGGER_UI_IMAGE=swaggerapi/swagger-ui
SWAGGER_UI_CONTAINER_NAME=social-raiting-swagger-ui
SWAGGER_UI_HOST_PORT=8081
SWAGGER_SPEC_PATH=./backend/docs/swagger.yaml
SERVER_PORT=8080
JWT_SECRET=replace-with-a-long-random-secret
DB_HOST=mysql
DB_PORT=3306
DB_NAME=social_raiting
DB_USER=social_raiting
DB_PASSWORD=change-db-password
DEFAULT_ADMIN_EMAIL=admin@example.com
DEFAULT_ADMIN_PASSWORD=change-admin-password

8
backend/.dockerignore Normal file
View File

@@ -0,0 +1,8 @@
.git
.gitignore
node_modules
tmp
dist
coverage
.env
*.log

16
backend/.env.example Normal file
View File

@@ -0,0 +1,16 @@
SERVER_PORT=8080
JWT_SECRET=replace-with-a-long-random-secret
MYSQL_DATABASE=social_raiting
MYSQL_USER=social_raiting
MYSQL_PASSWORD=change-db-password
MYSQL_ROOT_PASSWORD=change-root-password
DB_HOST=mysql
DB_PORT=3306
DB_NAME=social_raiting
DB_USER=social_raiting
DB_PASSWORD=change-db-password
DEFAULT_ADMIN_EMAIL=admin@example.com
DEFAULT_ADMIN_PASSWORD=change-admin-password

24
backend/Dockerfile Normal file
View File

@@ -0,0 +1,24 @@
FROM golang:1.25.6-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /social-raiting-backend .
FROM alpine:3.22
WORKDIR /app
RUN adduser -D -H -u 10001 appuser
COPY --from=builder /social-raiting-backend /app/social-raiting-backend
COPY docs /app/docs
EXPOSE 8080
USER appuser
CMD ["/app/social-raiting-backend"]

431
backend/docs/swagger.yaml Normal file
View File

@@ -0,0 +1,431 @@
openapi: 3.0.3
info:
title: Social Raiting API
version: 1.0.0
description: |
API for authentication, user management, and social rating operations.
Social rating values are allowed to go below zero. Decrease operations continue
subtracting from the current score without applying a lower bound.
servers:
- url: http://localhost:8080
description: Local backend
tags:
- name: Health
- name: Auth
- name: Social Rating
paths:
/ping:
get:
tags:
- Health
summary: Health check
operationId: ping
responses:
'200':
description: Backend is healthy
content:
application/json:
schema:
$ref: '#/components/schemas/PingResponse'
/api/auth/login:
post:
tags:
- Auth
summary: Login user
operationId: loginUser
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/LoginRequest'
responses:
'200':
description: Login successful
content:
application/json:
schema:
$ref: '#/components/schemas/AuthResponse'
'400':
description: Invalid request body
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Invalid credentials
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/auth/me:
get:
tags:
- Auth
summary: Get current user
operationId: getCurrentUser
security:
- bearerAuth: []
responses:
'200':
description: Current authenticated user
content:
application/json:
schema:
$ref: '#/components/schemas/UserResponse'
'401':
description: Missing or invalid token
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'404':
description: User not found
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/auth/register:
post:
tags:
- Auth
summary: Register user
description: Only authenticated admin users may create new users.
operationId: registerUser
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/RegisterRequest'
responses:
'201':
description: User created
content:
application/json:
schema:
$ref: '#/components/schemas/UserResponse'
'400':
description: Invalid request body
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Missing or invalid token
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'403':
description: Admin access required
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'409':
description: Email already exists
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/social-rating/increase:
post:
tags:
- Social Rating
summary: Increase social rating
operationId: increaseSocialRating
description: Adds a positive amount to the target user's current social rating.
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/ChangeSocialRatingRequest'
responses:
'200':
description: Social rating increased
content:
application/json:
schema:
$ref: '#/components/schemas/ChangeSocialRatingResponse'
'400':
description: Invalid request body
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Missing or invalid token
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'404':
description: Target or actor user not found
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/api/social-rating/decrease:
post:
tags:
- Social Rating
summary: Decrease social rating
operationId: decreaseSocialRating
description: |
Subtracts a positive amount from the target user's current social rating.
The resulting score may be negative.
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/ChangeSocialRatingRequest'
responses:
'200':
description: Social rating decreased
content:
application/json:
schema:
$ref: '#/components/schemas/ChangeSocialRatingResponse'
'400':
description: Invalid request body
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: Missing or invalid token
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'404':
description: Target or actor user not found
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
PingResponse:
type: object
properties:
message:
type: string
example: ok
required:
- message
ErrorResponse:
type: object
properties:
error:
type: string
example: invalid credentials
required:
- error
LoginRequest:
type: object
properties:
email:
type: string
format: email
example: admin@example.com
password:
type: string
format: password
example: strong-password
required:
- email
- password
RegisterRequest:
type: object
properties:
email:
type: string
format: email
example: user@example.com
password:
type: string
format: password
minLength: 8
example: strong-password
isAdmin:
type: boolean
example: false
required:
- email
- password
ChangeSocialRatingRequest:
type: object
properties:
targetUserId:
type: integer
format: uint64
example: 2
amount:
type: integer
minimum: 1
default: 1
example: 3
reason:
type: string
example: helpful review
source:
type: string
example: api
required:
- targetUserId
AuthResponse:
type: object
properties:
token:
type: string
example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
user:
$ref: '#/components/schemas/User'
required:
- token
- user
UserResponse:
type: object
properties:
user:
$ref: '#/components/schemas/User'
required:
- user
User:
type: object
properties:
id:
type: integer
format: uint64
example: 1
email:
type: string
format: email
example: admin@example.com
isAdmin:
type: boolean
example: true
socialRating:
$ref: '#/components/schemas/UserSocialRating'
createdAt:
type: string
format: date-time
updatedAt:
type: string
format: date-time
required:
- id
- email
- isAdmin
- createdAt
- updatedAt
UserSocialRating:
type: object
properties:
userId:
type: integer
format: uint64
example: 2
score:
type: integer
example: -4
lastOperationId:
type: integer
format: uint64
nullable: true
example: 15
createdAt:
type: string
format: date-time
updatedAt:
type: string
format: date-time
required:
- userId
- score
- createdAt
- updatedAt
SocialRatingOperation:
type: object
properties:
id:
type: integer
format: uint64
example: 15
targetUserId:
type: integer
format: uint64
example: 2
actorUserId:
type: integer
format: uint64
nullable: true
example: 1
delta:
type: integer
example: -3
operationType:
type: string
example: decrease
reason:
type: string
example: spam
source:
type: string
example: api
balanceAfter:
type: integer
example: -4
createdAt:
type: string
format: date-time
required:
- id
- targetUserId
- delta
- operationType
- balanceAfter
- createdAt
ChangeSocialRatingResponse:
type: object
properties:
operation:
$ref: '#/components/schemas/SocialRatingOperation'
currentRating:
$ref: '#/components/schemas/UserSocialRating'
required:
- operation
- currentRating

47
backend/go.mod Normal file
View File

@@ -0,0 +1,47 @@
module social-raiting.nekiiinkognito.ru
go 1.25.6
require (
github.com/gin-contrib/cors v1.7.6
github.com/gin-gonic/gin v1.12.0
github.com/golang-jwt/jwt/v5 v5.3.0
golang.org/x/crypto v0.48.0
gorm.io/driver/mysql v1.6.0
gorm.io/gorm v1.31.1
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/net v0.51.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.34.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
)

105
backend/go.sum Normal file
View File

@@ -0,0 +1,105 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQY=
github.com/gin-contrib/cors v1.7.6/go.mod h1:Ulcl+xN4jel9t1Ry8vqph23a60FwH9xVLd+3ykmTjOk=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
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-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/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/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
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-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/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
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/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
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/sys v0.6.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=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
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=
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=

View File

@@ -0,0 +1,39 @@
package auth
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"social-raiting.nekiiinkognito.ru/internal/models"
)
func RequireAdmin(db *gorm.DB) gin.HandlerFunc {
return func(ctx *gin.Context) {
userID, exists := ctx.Get("userID")
if !exists {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing user context"})
return
}
var user models.User
if err := db.First(&user, "id = ?", userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "user not found"})
return
}
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "failed to load user"})
return
}
if !user.IsAdmin {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
ctx.Next()
}
}

View File

@@ -0,0 +1,123 @@
package auth
import (
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"social-raiting.nekiiinkognito.ru/internal/models"
)
type Handler struct {
DB *gorm.DB
JWTSecret string
}
func NewHandler(db *gorm.DB, jwtSecret string) Handler {
return Handler{
DB: db,
JWTSecret: jwtSecret,
}
}
func (h Handler) Register(ctx *gin.Context) {
var req RegisterRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
email := strings.ToLower(strings.TrimSpace(req.Email))
passwordHash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to hash password"})
return
}
user := models.User{
Email: email,
PasswordHash: string(passwordHash),
IsAdmin: req.IsAdmin,
}
if err := h.DB.Create(&user).Error; err != nil {
if isDuplicateEmailError(err) {
ctx.JSON(http.StatusConflict, gin.H{"error": "email is already registered"})
return
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create user"})
return
}
ctx.JSON(http.StatusCreated, UserResponse{User: user})
}
func (h Handler) Login(ctx *gin.Context) {
var req LoginRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var user models.User
if err := h.DB.Where("email = ?", strings.ToLower(strings.TrimSpace(req.Email))).First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load user"})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
token, err := GenerateToken(user.ID, h.JWTSecret, TokenOptions{})
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create token"})
return
}
ctx.JSON(http.StatusOK, AuthResponse{
Token: token,
User: user,
})
}
func (h Handler) Me(ctx *gin.Context) {
userID, exists := ctx.Get("userID")
if !exists {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "missing user context"})
return
}
var user models.User
if err := h.DB.First(&user, "id = ?", userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load user"})
return
}
ctx.JSON(http.StatusOK, UserResponse{User: user})
}
func isDuplicateEmailError(err error) bool {
if err == nil {
return false
}
errText := strings.ToLower(err.Error())
return strings.Contains(errText, "duplicate") || strings.Contains(errText, "1062")
}

View File

@@ -0,0 +1,28 @@
package auth
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
func GenerateToken(userID uint, jwtSecret string, options TokenOptions) (string, error) {
ttl := options.TTL
if ttl <= 0 {
ttl = 24 * time.Hour
}
now := time.Now()
claims := JWTClaims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
Subject: fmt.Sprintf("%d", userID),
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(jwtSecret))
}

View File

@@ -0,0 +1,42 @@
package auth
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func Middleware(jwtSecret string) gin.HandlerFunc {
return func(ctx *gin.Context) {
header := strings.TrimSpace(ctx.GetHeader("Authorization"))
if header == "" {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
return
}
parts := strings.SplitN(header, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
return
}
claims := &JWTClaims{}
token, err := jwt.ParseWithClaims(parts[1], claims, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(jwtSecret), nil
})
if err != nil || !token.Valid {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
ctx.Set("userID", claims.UserID)
ctx.Next()
}
}

View File

@@ -0,0 +1,38 @@
package auth
import (
"time"
"github.com/golang-jwt/jwt/v5"
"social-raiting.nekiiinkognito.ru/internal/models"
)
type RegisterRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required,min=8"`
IsAdmin bool `json:"isAdmin"`
}
type LoginRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required"`
}
type AuthResponse struct {
Token string `json:"token"`
User models.User `json:"user"`
}
type JWTClaims struct {
UserID uint `json:"userId"`
jwt.RegisteredClaims
}
type UserResponse struct {
User models.User `json:"user"`
}
type TokenOptions struct {
TTL time.Duration
}

View File

@@ -0,0 +1,52 @@
package config
import (
"log"
"os"
"strings"
)
type Config struct {
ServerPort string
JWTSecret string
DBUser string
DBPassword string
DBHost string
DBPort string
DBName string
DefaultAdminEmail string
DefaultAdminPassword string
}
func Load() Config {
cfg := Config{
ServerPort: getEnv("SERVER_PORT", "8080"),
JWTSecret: getEnv("JWT_SECRET", "change-me-in-production"),
DBUser: getEnv("DB_USER", "root"),
DBPassword: getEnv("DB_PASSWORD", ""),
DBHost: getEnv("DB_HOST", "127.0.0.1"),
DBPort: getEnv("DB_PORT", "3306"),
DBName: getEnv("DB_NAME", "social_raiting"),
DefaultAdminEmail: getEnv("DEFAULT_ADMIN_EMAIL", "admin@example.com"),
DefaultAdminPassword: getEnv("DEFAULT_ADMIN_PASSWORD", "change-admin-password"),
}
if cfg.JWTSecret == "change-me-in-production" {
log.Println("warning: JWT_SECRET is using the default development value")
}
if cfg.DefaultAdminPassword == "change-admin-password" {
log.Println("warning: DEFAULT_ADMIN_PASSWORD is using the default development value")
}
return cfg
}
func getEnv(key, fallback string) string {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
return value
}

View File

@@ -0,0 +1,94 @@
package database
import (
"fmt"
"log"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"social-raiting.nekiiinkognito.ru/internal/config"
"social-raiting.nekiiinkognito.ru/internal/models"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func Connect(cfg config.Config) *gorm.DB {
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
cfg.DBUser,
cfg.DBPassword,
cfg.DBHost,
cfg.DBPort,
cfg.DBName,
)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("failed to connect to mysql: %v", err)
}
sqlDB, err := db.DB()
if err != nil {
log.Fatalf("failed to create sql database handle: %v", err)
}
sqlDB.SetConnMaxLifetime(5 * time.Minute)
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(25)
if err := sqlDB.Ping(); err != nil {
log.Fatalf("failed to ping mysql: %v", err)
}
if err := db.AutoMigrate(&models.User{}); err != nil {
log.Fatalf("failed to migrate database: %v", err)
}
if err := db.AutoMigrate(&models.UserSocialRating{}, &models.SocialRatingOperation{}); err != nil {
log.Fatalf("failed to migrate database: %v", err)
}
ensureDefaultAdmin(db, cfg)
return db
}
func ensureDefaultAdmin(db *gorm.DB, cfg config.Config) {
email := strings.ToLower(strings.TrimSpace(cfg.DefaultAdminEmail))
password := strings.TrimSpace(cfg.DefaultAdminPassword)
if email == "" || password == "" {
log.Println("skipping default admin bootstrap because admin credentials are empty")
return
}
var user models.User
err := db.Where("email = ?", email).First(&user).Error
if err == nil {
if !user.IsAdmin {
if updateErr := db.Model(&user).Update("is_admin", true).Error; updateErr != nil {
log.Fatalf("failed to promote default admin user: %v", updateErr)
}
}
return
}
if err != gorm.ErrRecordNotFound {
log.Fatalf("failed to check default admin user: %v", err)
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
log.Fatalf("failed to hash default admin password: %v", err)
}
user = models.User{
Email: email,
PasswordHash: string(passwordHash),
IsAdmin: true,
}
if err := db.Create(&user).Error; err != nil {
log.Fatalf("failed to create default admin user: %v", err)
}
}

View File

@@ -0,0 +1,26 @@
package models
import "time"
type SocialRatingOperation struct {
ID uint `json:"id" gorm:"primaryKey"`
TargetUserID uint `json:"targetUserId" gorm:"not null;index"`
TargetUser User `json:"-" gorm:"foreignKey:TargetUserID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
ActorUserID *uint `json:"actorUserId,omitempty" gorm:"index"`
ActorUser *User `json:"-" gorm:"foreignKey:ActorUserID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
Delta int `json:"delta" gorm:"not null"`
OperationType string `json:"operationType" gorm:"size:32;not null;index"`
Reason string `json:"reason,omitempty" gorm:"size:255"`
Source string `json:"source,omitempty" gorm:"size:64;index"`
BalanceAfter int `json:"balanceAfter" gorm:"not null"`
CreatedAt time.Time `json:"createdAt"`
}
type UserSocialRating struct {
UserID uint `json:"userId" gorm:"primaryKey"`
User User `json:"-" gorm:"foreignKey:UserID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
Score int `json:"score" gorm:"not null;default:0;index"`
LastOperationID *uint `json:"lastOperationId,omitempty" gorm:"index"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}

View File

@@ -0,0 +1,23 @@
package models
import (
"time"
"gorm.io/gorm"
)
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
Email string `json:"email" gorm:"size:255;uniqueIndex;not null"`
PasswordHash string `json:"-" gorm:"size:255;not null"`
IsAdmin bool `json:"isAdmin" gorm:"not null;default:false;index"`
SocialRating *UserSocialRating `json:"socialRating,omitempty" gorm:"foreignKey:UserID"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
func (u *User) AfterCreate(tx *gorm.DB) error {
return tx.FirstOrCreate(&UserSocialRating{}, UserSocialRating{
UserID: u.ID,
}).Error
}

View File

@@ -0,0 +1,49 @@
package server
import (
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"social-raiting.nekiiinkognito.ru/internal/auth"
"social-raiting.nekiiinkognito.ru/internal/config"
"social-raiting.nekiiinkognito.ru/internal/socialrating"
)
func NewRouter(db *gorm.DB, cfg config.Config) *gin.Engine {
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:5173", "http://127.0.0.1:5173", "http://localhost:8081", "http://127.0.0.1:8081", "https://social-rating.nekiiinkognito.ru/"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
router.GET("/ping", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "ok"})
})
router.StaticFile("/swagger.yaml", "./docs/swagger.yaml")
authHandler := auth.NewHandler(db, cfg.JWTSecret)
socialRatingHandler := socialrating.NewHandler(socialrating.NewService(db))
api := router.Group("/api")
api.POST("/auth/login", authHandler.Login)
protected := api.Group("/")
protected.Use(auth.Middleware(cfg.JWTSecret))
protected.GET("/auth/me", authHandler.Me)
protected.POST("/social-rating/increase", socialRatingHandler.Increase)
protected.POST("/social-rating/decrease", socialRatingHandler.Decrease)
admin := protected.Group("/")
admin.Use(auth.RequireAdmin(db))
admin.POST("/auth/register", authHandler.Register)
return router
}

View File

@@ -0,0 +1,99 @@
package socialrating
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"social-raiting.nekiiinkognito.ru/internal/models"
)
type Handler struct {
Service Service
}
type ChangeRequest struct {
TargetUserID uint `json:"targetUserId" binding:"required"`
Amount int `json:"amount"`
Reason string `json:"reason"`
Source string `json:"source"`
}
type ChangeResponse struct {
Operation models.SocialRatingOperation `json:"operation"`
CurrentRating models.UserSocialRating `json:"currentRating"`
}
func NewHandler(service Service) Handler {
return Handler{Service: service}
}
func (h Handler) Increase(ctx *gin.Context) {
h.applySignedChange(ctx, "increase", 1)
}
func (h Handler) Decrease(ctx *gin.Context) {
h.applySignedChange(ctx, "decrease", -1)
}
func (h Handler) applySignedChange(ctx *gin.Context, operationType string, direction int) {
var req ChangeRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
actorUserID, ok := getActorUserID(ctx)
if !ok {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "missing user context"})
return
}
amount := req.Amount
if amount == 0 {
amount = 1
}
if amount < 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "amount must be greater than zero"})
return
}
operation, currentRating, err := h.Service.ApplyChange(ChangeInput{
TargetUserID: req.TargetUserID,
ActorUserID: &actorUserID,
Delta: amount * direction,
OperationType: operationType,
Reason: req.Reason,
Source: req.Source,
})
if err != nil {
handleApplyChangeError(ctx, err)
return
}
ctx.JSON(http.StatusOK, ChangeResponse{
Operation: operation,
CurrentRating: currentRating,
})
}
func getActorUserID(ctx *gin.Context) (uint, bool) {
value, exists := ctx.Get("userID")
if !exists {
return 0, false
}
userID, ok := value.(uint)
return userID, ok
}
func handleApplyChangeError(ctx *gin.Context, err error) {
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
ctx.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
default:
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}

View File

@@ -0,0 +1,97 @@
package socialrating
import (
"errors"
"strings"
"gorm.io/gorm"
"social-raiting.nekiiinkognito.ru/internal/models"
)
type Service struct {
DB *gorm.DB
}
type ChangeInput struct {
TargetUserID uint
ActorUserID *uint
Delta int
OperationType string
Reason string
Source string
}
func NewService(db *gorm.DB) Service {
return Service{DB: db}
}
func (s Service) ApplyChange(input ChangeInput) (models.SocialRatingOperation, models.UserSocialRating, error) {
var operation models.SocialRatingOperation
var currentRating models.UserSocialRating
if err := validateChangeInput(input); err != nil {
return operation, currentRating, err
}
err := s.DB.Transaction(func(tx *gorm.DB) error {
if err := ensureUserExists(tx, input.TargetUserID); err != nil {
return err
}
if input.ActorUserID != nil {
if err := ensureUserExists(tx, *input.ActorUserID); err != nil {
return err
}
}
currentRating = models.UserSocialRating{UserID: input.TargetUserID}
if err := tx.FirstOrCreate(&currentRating, models.UserSocialRating{
UserID: input.TargetUserID,
}).Error; err != nil {
return err
}
// Social rating is allowed to go below zero, so no lower bound is applied here.
currentRating.Score += input.Delta
operation = models.SocialRatingOperation{
TargetUserID: input.TargetUserID,
ActorUserID: input.ActorUserID,
Delta: input.Delta,
OperationType: strings.TrimSpace(input.OperationType),
Reason: strings.TrimSpace(input.Reason),
Source: strings.TrimSpace(input.Source),
BalanceAfter: currentRating.Score,
}
if err := tx.Create(&operation).Error; err != nil {
return err
}
currentRating.LastOperationID = &operation.ID
return tx.Save(&currentRating).Error
})
return operation, currentRating, err
}
func validateChangeInput(input ChangeInput) error {
if input.TargetUserID == 0 {
return errors.New("target user id is required")
}
if strings.TrimSpace(input.OperationType) == "" {
return errors.New("operation type is required")
}
if input.Delta == 0 {
return errors.New("delta must not be zero")
}
return nil
}
func ensureUserExists(tx *gorm.DB, userID uint) error {
var user models.User
return tx.First(&user, "id = ?", userID).Error
}

20
backend/main.go Normal file
View File

@@ -0,0 +1,20 @@
package main
import (
"log"
"social-raiting.nekiiinkognito.ru/internal/config"
"social-raiting.nekiiinkognito.ru/internal/database"
"social-raiting.nekiiinkognito.ru/internal/server"
)
func main() {
cfg := config.Load()
db := database.Connect(cfg)
router := server.NewRouter(db, cfg)
log.Printf("backend listening on :%s", cfg.ServerPort)
if err := router.Run(":" + cfg.ServerPort); err != nil {
log.Fatalf("failed to start server: %v", err)
}
}

46
docker-compose.yml Normal file
View File

@@ -0,0 +1,46 @@
services:
mysql:
image: ${MYSQL_IMAGE}
container_name: ${MYSQL_CONTAINER_NAME}
restart: ${COMPOSE_RESTART_POLICY}
env_file:
- ./.env
ports:
- "${MYSQL_HOST_PORT}:3306"
volumes:
- ${MYSQL_VOLUME_NAME}:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-uroot", "-p${MYSQL_ROOT_PASSWORD}"]
interval: ${MYSQL_HEALTHCHECK_INTERVAL}
timeout: ${MYSQL_HEALTHCHECK_TIMEOUT}
retries: ${MYSQL_HEALTHCHECK_RETRIES}
backend:
build:
context: ${BACKEND_BUILD_CONTEXT}
dockerfile: ${BACKEND_DOCKERFILE}
container_name: ${BACKEND_CONTAINER_NAME}
restart: ${COMPOSE_RESTART_POLICY}
depends_on:
mysql:
condition: service_healthy
env_file:
- ./.env
ports:
- "${BACKEND_HOST_PORT}:${SERVER_PORT}"
swagger-ui:
image: ${SWAGGER_UI_IMAGE}
container_name: ${SWAGGER_UI_CONTAINER_NAME}
restart: ${COMPOSE_RESTART_POLICY}
depends_on:
- backend
environment:
SWAGGER_JSON: /usr/share/nginx/html/swagger.yaml
ports:
- "${SWAGGER_UI_HOST_PORT}:8080"
volumes:
- ${SWAGGER_SPEC_PATH}:/usr/share/nginx/html/swagger.yaml:ro
volumes:
${MYSQL_VOLUME_NAME}:

24
frontend/social-raiting/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>social-raiting</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

4772
frontend/social-raiting/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
{
"name": "social-raiting",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/themes": "^3.3.0",
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.4"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

View File

@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

View File

@@ -0,0 +1,15 @@
import { Button, Container, Heading } from "@radix-ui/themes"
function App() {
return (
<>
<Container size={"2"}>
<Heading>This is an app</Heading>
<Button>Go inside</Button>
</Container>
</>
)
}
export default App

View File

View File

@@ -0,0 +1,11 @@
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import "@radix-ui/themes/styles.css";
import { Theme } from '@radix-ui/themes'
createRoot(document.getElementById('root')!).render(
<Theme accentColor="pink" grayColor="gray" appearance="dark">
<App />
</Theme>
)

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})