66 lines
2.0 KiB
Go
66 lines
2.0 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"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{
|
|
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
|
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
|
|
ExposeHeaders: []string{"Content-Length"},
|
|
AllowOriginFunc: func(origin string) bool {
|
|
switch {
|
|
case strings.HasPrefix(origin, "http://localhost:"):
|
|
return true
|
|
case strings.HasPrefix(origin, "http://127.0.0.1:"):
|
|
return true
|
|
case origin == "https://social-rating.nekiiinkognito.ru":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
},
|
|
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.GET("/users", socialRatingHandler.ListUsers)
|
|
protected.GET("/users/:userId", socialRatingHandler.GetUser)
|
|
protected.GET("/users/:userId/social-rating/history", socialRatingHandler.GetUserHistory)
|
|
protected.GET("/social-rating/operations", socialRatingHandler.GetRecentOperations)
|
|
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
|
|
}
|