7 changed files with 133 additions and 24 deletions
-
2README.md
-
9api/v1/users/route.go
-
32api/v1/users/users.go
-
37cmd/server/server.go
-
21lib/authentication/authentication.go
-
7lib/cache/cache.go
-
49lib/middlewares/authentication.go
@ -0,0 +1,21 @@ |
|||
package authentication |
|||
|
|||
import ( |
|||
"errors" |
|||
"fmt" |
|||
|
|||
"git.devices.local/mawas/golang-api-skeleton/lib/response" |
|||
"github.com/gin-gonic/gin" |
|||
) |
|||
|
|||
// Authorized blocks unauthorized requestors
|
|||
func Authorized(c *gin.Context) { |
|||
var resp response.Envelope |
|||
userID, exists := c.Get("userID") |
|||
if !exists { |
|||
c.AbortWithStatusJSON(403, resp.AppendError(errors.New("unauthorized"))) |
|||
return |
|||
} |
|||
fmt.Println("permission check", userID) |
|||
// TODO add cache perm check here
|
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
package middlewares |
|||
|
|||
import ( |
|||
"strings" |
|||
|
|||
"git.devices.local/mawas/golang-api-skeleton/lib/cache" |
|||
"github.com/gin-gonic/gin" |
|||
) |
|||
|
|||
func Authentication() gin.HandlerFunc { |
|||
return func(c *gin.Context) { |
|||
tokenString, err := c.Cookie("token") |
|||
appCache := c.MustGet("cache").(cache.Cache) |
|||
// failed to read cookie
|
|||
if err != nil { |
|||
// try reading HTTP Header
|
|||
authorization := c.Request.Header.Get("Authorization") |
|||
if authorization == "" { |
|||
c.Next() |
|||
return |
|||
} |
|||
sp := strings.Split(authorization, "Bearer ") |
|||
// invalid token
|
|||
if len(sp) < 2 { |
|||
c.Next() |
|||
return |
|||
} |
|||
tokenString = sp[1] |
|||
} |
|||
// https://datatracker.ietf.org/doc/rfc8959/?include_text=1
|
|||
userID, err := appCache.Get("token:" + tokenString) |
|||
if err != nil { |
|||
c.Next() |
|||
return |
|||
} |
|||
if userID != nil { |
|||
username, err := appCache.Get("user:" + *userID) |
|||
if err != nil { |
|||
c.Next() |
|||
return |
|||
} |
|||
if username != nil { |
|||
c.Set("username", *username) |
|||
} |
|||
c.Set("userID", *userID) |
|||
} |
|||
c.Next() |
|||
} |
|||
} |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue