wakapi/middlewares/authenticate.go

39 lines
844 B
Go
Raw Normal View History

2019-05-06 01:40:41 +03:00
package middlewares
import (
"context"
"encoding/base64"
"net/http"
"strings"
"github.com/n1try/wakapi/models"
"github.com/n1try/wakapi/services"
)
type AuthenticateMiddleware struct {
UserSrvc *services.UserService
}
func (m *AuthenticateMiddleware) Handle(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
authHeader := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeader) != 2 {
w.WriteHeader(http.StatusUnauthorized)
2019-05-06 01:40:41 +03:00
return
}
key, err := base64.StdEncoding.DecodeString(authHeader[1])
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
2019-05-06 01:40:41 +03:00
return
}
user, err := m.UserSrvc.GetUserByKey(strings.TrimSpace(string(key)))
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
2019-05-06 01:40:41 +03:00
return
}
2019-05-11 18:49:56 +03:00
ctx := context.WithValue(r.Context(), models.UserKey, user)
2019-05-06 01:40:41 +03:00
next(w, r.WithContext(ctx))
}