Merge branch 'dev-ars' into dev
This commit is contained in:
commit
31e55c0539
12 changed files with 233 additions and 5 deletions
|
|
@ -120,6 +120,8 @@ paths:
|
|||
description: Title not found
|
||||
'500':
|
||||
description: Unknown server error
|
||||
security:
|
||||
- JwtAuthCookies: []
|
||||
'/users/{user_id}':
|
||||
get:
|
||||
operationId: getUsersId
|
||||
|
|
@ -156,6 +158,8 @@ paths:
|
|||
Password updates must be done via the dedicated auth-service (`/auth/`).
|
||||
Fields not provided in the request body remain unchanged.
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/accessToken'
|
||||
- $ref: '#/components/parameters/csrfToken'
|
||||
- name: user_id
|
||||
in: path
|
||||
description: User ID (primary key)
|
||||
|
|
@ -223,6 +227,8 @@ paths:
|
|||
description: 'Unprocessable Entity — semantic errors not caught by schema (e.g., invalid `avatar_id`)'
|
||||
'500':
|
||||
description: Unknown server error
|
||||
security:
|
||||
- JwtAuthCookies: []
|
||||
'/users/{user_id}/titles':
|
||||
get:
|
||||
operationId: getUserTitles
|
||||
|
|
@ -474,6 +480,39 @@ paths:
|
|||
description: Internal server error
|
||||
components:
|
||||
parameters:
|
||||
accessToken:
|
||||
name: access_token
|
||||
in: cookie
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: jwt
|
||||
example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.x.y
|
||||
description: |
|
||||
JWT access token.
|
||||
csrfToken:
|
||||
name: XSRF-TOKEN
|
||||
in: cookie
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
pattern: '^[a-zA-Z0-9_-]{32,64}$'
|
||||
example: abc123def456ghi789jkl012mno345pqr
|
||||
description: |
|
||||
Anti-CSRF token (Double Submit Cookie pattern).
|
||||
Stored in non-HttpOnly cookie, readable by JavaScript.
|
||||
Must be echoed in `X-XSRF-TOKEN` header for state-changing requests (POST/PUT/PATCH/DELETE).
|
||||
csrfTokenHeader:
|
||||
name: X-XSRF-TOKEN
|
||||
in: header
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
pattern: '^[a-zA-Z0-9_-]{32,64}$'
|
||||
description: |
|
||||
Anti-CSRF token. Must match the `XSRF-TOKEN` cookie.
|
||||
Required for all state-changing requests (POST/PUT/PATCH/DELETE).
|
||||
example: abc123def456ghi789jkl012mno345pqr
|
||||
cursor:
|
||||
in: query
|
||||
name: cursor
|
||||
|
|
|
|||
|
|
@ -16,6 +16,10 @@ import (
|
|||
openapi_types "github.com/oapi-codegen/runtime/types"
|
||||
)
|
||||
|
||||
const (
|
||||
JwtAuthCookiesScopes = "JwtAuthCookies.Scopes"
|
||||
)
|
||||
|
||||
// Defines values for ReleaseSeason.
|
||||
const (
|
||||
Fall ReleaseSeason = "fall"
|
||||
|
|
@ -170,6 +174,12 @@ type UserTitleMini struct {
|
|||
// UserTitleStatus User's title status
|
||||
type UserTitleStatus string
|
||||
|
||||
// AccessToken defines model for accessToken.
|
||||
type AccessToken = string
|
||||
|
||||
// CsrfToken defines model for csrfToken.
|
||||
type CsrfToken = string
|
||||
|
||||
// Cursor defines model for cursor.
|
||||
type Cursor = string
|
||||
|
||||
|
|
@ -219,6 +229,17 @@ type UpdateUserJSONBody struct {
|
|||
UserDesc *string `json:"user_desc,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateUserParams defines parameters for UpdateUser.
|
||||
type UpdateUserParams struct {
|
||||
// AccessToken JWT access token.
|
||||
AccessToken AccessToken `form:"access_token" json:"access_token"`
|
||||
|
||||
// XSRFTOKEN Anti-CSRF token (Double Submit Cookie pattern).
|
||||
// Stored in non-HttpOnly cookie, readable by JavaScript.
|
||||
// Must be echoed in `X-XSRF-TOKEN` header for state-changing requests (POST/PUT/PATCH/DELETE).
|
||||
XSRFTOKEN CsrfToken `form:"XSRF-TOKEN" json:"XSRF-TOKEN"`
|
||||
}
|
||||
|
||||
// GetUserTitlesParams defines parameters for GetUserTitles.
|
||||
type GetUserTitlesParams struct {
|
||||
Cursor *Cursor `form:"cursor,omitempty" json:"cursor,omitempty"`
|
||||
|
|
@ -276,7 +297,7 @@ type ServerInterface interface {
|
|||
GetUsersId(c *gin.Context, userId string, params GetUsersIdParams)
|
||||
// Partially update a user account
|
||||
// (PATCH /users/{user_id})
|
||||
UpdateUser(c *gin.Context, userId int64)
|
||||
UpdateUser(c *gin.Context, userId int64, params UpdateUserParams)
|
||||
// Get user titles
|
||||
// (GET /users/{user_id}/titles)
|
||||
GetUserTitles(c *gin.Context, userId string, params GetUserTitlesParams)
|
||||
|
|
@ -431,6 +452,8 @@ func (siw *ServerInterfaceWrapper) GetTitle(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
c.Set(JwtAuthCookiesScopes, []string{})
|
||||
|
||||
// Parameter object where we will unmarshal all parameters from the context
|
||||
var params GetTitleParams
|
||||
|
||||
|
|
@ -501,6 +524,47 @@ func (siw *ServerInterfaceWrapper) UpdateUser(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
c.Set(JwtAuthCookiesScopes, []string{})
|
||||
|
||||
// Parameter object where we will unmarshal all parameters from the context
|
||||
var params UpdateUserParams
|
||||
|
||||
{
|
||||
var cookie string
|
||||
|
||||
if cookie, err = c.Cookie("access_token"); err == nil {
|
||||
var value AccessToken
|
||||
err = runtime.BindStyledParameterWithOptions("simple", "access_token", cookie, &value, runtime.BindStyledParameterOptions{Explode: true, Required: true})
|
||||
if err != nil {
|
||||
siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter access_token: %w", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
params.AccessToken = value
|
||||
|
||||
} else {
|
||||
siw.ErrorHandler(c, fmt.Errorf("Query argument access_token is required, but not found"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var cookie string
|
||||
|
||||
if cookie, err = c.Cookie("XSRF-TOKEN"); err == nil {
|
||||
var value CsrfToken
|
||||
err = runtime.BindStyledParameterWithOptions("simple", "XSRF-TOKEN", cookie, &value, runtime.BindStyledParameterOptions{Explode: true, Required: true})
|
||||
if err != nil {
|
||||
siw.ErrorHandler(c, fmt.Errorf("Invalid format for parameter XSRF-TOKEN: %w", err), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
params.XSRFTOKEN = value
|
||||
|
||||
} else {
|
||||
siw.ErrorHandler(c, fmt.Errorf("Query argument XSRF-TOKEN is required, but not found"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for _, middleware := range siw.HandlerMiddlewares {
|
||||
middleware(c)
|
||||
if c.IsAborted() {
|
||||
|
|
@ -508,7 +572,7 @@ func (siw *ServerInterfaceWrapper) UpdateUser(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
siw.Handler.UpdateUser(c, userId)
|
||||
siw.Handler.UpdateUser(c, userId, params)
|
||||
}
|
||||
|
||||
// GetUserTitles operation middleware
|
||||
|
|
@ -935,6 +999,7 @@ func (response GetUsersId500Response) VisitGetUsersIdResponse(w http.ResponseWri
|
|||
|
||||
type UpdateUserRequestObject struct {
|
||||
UserId int64 `json:"user_id"`
|
||||
Params UpdateUserParams
|
||||
Body *UpdateUserJSONRequestBody
|
||||
}
|
||||
|
||||
|
|
@ -1411,10 +1476,11 @@ func (sh *strictHandler) GetUsersId(ctx *gin.Context, userId string, params GetU
|
|||
}
|
||||
|
||||
// UpdateUser operation middleware
|
||||
func (sh *strictHandler) UpdateUser(ctx *gin.Context, userId int64) {
|
||||
func (sh *strictHandler) UpdateUser(ctx *gin.Context, userId int64, params UpdateUserParams) {
|
||||
var request UpdateUserRequestObject
|
||||
|
||||
request.UserId = userId
|
||||
request.Params = params
|
||||
|
||||
var body UpdateUserJSONRequestBody
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,10 @@
|
|||
cursor:
|
||||
$ref: "./cursor.yaml"
|
||||
title_sort:
|
||||
$ref: "./title_sort.yaml"
|
||||
$ref: "./title_sort.yaml"
|
||||
accessToken:
|
||||
$ref: "./access_token.yaml"
|
||||
csrfToken:
|
||||
$ref: "./xsrf_token_cookie.yaml"
|
||||
csrfTokenHeader:
|
||||
$ref: "./xsrf_token_header.yaml"
|
||||
9
api/parameters/access_token.yaml
Normal file
9
api/parameters/access_token.yaml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
name: access_token
|
||||
in: cookie
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: jwt
|
||||
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.x.y"
|
||||
description: |
|
||||
JWT access token.
|
||||
11
api/parameters/xsrf_token_cookie.yaml
Normal file
11
api/parameters/xsrf_token_cookie.yaml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
name: XSRF-TOKEN
|
||||
in: cookie
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
pattern: "^[a-zA-Z0-9_-]{32,64}$"
|
||||
example: "abc123def456ghi789jkl012mno345pqr"
|
||||
description: |
|
||||
Anti-CSRF token (Double Submit Cookie pattern).
|
||||
Stored in non-HttpOnly cookie, readable by JavaScript.
|
||||
Must be echoed in `X-XSRF-TOKEN` header for state-changing requests (POST/PUT/PATCH/DELETE).
|
||||
10
api/parameters/xsrf_token_header.yaml
Normal file
10
api/parameters/xsrf_token_header.yaml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
name: X-XSRF-TOKEN
|
||||
in: header
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
pattern: "^[a-zA-Z0-9_-]{32,64}$"
|
||||
description: |
|
||||
Anti-CSRF token. Must match the `XSRF-TOKEN` cookie.
|
||||
Required for all state-changing requests (POST/PUT/PATCH/DELETE).
|
||||
example: "abc123def456ghi789jkl012mno345pqr"
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
get:
|
||||
summary: Get title description
|
||||
security:
|
||||
- JwtAuthCookies: []
|
||||
operationId: getTitle
|
||||
parameters:
|
||||
- in: path
|
||||
|
|
|
|||
|
|
@ -28,12 +28,16 @@ get:
|
|||
|
||||
patch:
|
||||
summary: Partially update a user account
|
||||
security:
|
||||
- JwtAuthCookies: []
|
||||
description: |
|
||||
Update selected user profile fields (excluding password).
|
||||
Password updates must be done via the dedicated auth-service (`/auth/`).
|
||||
Fields not provided in the request body remain unchanged.
|
||||
operationId: updateUser
|
||||
parameters:
|
||||
- $ref: '../parameters/access_token.yaml' # ← для поля в UI и GoDoc
|
||||
- $ref: '../parameters/xsrf_token_cookie.yaml' # ← для CSRF
|
||||
- name: user_id
|
||||
in: path
|
||||
required: true
|
||||
|
|
|
|||
7
api/schemas/JWTAuth.yaml
Normal file
7
api/schemas/JWTAuth.yaml
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# type: apiKey
|
||||
# in: cookie
|
||||
# name: access_token
|
||||
# scheme: bearer
|
||||
# bearerFormat: JWT
|
||||
# description: |
|
||||
# JWT access token sent in `Cookie: access_token=...`.
|
||||
|
|
@ -24,3 +24,5 @@ User:
|
|||
$ref: "./User.yaml"
|
||||
UserTitle:
|
||||
$ref: "./UserTitle.yaml"
|
||||
# JwtAuth:
|
||||
# $ref: "./JWTAuth.yaml"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
|
||||
oapi "nyanimedb/api"
|
||||
handlers "nyanimedb/modules/backend/handlers"
|
||||
middleware "nyanimedb/modules/backend/middlewares"
|
||||
"nyanimedb/modules/backend/rmq"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
|
|
@ -45,6 +46,8 @@ func main() {
|
|||
|
||||
r := gin.Default()
|
||||
|
||||
r.Use(middleware.CSRFMiddleware())
|
||||
// jwt middle will be here
|
||||
queries := sqlc.New(pool)
|
||||
|
||||
// === RabbitMQ setup ===
|
||||
|
|
@ -63,7 +66,6 @@ func main() {
|
|||
rpcClient := rmq.NewRPCClient(rmqConn, 30*time.Second)
|
||||
|
||||
server := handlers.NewServer(queries, publisher, rpcClient)
|
||||
// r.LoadHTMLGlob("templates/*")
|
||||
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"}, // allow all origins, change to specific domains in production
|
||||
|
|
|
|||
70
modules/backend/middlewares/csrf.go
Normal file
70
modules/backend/middlewares/csrf.go
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CSRFMiddleware для Gin
|
||||
func CSRFMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Пропускаем безопасные методы
|
||||
if !isStateChangingMethod(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 1. Получаем токен из заголовка
|
||||
headerToken := c.GetHeader("X-XSRF-TOKEN")
|
||||
if headerToken == "" {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"error": "missing X-XSRF-TOKEN header",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Получаем токен из cookie
|
||||
cookie, err := c.Cookie("xsrf_token")
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"error": "missing xsrf_token cookie",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Безопасное сравнение
|
||||
if subtle.ConstantTimeCompare([]byte(headerToken), []byte(cookie)) != 1 {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"error": "CSRF token mismatch",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Опционально: сохраняем токен в контексте
|
||||
c.Set("csrf_token", headerToken)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func isStateChangingMethod(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// CSRFTokenFromGin извлекает токен из Gin context
|
||||
func CSRFTokenFromGin(c *gin.Context) (string, bool) {
|
||||
token, exists := c.Get("xsrf_token")
|
||||
if !exists {
|
||||
return "", false
|
||||
}
|
||||
if s, ok := token.(string); ok {
|
||||
return s, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue