Измен. логики получения информации о пользователе

This commit is contained in:
Ymnuk 2023-11-15 14:37:29 +03:00
parent 09f8950662
commit d39b98bc0f
17 changed files with 356 additions and 288 deletions

View File

@ -152,8 +152,17 @@ func generateModelBase() {
}
}
if err := templ.PrepareTmplFile("tmpl/backend/db/migrate.tmpl", Project, filepath.Join(AppConfig.OutdirBackend, "db", "migrate.go")); err != nil {
log.Fatal(err)
if len(Project.DB.Tables) > 0 {
for _, table := range Project.DB.Tables {
if len(table.Values) > 0 {
if err := templ.PrepareTmplFile("tmpl/backend/db/migrate-model.tmpl", structs.RestStruct{
Project: Project,
Table: &table,
}, filepath.Join(AppConfig.OutdirBackend, "db", "migrate"+templ.FieldNamePrepare(table.Name)+".go")); err != nil {
log.Fatal(err)
}
}
}
}
// middleware

View File

@ -83,34 +83,34 @@ func DBConnect() {
// SetConnMaxLifetime устанавливает максимальное время, в течение которого соединение может использоваться повторно.
sqlDB.SetConnMaxLifetime(time.Hour)
tx := BeginTransation()
if lib.AppConfig.DbMigrate {
err = tx.AutoMigrate(
model.User{},
model.Role{},
model.UserRole{},
{{ range $index, $table := .DB.Tables }}
model.{{fieldNamePrepare $table.Name }}{},
tx := BeginTransation()
err = tx.AutoMigrate(
model.User{},
model.Role{},
model.UserRole{},
{{ range $index, $table := .DB.Tables }}model.{{fieldNamePrepare $table.Name }}{},
{{ end }}
)
EndTransaction(tx, err)
if err != nil {
log.Fatal(err)
}
updateRoles()
updateUsers()
// Добавление функций миграции
{{ range $index, $item := .DB.Tables }}{{ if $item.Values }}update{{ fieldNamePrepare $item.Name}}(){{ end }}
{{ end }}
)
EndTransaction(tx, err)
if err != nil {
log.Fatal(err)
}
updateRoles()
updateUsers()
// Добавление функций миграции
{{ range $index, $item := .DB.Tables }}
{{ if $item.Values }}
update{{ fieldNamePrepare $item.Name}}()
{{ end }}
{{ end }}
}
// Получить роль по имени

View File

@ -0,0 +1,47 @@
package db
import (
"{{ .Project.Name }}/db/model"
{{ $hasFieldTime := false }}
{{ if .Table.Values }}
{{ $hasFldTime := hasFieldType .Table.Fields "time" }}
{{ if eq $hasFldTime true }}
{{ $hasFieldTime = true }}
{{ end }}
{{ end }}
{{ if $hasFieldTime }}"time"{{ end }}
uuid "github.com/satori/go.uuid"
)
{{ if .Table.Values }}
func update{{ fieldNamePrepare .Table.Name}}() {
records := []model.{{ fieldNamePrepare .Table.Name }} {
{{ range $i, $field := .Table.Values }}
{
{{ range $name, $value := $field }}
{{ if eq $name "id" }}
Base: model.Base{
ID: uuid.FromStringOrNil(`{{ $value }}`),
},
{{ end }}
{{ if ne $name "id" }}{{ fieldNamePrepare $name }}: {{ $fld := fieldInTableByName $name $.Table }}{{ $fldTypeName := fieldType $fld }}{{ fieldStringToType $value $fld }},{{ end }}
{{ end }}
},
{{ end }}
}
var err error
tx := BeginTransation()
defer func() {
EndTransaction(tx, err)
}()
tx.Delete(&model.{{ fieldNamePrepare .Table.Name}}{}, "1 = 1")
if res := tx.Create(&records); res.RowsAffected == 0 {
panic(err)
}
}
{{ end }}

View File

@ -1,40 +0,0 @@
package db
import (
"{{ .Name }}/db/model"
{{ $hasFieldTime := false }}{{ range $idxTbl, $tbl := .DB.Tables }}{{ if $tbl.Values }}{{ $hasFldTime := hasFieldType $tbl.Fields "time" }}{{ if eq $hasFldTime true }}{{ $hasFieldTime = true }}{{ end }}{{ end }}{{ if $hasFieldTime }}"time"{{ end }}{{ end }}
uuid "github.com/satori/go.uuid"
)
{{ range $index, $item := .DB.Tables }}{{ if $item.Values }}
func update{{ fieldNamePrepare $item.Name}}() {
records := []model.{{ fieldNamePrepare $item.Name }} {
{{ range $i, $field := $item.Values }}
{
{{ range $name, $value := $field }}
{{ if eq $name "id" }}
Base: model.Base{
ID: uuid.FromStringOrNil(`{{ $value }}`),
},
{{ end }}
{{ if ne $name "id" }}{{ fieldNamePrepare $name }}: {{ $fld := fieldInTableByName $name $item }}{{ $fldTypeName := fieldType $fld }}{{ fieldStringToType $value $fld }},{{ end }}
{{ end }}
},
{{ end }}
}
var err error
tx := BeginTransation()
defer func() {
EndTransaction(tx, err)
}()
tx.Delete(&model.{{ fieldNamePrepare $item.Name}}{}, "1 = 1")
if res := tx.Create(&records); res.RowsAffected == 0 {
panic(err)
}
}
{{ end }}{{ end }}

View File

@ -7,6 +7,7 @@ import (
"crypto/sha512"
"encoding/hex"
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
)
@ -102,3 +103,10 @@ func (user *User) VerifyPassword(value string) (result bool) {
func (user *User) BeforeCreate(scope *gorm.DB) (err error) {
return user.Base.BeforeCreate(scope)
}
func (user *User) GetUserByID(id uuid.UUID, scope *gorm.DB) (usr User, err error) {
if res := scope.Preload("Role").First(&usr, id); res.RowsAffected == 0 {
err = res.Error
}
return
}

View File

@ -12,6 +12,7 @@ var AppConfig struct {
DbPort string `arg:"--db-port,env:DB_PORT" default:"5432" help:"Database port for connect"`
DbLogin string `arg:"--db-login,env:DB_LOGIN" default:"db" help:"Database login for connect"`
DbPassword string `arg:"--db-pwd,env:DB_PWD" default:"db" help:"Database password for connect"`
DbMigrate bool `arg:"--db-migrate,env:DB_MIGRATE" help:"Migrate structure and references in Database"`
Host string `arg:"--host,env:HOST" default:"example.com" help:"Host name for display and other processes"`
Port string `arg:"--port,env:PORT" default:"3000" help:"Open port for incoming connections"`

View File

@ -51,6 +51,10 @@ func main() {
db.DBConnect()
if lib.AppConfig.DbMigrate {
return
}
go func() {
e = echo.New()
@ -72,6 +76,4 @@ func main() {
fmt.Println(err)
}
fmt.Println("exiting")
}

View File

@ -6,6 +6,7 @@ import (
)
func Init(e *echo.Echo) {
e.Use(echomiddleware.RequestID())
e.Use(echomiddleware.BodyLimit("100M"))
e.Use(echomiddleware.Logger())
//e.Use(echomiddleware.Recover())
@ -17,4 +18,17 @@ func Init(e *echo.Echo) {
swagger.Servers = nil
e.Use(middleware.OapiRequestValidator(swagger))*/
e.Use(logging())
}
func logging() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if err := next(c); err != nil {
c.Error(err)
}
// TODO
return nil
}
}
}

View File

@ -5,42 +5,14 @@ import (
"{{ .Name }}/db"
"{{ .Name }}/db/model"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
)
// DeleteUser deleteUser
// @Summary Удаление пользователя
// @Description Удаление информации о пользователе
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} structs.Result
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id} [delete]
// @Security BearerAuth
func delete(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restDelete(c echo.Context) error {
var err error
tx := db.BeginTransation()

View File

@ -11,23 +11,7 @@ import (
uuid "github.com/satori/go.uuid"
)
// GetUser getUser
// @Summary Получить пользователя
// @Description Получения информации о пользователе по его id
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id} [get]
// @Security BearerAuth
func get(c echo.Context) error {
id := uuid.FromStringOrNil(c.Param("id"))
func restGet(c echo.Context, id uuid.UUID) error {
var err error

View File

@ -2,12 +2,16 @@ package user
import (
"{{ .Name }}/route/api/user/role"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"net/http"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
)
func Init(c *echo.Group) {
r := c.Group("/roles")
role.Init(r)
@ -20,3 +24,238 @@ func Init(c *echo.Group) {
c.PUT("/:id", put)
c.DELETE("/:id", delete)
}
// ListUsers listUsers
// @Summary Получить пользователя
// @Description Возвращает список пользователей
// @Tags users
// @Accept json
// @Produce json
// @Success 200 {object} []model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user [get]
// @Security BearerAuth
func listUsers(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restListUsers(c)
}
// GetUser getUser
// @Summary Получить пользователя
// @Description Получения информации о пользователе по его id
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id} [get]
// @Security BearerAuth
func get(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
/*return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})*/
return restGet(c, userID)
}
userID = uuid.FromStringOrNil(c.Param("id"))
return restGet(c, userID)
}
// CreateUser createUser
// @Summary Создать пользователя
// @Description Добавление нового пользователя в систему
// @Tags users
// @Accept json
// @Produce json
// @Param body body model.User true "Описание нового пользователя"
// @Success 200 {object} model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user [post]
// @Security BearerAuth
func post(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restPost(c)
}
// UpdateUser updateUser
// @Summary Обновление пользователя
// @Description Обновление информации о пользователе, а так же смена пароля при необходимости
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Param body body model.User true "Описание существующего пользователя"
// @Success 200 {object} model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id} [put]
// @Security BearerAuth
func put(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restPut(c)
}
// LockUser lockUser
// @Summary Блокирование пользователя
// @Description Принудительное блокирование пользователя
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} structs.Result
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id}/lock [post]
// @Security BearerAuth
func lock(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restLock(c)
}
// UnlockUser unlockUser
// @Summary Разблокирование пользователя
// @Description Разблокирование пользователя
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} structs.Result
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id}/unlock [post]
// @Security BearerAuth
func unlock(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restUnlock(c)
}
// DeleteUser deleteUser
// @Summary Удаление пользователя
// @Description Удаление информации о пользователе
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} structs.Result
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id} [delete]
// @Security BearerAuth
func delete(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restDelete(c)
}
// LdapSearch ldapSearch
// @Summary Найти пользователя в LDAP
// @Description Возвращает список пользователей, найденных в LDAP
// @Tags users
// @Accept json
// @Produce json
// @Param value query string false "строка либо часть строки для поиска"
// @Success 200 {object} []model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/search-ldap [get]
// @Security BearerAuth
func searchLdap(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
return restSearchLdap(c)
}

