1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

Add user cache in authentication middleware.

This commit is contained in:
Ferdinand Muetsch 2019-05-21 14:23:41 +02:00
parent 86fe3a4bae
commit e572eb3b10

View File

@ -5,6 +5,10 @@ import (
"encoding/base64" "encoding/base64"
"net/http" "net/http"
"strings" "strings"
"time"
"fmt"
"github.com/patrickmn/go-cache"
"github.com/n1try/wakapi/models" "github.com/n1try/wakapi/models"
"github.com/n1try/wakapi/services" "github.com/n1try/wakapi/services"
@ -12,9 +16,22 @@ import (
type AuthenticateMiddleware struct { type AuthenticateMiddleware struct {
UserSrvc *services.UserService UserSrvc *services.UserService
Cache *cache.Cache
Initialized bool
}
func (m *AuthenticateMiddleware) Init() {
if m.Cache == nil {
m.Cache = cache.New(1*time.Hour, 2*time.Hour)
}
m.Initialized = true
} }
func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if !m.Initialized {
m.Init()
}
authHeader := strings.Split(r.Header.Get("Authorization"), " ") authHeader := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeader) != 2 { if len(authHeader) != 2 {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
@ -27,12 +44,22 @@ func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request,
return return
} }
user, err := m.UserSrvc.GetUserByKey(strings.TrimSpace(string(key))) var user *models.User
if err != nil { userKey := strings.TrimSpace(string(key))
w.WriteHeader(http.StatusUnauthorized) cachedUser, ok := m.Cache.Get(userKey)
return if !ok {
user, err = m.UserSrvc.GetUserByKey(userKey)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
} else {
fmt.Println("Cache Hit")
user = cachedUser.(*models.User)
} }
m.Cache.Set(userKey, user, cache.DefaultExpiration)
ctx := context.WithValue(r.Context(), models.UserKey, user) ctx := context.WithValue(r.Context(), models.UserKey, user)
next(w, r.WithContext(ctx)) next(w, r.WithContext(ctx))
} }