admin check

This commit is contained in:
BENEDEK László 2024-10-10 22:27:01 +02:00
parent 8e0e53af0d
commit 84ead30400
3 changed files with 50 additions and 2 deletions

View File

@ -33,5 +33,24 @@ func LoggedIn(c *gin.Context) {
} }
func IsAdmin(c *gin.Context) { func IsAdmin(c *gin.Context) {
neptun, exists := c.Get("neptun")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{
"status": http.StatusUnauthorized,
"error": "not logged in",
})
c.Abort()
return
}
err := auth.IsAdmin(neptun.(string))
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"status": http.StatusUnauthorized,
"error": "not an admin",
})
c.Abort()
return
}
} }

View File

@ -26,7 +26,7 @@ func Listen(address string, path string) {
apiAuth.GET("login", auth.Login) apiAuth.GET("login", auth.Login)
} }
apiTest := api.Group("test").Use(auth.LoggedIn) apiTest := api.Group("test").Use(auth.LoggedIn).Use(auth.IsAdmin)
{ {
apiTest.GET("logged_in", func(c *gin.Context) { apiTest.GET("logged_in", func(c *gin.Context) {
neptun, _ := c.Get("neptun") neptun, _ := c.Get("neptun")
@ -37,6 +37,13 @@ func Listen(address string, path string) {
"neptun": neptun, "neptun": neptun,
}) })
}) })
apiTest.GET("is_admin", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "if you see this you are an admin",
})
})
} }
} }

View File

@ -1,6 +1,8 @@
package auth package auth
import ( import (
"errors"
"git.tek.govt.hu/dowerx/szoe-pontok/database" "git.tek.govt.hu/dowerx/szoe-pontok/database"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
@ -17,7 +19,27 @@ func LoggedIn(token string) (string, error) {
} }
func IsAdmin(neptun string) error { func IsAdmin(neptun string) error {
// db := database.GetDB() db := database.GetDB()
rows, err := db.NamedQuery(`select count(*) from "admin" inner join "user" on "user"."id" = "admin"."user" where "user"."neptun" = :neptun`,
map[string]interface{}{
"neptun": neptun,
})
if err != nil {
return err
}
var count int
if !rows.Next() {
return errors.New("not an admin")
}
rows.Scan(&count)
if count != 1 {
return errors.New("not an admin")
}
return nil return nil
} }