Добавлен основные классы для сервиса авторизаци

This commit is contained in:
Ганеев Артем
2025-10-28 20:49:54 +03:00
parent def3552a67
commit 736b8031f8
26 changed files with 904 additions and 40 deletions

View File

@@ -1,13 +1,65 @@
package handler
import (
"authorization/internal"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *Handler) signUp(c *gin.Context) {
var input internal.User
if err := c.BindJSON(&input); err != nil {
newErrorResponse(c, http.StatusBadRequest, err.Error())
return
}
id, err := h.services.Authorization.CreateUser(input)
if err != nil {
newErrorResponse(c, http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"id": id,
})
}
func (h *Handler) signIn(c *gin.Context) {
var input internal.AuthUser
if err := c.BindJSON(&input); err != nil {
newErrorResponse(c, http.StatusBadRequest, err.Error())
return
}
accesstoken, refreshToken, err := h.services.Authorization.GenerateToken(input.Username, input.Password)
if err != nil {
newErrorResponse(c, http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"accessToken": accesstoken,
"refreshToken": refreshToken,
})
}
func (h *Handler) refresh(c *gin.Context) {
var input internal.RefreshTokenRequest
if err := c.BindJSON(&input); err != nil {
newErrorResponse(c, http.StatusBadRequest, err.Error())
return
}
accessToken, refreshToken, err := h.services.Authorization.RefreshToken(input.RefreshToken)
if err != nil {
newErrorResponse(c, http.StatusUnauthorized, err.Error())
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"accessToken": accessToken,
"refreshToken": refreshToken,
})
}

View File

@@ -1,17 +1,40 @@
package handler
import "github.com/gin-gonic/gin"
import (
"authorization/internal/service"
"github.com/gin-gonic/gin"
)
type Handler struct {
services *service.Service
}
func NewHandler(services *service.Service) *Handler {
return &Handler{
services: services,
}
}
func (h *Handler) InitRoutes() *gin.Engine {
router := gin.New()
auth := router.Group("/auth")
serviceRouter := router.Group("/auth-service")
{
auth.POST("/sign-up", h.signUp)
auth.POST("/sign-in", h.signIn)
auth := serviceRouter.Group("/auth")
{
auth.POST("/sign-up", h.signUp)
auth.POST("/sign-in", h.signIn)
auth.POST("/refresh", h.refresh)
}
api := router.Group("/api")
{
users := api.Group("/users", h.checkAdminIdentity)
{
users.POST("/:username", h.changeUserRole)
}
}
}
return router
}

View File

@@ -0,0 +1,42 @@
package handler
import (
"authorization/internal"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
const (
authorizationHeader = "Authorization"
roleKey = "user_role"
)
func (h *Handler) checkAdminIdentity(c *gin.Context) {
header := c.GetHeader(authorizationHeader)
if header == "" {
newErrorResponse(c, http.StatusUnauthorized, "Пустой header авторизации")
return
}
headerParts := strings.Split(header, " ")
if len(headerParts) != 2 {
newErrorResponse(c, http.StatusUnauthorized, "Невалидный токен JWT")
return
}
userRole, err := h.services.ParseToken(headerParts[1])
if userRole != string(internal.Admin) {
newErrorResponse(c, http.StatusUnauthorized, "Недостаточно прав для выполнения запроса")
return
}
if err != nil {
newErrorResponse(c, http.StatusUnauthorized, "Ошибка при извлечении claims")
return
}
c.Set(roleKey, userRole)
}

View File

@@ -0,0 +1,15 @@
package handler
import (
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
type error struct {
Message string `json:"message"`
}
func newErrorResponse(c *gin.Context, statusCode int, message string) {
logrus.Error(message)
c.AbortWithStatusJSON(statusCode, error{Message: message})
}

36
internal/handler/users.go Normal file
View File

@@ -0,0 +1,36 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
)
type ChangeUserRoleRequest struct {
Role string `json:"role"`
}
func (h *Handler) changeUserRole(c *gin.Context) {
var input ChangeUserRoleRequest
if err := c.BindJSON(&input); err != nil {
newErrorResponse(c, http.StatusBadRequest, err.Error())
return
}
username := c.Param("username")
if username == "" {
newErrorResponse(c, http.StatusBadRequest, "Ошибка в строке запроса")
return
}
role, err := h.services.ChangeUserRole(username, input.Role)
if err != nil {
newErrorResponse(c, http.StatusBadRequest, err.Error())
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"newRole": role,
})
}