You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1014 B
49 lines
1014 B
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()
|
|
}
|
|
}
|