View File

@ -6,42 +6,13 @@ import (
"{{ .Name }}/db/model"
"{{ .Name }}/lib"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
ldap "github.com/go-ldap/ldap/v3"
)
// LdapSearch ldapSearch
// @Summary Найти пользователя в LDAP
// @Description Возвращает список пользователей, найденных в LDAP
// @Tags users
// @Accept json
// @Produce json
// @Param value query string false "строка либо часть строки для поиска"
// @Success 200 {object} []model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/search-ldap [get]
// @Security BearerAuth
func searchLdap(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restSearchLdap(c echo.Context) error {
if len(c.QueryParam("value")) >= 3 {
conn,err := lib.ConnectToLdap()

View File

@ -5,40 +5,13 @@ import (
"{{ .Name }}/db"
"{{ .Name }}/db/model"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
)
// ListUsers listUsers
// @Summary Получить пользователя
// @Description Возвращает список пользователей
// @Tags users
// @Accept json
// @Produce json
// @Success 200 {object} []model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user [get]
// @Security BearerAuth
func listUsers(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restListUsers(c echo.Context) error {
var err error

View File

@ -5,42 +5,13 @@ import (
"{{ .Name }}/db"
"{{ .Name }}/db/model"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
)
// LockUser lockUser
// @Summary Блокирование пользователя
// @Description Принудительное блокирование пользователя
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} structs.Result
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id}/lock [post]
// @Security BearerAuth
func lock(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restLock(c echo.Context) error {
var err error
tx := db.BeginTransation()

View File

@ -15,34 +15,8 @@ import (
uuid "github.com/satori/go.uuid"
)
// CreateUser createUser
// @Summary Создать пользователя
// @Description Добавление нового пользователя в систему
// @Tags users
// @Accept json
// @Produce json
// @Param body body model.User true "Описание нового пользователя"
// @Success 200 {object} model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user [post]
// @Security BearerAuth
func post(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restPost(c echo.Context) error {
var err error
var userForm model.User

View File

@ -7,43 +7,14 @@ import (
"{{ .Name }}/db"
"{{ .Name }}/db/model"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
)
// UpdateUser updateUser
// @Summary Обновление пользователя
// @Description Обновление информации о пользователе, а так же смена пароля при необходимости
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Param body body model.User true "Описание существующего пользователя"
// @Success 200 {object} model.User
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id} [put]
// @Security BearerAuth
func put(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restPut(c echo.Context) error {
var err error
var userForm model.User

View File

@ -5,42 +5,14 @@ import (
"{{ .Name }}/db"
"{{ .Name }}/db/model"
"{{ .Name }}/middleware"
"{{ .Name }}/structs"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
uuid "github.com/satori/go.uuid"
)
// UnlockUser unlockUser
// @Summary Разблокирование пользователя
// @Description Разблокирование пользователя
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "Идентификатор пользователя"
// @Success 200 {object} structs.Result
// @Failure 400 {object} structs.Result
// @Failure 401 {object} structs.Result
// @Failure 404 {object} structs.Result
// @Failure 500 {object} structs.Result
// @Router /user/{id}/unlock [post]
// @Security BearerAuth
func unlock(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userID := uuid.FromStringOrNil(claims["id"].(string))
if !middleware.InRole(userID, "SEC_ADMIN") {
return c.JSON(http.StatusForbidden, structs.Result{
Result: &[]bool{false}[0],
Code: &[]int{http.StatusForbidden}[0],
Message: &[]string{"Отказано в доступе"}[0],
})
}
func restUnlock(c echo.Context) error {
var err error
tx := db.BeginTransation()