Skip to content

Commit

Permalink
methods. check auth directly in methods
Browse files Browse the repository at this point in the history
  • Loading branch information
edospadoni committed Mar 13, 2024
1 parent 63649fa commit d47b738
Showing 1 changed file with 37 additions and 26 deletions.
63 changes: 37 additions & 26 deletions api/methods/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,15 @@ import (

func GetAccounts(c *gin.Context) {
// check auth for not admin users
checkAuth(c)
isAdmin, _ := storage.IsAdmin(jwt.ExtractClaims(c)["id"].(string))
if !isAdmin {
c.JSON(http.StatusForbidden, structs.Map(response.StatusForbidden{
Code: 403,
Message: "can't access this resource",
Data: nil,
}))
return
}

// execute query
accounts, err := storage.GetAccounts()
Expand Down Expand Up @@ -58,7 +66,15 @@ func GetAccounts(c *gin.Context) {

func GetAccount(c *gin.Context) {
// check auth for not admin users
checkAuth(c)
isAdmin, _ := storage.IsAdmin(jwt.ExtractClaims(c)["id"].(string))
if !isAdmin {
c.JSON(http.StatusForbidden, structs.Map(response.StatusForbidden{
Code: 403,
Message: "can't access this resource",
Data: nil,
}))
return
}

// get account id
accountID := c.Param("account_id")
Expand Down Expand Up @@ -95,7 +111,15 @@ func GetAccount(c *gin.Context) {

func AddAccount(c *gin.Context) {
// check auth for not admin users
checkAuth(c)
isAdmin, _ := storage.IsAdmin(jwt.ExtractClaims(c)["id"].(string))
if !isAdmin {
c.JSON(http.StatusForbidden, structs.Map(response.StatusForbidden{
Code: 403,
Message: "can't access this resource",
Data: nil,
}))
return
}

// get account fields
var json models.Account
Expand Down Expand Up @@ -130,11 +154,8 @@ func UpdateAccount(c *gin.Context) {
// get account id
accountID := c.Param("account_id")

// get claims
claims := jwt.ExtractClaims(c)

// check is admin
isAdmin, id := storage.IsAdmin(claims["id"].(string))
isAdmin, id := storage.IsAdmin(jwt.ExtractClaims(c)["id"].(string))

// check authorization
if !isAdmin && accountID != id {
Expand Down Expand Up @@ -176,7 +197,15 @@ func UpdateAccount(c *gin.Context) {

func DeleteAccount(c *gin.Context) {
// check auth
checkAuth(c)
isAdmin, _ := storage.IsAdmin(jwt.ExtractClaims(c)["id"].(string))
if !isAdmin {
c.JSON(http.StatusForbidden, structs.Map(response.StatusForbidden{
Code: 403,
Message: "can't access this resource",
Data: nil,
}))
return
}

// get account id
accountID := c.Param("account_id")
Expand All @@ -201,21 +230,3 @@ func DeleteAccount(c *gin.Context) {
Data: nil,
}))
}

func checkAuth(c *gin.Context) {
// get claims
claims := jwt.ExtractClaims(c)

// check is admin
isAdmin, _ := storage.IsAdmin(claims["id"].(string))

// check authorization
if !isAdmin {
c.JSON(http.StatusForbidden, structs.Map(response.StatusForbidden{
Code: 403,
Message: "can't access this resource",
Data: nil,
}))
return
}
}

0 comments on commit d47b738

Please sign in to comment.