Merge pull request #3 from Nekiiinkognito/adminMiddleware

Some epic changes
This commit is contained in:
Maxim 2024-11-14 19:56:31 +03:00 committed by GitHub
commit 8f12afae7e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 154 additions and 26 deletions

View File

@ -148,14 +148,13 @@ func (q *Queries) GetPostsByUserId(ctx context.Context, userID int64) ([]Post, e
const updatePostByPostId = `-- name: UpdatePostByPostId :one const updatePostByPostId = `-- name: UpdatePostByPostId :one
UPDATE public.posts UPDATE public.posts
SET blog_id=$1, user_id=$2, title=$3, "content"=$4, updated_at=CURRENT_TIMESTAMP SET blog_id=$1, title=$2, "content"=$3, updated_at=CURRENT_TIMESTAMP
WHERE post_id = $5 WHERE post_id = $4
RETURNING post_id, blog_id, user_id, title, content, created_at, updated_at RETURNING post_id, blog_id, user_id, title, content, created_at, updated_at
` `
type UpdatePostByPostIdParams struct { type UpdatePostByPostIdParams struct {
BlogID pgtype.Int8 `json:"blog_id"` BlogID pgtype.Int8 `json:"blog_id"`
UserID int64 `json:"user_id"`
Title pgtype.Text `json:"title"` Title pgtype.Text `json:"title"`
Content pgtype.Text `json:"content"` Content pgtype.Text `json:"content"`
PostID int64 `json:"post_id"` PostID int64 `json:"post_id"`
@ -164,7 +163,6 @@ type UpdatePostByPostIdParams struct {
func (q *Queries) UpdatePostByPostId(ctx context.Context, arg UpdatePostByPostIdParams) (Post, error) { func (q *Queries) UpdatePostByPostId(ctx context.Context, arg UpdatePostByPostIdParams) (Post, error) {
row := q.db.QueryRow(ctx, updatePostByPostId, row := q.db.QueryRow(ctx, updatePostByPostId,
arg.BlogID, arg.BlogID,
arg.UserID,
arg.Title, arg.Title,
arg.Content, arg.Content,
arg.PostID, arg.PostID,

View File

@ -21,8 +21,8 @@ RETURNING *;
-- name: UpdatePostByPostId :one -- name: UpdatePostByPostId :one
UPDATE public.posts UPDATE public.posts
SET blog_id=$1, user_id=$2, title=$3, "content"=$4, updated_at=CURRENT_TIMESTAMP SET blog_id=$1, title=$2, "content"=$3, updated_at=CURRENT_TIMESTAMP
WHERE post_id = $5 WHERE post_id = $4
RETURNING *; RETURNING *;
-- name: DeletePostByPostId :exec -- name: DeletePostByPostId :exec

View File

@ -1,10 +1,8 @@
package middleware package middleware
import ( import (
"context"
rest_api_stuff "enshi/REST_API_stuff" rest_api_stuff "enshi/REST_API_stuff"
db_repo "enshi/db/go_queries" "enshi/middleware/checkRole"
"enshi/db_connection"
"enshi/middleware/getters" "enshi/middleware/getters"
"fmt" "fmt"
@ -21,16 +19,14 @@ func AdminMiddleware() gin.HandlerFunc {
c.Abort() c.Abort()
} }
user, err := isAdmin, err := checkRole.IsAdmin(userId)
db_repo.New(db_connection.Dbx).
GetUserById(context.Background(), userId)
if err != nil || user.UserID == 0 { if err != nil {
rest_api_stuff.BadRequestAnswer(c, err) rest_api_stuff.BadRequestAnswer(c, err)
c.Abort() c.Abort()
} }
if !user.IsAdmin { if !isAdmin {
rest_api_stuff.UnauthorizedAnswer(c, fmt.Errorf("not allowed")) rest_api_stuff.UnauthorizedAnswer(c, fmt.Errorf("not allowed"))
c.Abort() c.Abort()
} }

View File

@ -0,0 +1,23 @@
package checkRole
import (
"context"
db_repo "enshi/db/go_queries"
"enshi/db_connection"
)
func IsAdmin(userId int64) (bool, error) {
user, err :=
db_repo.New(db_connection.Dbx).
GetUserById(context.Background(), userId)
if err != nil || user.UserID == 0 {
return false, err
}
if !user.IsAdmin {
return false, nil
}
return true, nil
}

View File

@ -0,0 +1,23 @@
package checkRole
import (
"context"
db_repo "enshi/db/go_queries"
"enshi/db_connection"
)
func IsOwnerOfThePost(userId int64, postId int64) (bool, error) {
post, err :=
db_repo.New(db_connection.Dbx).
GetPostsByPostId(context.Background(), postId)
if err != nil {
return false, err
}
if post.UserID != userId {
return false, nil
}
return true, nil
}

View File

@ -30,13 +30,8 @@ func GetClaimsFromContext(c *gin.Context) (auth.UserInfoJWT, error) {
UserInfo.Id = parsedUserId UserInfo.Id = parsedUserId
UserInfo.Username = claims.(jwt.MapClaims)["username"].(string) UserInfo.Username = claims.(jwt.MapClaims)["username"].(string)
isAdmin, err := strconv.ParseBool(claims.(jwt.MapClaims)["isAdmin"].(string)) isAdmin := claims.(jwt.MapClaims)["isAdmin"].(bool)
if err != nil {
UserInfo.IsAdmin = false
fmt.Println(global.RedColor + "isAdmin prop corrupted" + global.ResetColor)
} else {
UserInfo.IsAdmin = isAdmin UserInfo.IsAdmin = isAdmin
}
return UserInfo, nil return UserInfo, nil

View File

@ -13,7 +13,7 @@ import (
func DeletePost(c *gin.Context) { func DeletePost(c *gin.Context) {
var deletePostId struct { var deletePostId struct {
PostId int64 PostId int64 `json:"post_id"`
} }
if err := c.BindJSON(&deletePostId); err != nil { if err := c.BindJSON(&deletePostId); err != nil {

View File

@ -12,7 +12,7 @@ import (
func GetPost(c *gin.Context) { func GetPost(c *gin.Context) {
var postParams struct { var postParams struct {
PostId int64 PostId int64 `json:"post_id"`
} }
if err := c.BindJSON(&postParams); err != nil { if err := c.BindJSON(&postParams); err != nil {

View File

@ -0,0 +1,51 @@
package postsRoutes
import (
"context"
rest_api_stuff "enshi/REST_API_stuff"
db_repo "enshi/db/go_queries"
"enshi/db_connection"
"enshi/middleware/checkRole"
"enshi/middleware/getters"
"fmt"
"github.com/gin-gonic/gin"
)
func UpdatePost(c *gin.Context) {
var UpdatedPostParams db_repo.UpdatePostByPostIdParams
if err := c.BindJSON(&UpdatedPostParams); err != nil {
rest_api_stuff.BadRequestAnswer(c, err)
return
}
userId, err := getters.GetUserIdFromContext(c)
if err != nil {
rest_api_stuff.InternalErrorAnswer(c, err)
return
}
if isOwner, _ := checkRole.IsOwnerOfThePost(
userId,
UpdatedPostParams.PostID,
); !isOwner {
rest_api_stuff.UnauthorizedAnswer(c, fmt.Errorf("you are now allowed to change this"))
return
}
_, err = db_repo.New(
db_connection.Dbx,
).UpdatePostByPostId(
context.Background(),
UpdatedPostParams,
)
if err != nil {
rest_api_stuff.InternalErrorAnswer(c, err)
return
}
rest_api_stuff.OkAnswer(c, "post has been updated")
}

View File

@ -0,0 +1,38 @@
package userProfileRoutes
import (
"context"
rest_api_stuff "enshi/REST_API_stuff"
db_repo "enshi/db/go_queries"
"enshi/db_connection"
"enshi/middleware/getters"
"github.com/gin-gonic/gin"
)
func UpdateUserProfile(c *gin.Context) {
var newProfile db_repo.UpdateProfileByUserIdParams
if err := c.BindJSON(&newProfile); err != nil {
rest_api_stuff.BadRequestAnswer(c, err)
return
}
userId, err := getters.GetUserIdFromContext(c)
if err != nil {
rest_api_stuff.InternalErrorAnswer(c, err)
return
}
newProfile.UserID = userId
if _, err := db_repo.New(db_connection.Dbx).UpdateProfileByUserId(
context.Background(),
newProfile,
); err != nil {
rest_api_stuff.InternalErrorAnswer(c, err)
return
}
rest_api_stuff.OkAnswer(c, "profile was updated")
}

View File

@ -5,6 +5,7 @@ import (
"enshi/routes" "enshi/routes"
"enshi/routes/authRoutes" "enshi/routes/authRoutes"
"enshi/routes/postsRoutes" "enshi/routes/postsRoutes"
"enshi/routes/userProfileRoutes"
"net/http" "net/http"
"strings" "strings"
@ -30,17 +31,20 @@ func SetupRotes(g *gin.Engine) error {
freeGroup.POST("login", authRoutes.Login) freeGroup.POST("login", authRoutes.Login)
freeGroup.POST("registerUser", authRoutes.RegisterUser) freeGroup.POST("registerUser", authRoutes.RegisterUser)
freeGroup.GET("getPost", postsRoutes.GetPost)
// Auth group routes // Auth group routes
authGroup := g.Group("/") authGroup := g.Group("/")
authGroup.Use(middleware.AuthMiddleware()) authGroup.Use(middleware.AuthMiddleware())
authGroup.GET("getPost", postsRoutes.GetPost) authGroup.POST("updatePost", postsRoutes.UpdatePost)
authGroup.POST("createPost", postsRoutes.CreatePost) authGroup.POST("createPost", postsRoutes.CreatePost)
authGroup.POST("deletePost", postsRoutes.DeletePost)
authGroup.POST("changeUserProfile", routes.ChangeUserProfile) authGroup.POST("changeUserProfile", routes.ChangeUserProfile)
authGroup.POST("updateProfile", userProfileRoutes.UpdateUserProfile)
authGroup.DELETE("deletePost", postsRoutes.DeletePost)
// Admin group routes
adminGroup := authGroup.Group("/admin/") adminGroup := authGroup.Group("/admin/")
adminGroup.Use(middleware.AdminMiddleware()) adminGroup.Use(middleware.AdminMiddleware())