Skip to content

Commit 8479ddc

Browse files
committed
feat(api): 🔒 check auth for routes
1 parent 6d052d1 commit 8479ddc

File tree

4 files changed

+48
-6
lines changed

4 files changed

+48
-6
lines changed

api/openapi.yaml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,6 @@ paths:
4848
Authenticates a user by user_name and password, starts a new session,
4949
and returns a session cookie.
5050
operationId: signInUser
51-
security:
52-
- sessionAuth: []
5351
requestBody:
5452
required: true
5553
content:

cmd/main.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ import (
99
"ctf01d/internal/config"
1010
"ctf01d/internal/handler"
1111
"ctf01d/internal/httpserver"
12+
"ctf01d/internal/middleware/auth"
1213
migration "ctf01d/internal/migrations/psql"
14+
"ctf01d/internal/repository"
1315
"ctf01d/pkg/ginmiddleware"
14-
1516
"github.com/getkin/kin-openapi/openapi3"
1617
"github.com/getkin/kin-openapi/openapi3filter"
1718
"github.com/gin-contrib/cors"
@@ -31,11 +32,14 @@ func main() {
3132
slog.Error("Config error: " + err.Error())
3233
os.Exit(1)
3334
}
35+
3436
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
3537
Level: slog.Level(cfg.ParseLogLevel(cfg.Log.Level)),
3638
}))
3739
slog.SetDefault(logger)
3840
slog.Info("Config path is - " + path)
41+
42+
// Подключение к БД
3943
db, err := migration.InitDatabase(cfg)
4044
if err != nil {
4145
slog.Error("Database connection error: " + err.Error())
@@ -70,7 +74,13 @@ func main() {
7074

7175
// API-группа, к которой применяются валидаторы
7276
apiGroup := router.Group("/", requestValidator, responseValidator)
73-
httpserver.RegisterHandlers(apiGroup, hndlr)
77+
sessionRepo := repository.NewSessionRepository(db)
78+
options := httpserver.GinServerOptions{
79+
Middlewares: []httpserver.MiddlewareFunc{
80+
auth.AuthenticationMiddleware(sessionRepo),
81+
},
82+
}
83+
httpserver.RegisterHandlersWithOptions(apiGroup, hndlr, options)
7484

7585
// HTML маршрутизатор для корня
7686
router.GET("/", httpserver.NewHtmlRouter())

internal/httpserver/httpserver.gen.go

Lines changed: 0 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package auth
2+
3+
import (
4+
"net/http"
5+
6+
"ctf01d/internal/httpserver"
7+
"ctf01d/internal/repository"
8+
"github.com/gin-gonic/gin"
9+
)
10+
11+
func AuthenticationMiddleware(repo repository.SessionRepository) httpserver.MiddlewareFunc {
12+
return func(c *gin.Context) {
13+
// Проверка, нужен ли вообще роуту токен для авторизации
14+
_, sessionExists := c.Keys["sessionAuth.Scopes"]
15+
16+
if !sessionExists {
17+
c.Next()
18+
return
19+
}
20+
21+
sessionCookie, err := c.Cookie("session_id")
22+
if err != nil || sessionCookie == "" {
23+
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Session cookie required"})
24+
return
25+
}
26+
27+
userId, err := repo.GetSessionFromDB(c, sessionCookie)
28+
if err != nil {
29+
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid session"})
30+
return
31+
}
32+
33+
c.Set("user_id", userId)
34+
c.Next()
35+
}
36+
}

0 commit comments

Comments
 (0)