diff --git a/go.mod b/go.mod index a98ca40..3243e03 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/cloudwego/base64x v0.1.5 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/gabriel-vasile/mimetype v1.4.9 // indirect + github.com/gin-contrib/cors v1.7.5 // indirect github.com/gin-contrib/sse v1.1.0 // indirect github.com/gin-gonic/gin v1.10.0 // indirect github.com/go-playground/locales v0.14.1 // indirect diff --git a/go.sum b/go.sum index 0535107..d640934 100644 --- a/go.sum +++ b/go.sum @@ -13,6 +13,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY= github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok= +github.com/gin-contrib/cors v1.7.5 h1:cXC9SmofOrRg0w9PigwGlHG3ztswH6bqq4vJVXnvYMk= +github.com/gin-contrib/cors v1.7.5/go.mod h1:4q3yi7xBEDDWKapjT2o1V7mScKDDr8k+jZ0fSquGoy0= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= diff --git a/internal/auth/jwt.go b/internal/auth/jwt.go index 6406697..6e7cbd5 100644 --- a/internal/auth/jwt.go +++ b/internal/auth/jwt.go @@ -1,6 +1,7 @@ package auth import ( + "strings" "time" "github.com/gin-gonic/gin" @@ -38,26 +39,31 @@ func (j *JwtTokenGenerator) GenerateToken(claims map[string]interface{}) (string // Gin middleware func (j *JwtTokenGenerator) GinMiddleware() gin.HandlerFunc { return func(c *gin.Context) { - token, err := c.Request.Cookie("token") - if err != nil { + authHeader := c.GetHeader("Authorization") + if authHeader == "" { c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"}) return } - t, err := jwt.Parse(token.Value, func(t *jwt.Token) (interface{}, error) { + + tokenString := strings.TrimPrefix(authHeader, "Bearer ") + t, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, jwt.ErrSignatureInvalid } return []byte(j.Key), nil }) + if err != nil { c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"}) return } + claims, ok := t.Claims.(jwt.MapClaims) - if !ok || claims["role"] != "admin" { // Check role, only if its admin let it go + if !ok || claims["role"] != "admin" { c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"}) return } + c.Next() } } \ No newline at end of file diff --git a/internal/helpers/dbHelpers.go b/internal/helpers/dbHelpers.go index c9543df..b6caeb4 100644 --- a/internal/helpers/dbHelpers.go +++ b/internal/helpers/dbHelpers.go @@ -7,7 +7,7 @@ import ( ) func AddMigrations(db *gorm.DB) { - db.AutoMigrate(&models.Post{}, &models.MediaAttachment{}, &models.Account{}, models.ComUser{}) + db.AutoMigrate(&models.Post{}, &models.MediaAttachment{}, &models.Account{}) } diff --git a/internal/models/comUser.go b/internal/models/comUser.go deleted file mode 100644 index 7903254..0000000 --- a/internal/models/comUser.go +++ /dev/null @@ -1,10 +0,0 @@ -package models - -// Funny you are -type ComUser struct { - Id string - Username string - Password string - Email string - IsVerified bool -} diff --git a/internal/server/router.go b/internal/server/router.go index 7ae6ef0..a1571e8 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -5,12 +5,19 @@ import ( handlers_admin "CatsOfMastodonBotGo/internal/web/handlers/admin" handlers_api "CatsOfMastodonBotGo/internal/web/handlers/api" + "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func SetupRouter(appContext *internal.AppContext) *gin.Engine { r := gin.Default() - + + r.Use(cors.New(cors.Config{ + AllowOrigins: []string{"https://extra-mama-chiz.surge.sh"}, // Just for test + AllowMethods: []string{"POST", "GET", "OPTIONS"}, + AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, + AllowCredentials: true, + })) adminDashboardHandler := handlers_admin.NewAdminDashboardHandler(appContext) apiHandler := handlers_api.NewApiEndpointHandler(appContext) @@ -19,8 +26,9 @@ func SetupRouter(appContext *internal.AppContext) *gin.Engine { // My man, this is done way more efficient and fast in .NET, specially the authentication part admin.POST("/login", adminDashboardHandler.Login) - admin.POST("/approve", appContext.Jwt.GinMiddleware() ,adminDashboardHandler.ApproveMedia) - admin.POST("/reject" ,appContext.Jwt.GinMiddleware() , adminDashboardHandler.RejectMedia) + admin.GET("/getmedia", appContext.Jwt.GinMiddleware(), adminDashboardHandler.GetMedia) + admin.POST("/approve", appContext.Jwt.GinMiddleware(), adminDashboardHandler.ApproveMedia) + admin.POST("/reject", appContext.Jwt.GinMiddleware(), adminDashboardHandler.RejectMedia) api := r.Group("/api") diff --git a/internal/services/postService.go b/internal/services/postService.go index ed65dd3..d5c4a93 100644 --- a/internal/services/postService.go +++ b/internal/services/postService.go @@ -60,11 +60,22 @@ func (ps *PostService) GetExistingAccountIds() []string { ps.db.Model(&models.Account{}).Pluck("acc_id", &existingAccountIds) return existingAccountIds } + + func (*PostService) GetNewPosts(existingPostIds []string, posts []models.Post) []models.Post { var newPosts []models.Post = nil for _, post := range posts { if !arrayContains(existingPostIds, post.ID) && len(post.Attachments) > 0 && !post.Account.IsBot { - newPosts = append(newPosts, post) + var allImageMedia = true + for _, attachment := range post.Attachments { + if attachment.Type != "image" { + allImageMedia = false + break + } + } // Inefficient but anyways + if allImageMedia { + newPosts = append(newPosts, post) + } } } return newPosts @@ -94,9 +105,12 @@ func (ps *PostService) GetRandomPost() models.Post { var post models.Post ps.db. Preload("Account"). - Preload("Attachments"). + Preload("Attachments", "approved = ?", true). Order("RANDOM()"). First(&post) + if len(post.Attachments) > 0 { + post.Attachments = []models.MediaAttachment{post.Attachments[0]} + } return post } @@ -112,6 +126,18 @@ func (ps *PostService) RejectMedia(mediaId string) bool { Update("rejected", true).RowsAffected > 0 } +// Get a post which approve and rejet are false (For admin panel) +func (ps *PostService) GetMedia() models.MediaAttachment { + var media models.MediaAttachment + ps.db.Model(&models.MediaAttachment{}). + Where("approved = ?", false). + Where("rejected = ?", false). + Order("RANDOM()"). + First(&media) + return media +} + + func arrayContains(arr []string, str string) bool { for _, a := range arr { if a == str { diff --git a/internal/web/handlers/admin/adminDash.go b/internal/web/handlers/admin/adminDash.go index 8332fce..bba60cc 100644 --- a/internal/web/handlers/admin/adminDash.go +++ b/internal/web/handlers/admin/adminDash.go @@ -45,10 +45,15 @@ func (appContext *AdminDashboardHandler) RejectMedia(c *gin.Context) { } } +func (appContext *AdminDashboardHandler) GetMedia(c *gin.Context) { + media := appContext.AppContext.PostService.GetMedia() + c.JSON(http.StatusOK, media) +} + func (appContext *AdminDashboardHandler) Login(c *gin.Context) { var input requestmodels.LoginInput - + // Validate data if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) @@ -62,17 +67,13 @@ func (appContext *AdminDashboardHandler) Login(c *gin.Context) { return } - c.SetCookie("token", token, 3600, "/", "", false, true) - c.JSON(http.StatusOK, gin.H{"message": "Login successful"}) + c.JSON(http.StatusOK, gin.H{"message": "Login successful", "token": token}) } else { c.JSON(401, gin.H{ - "YouAreOn": "Unauthorized", + "error": "wrong password", }) return } - c.JSON(200, gin.H{ - "YouAreOn": "Login", - }) }