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

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)
}
}