wakapi/middlewares/authenticate.go

129 lines
3.2 KiB
Go
Raw Normal View History

2019-05-06 01:40:41 +03:00
package middlewares
import (
"context"
"errors"
2020-05-24 18:39:19 +03:00
"fmt"
2020-10-16 17:11:14 +03:00
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/utils"
"log"
2019-05-06 01:40:41 +03:00
"net/http"
"strings"
"time"
"github.com/patrickmn/go-cache"
2019-05-06 01:40:41 +03:00
2020-03-31 13:22:17 +03:00
"github.com/muety/wakapi/models"
"github.com/muety/wakapi/services"
2019-05-06 01:40:41 +03:00
)
type AuthenticateMiddleware struct {
2020-10-16 17:11:14 +03:00
config *conf.Config
cache *cache.Cache
userSrvc services.IUserService
whitelistPaths []string
}
func NewAuthenticateMiddleware(userService services.IUserService, whitelistPaths []string) *AuthenticateMiddleware {
return &AuthenticateMiddleware{
2020-10-16 17:11:14 +03:00
config: conf.Get(),
userSrvc: userService,
cache: cache.New(1*time.Hour, 2*time.Hour),
whitelistPaths: whitelistPaths,
}
2019-05-06 01:40:41 +03:00
}
func (m *AuthenticateMiddleware) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m.ServeHTTP(w, r, h.ServeHTTP)
})
}
func (m *AuthenticateMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
for _, p := range m.whitelistPaths {
2020-04-08 22:29:11 +03:00
if strings.HasPrefix(r.URL.Path, p) || r.URL.Path == p {
next(w, r)
return
}
}
var user *models.User
user, err := m.tryGetUserByCookie(r)
if err != nil {
user, err = m.tryGetUserByApiKey(r)
}
if err != nil {
if strings.HasPrefix(r.URL.Path, "/api") {
w.WriteHeader(http.StatusUnauthorized)
} else {
http.SetCookie(w, m.config.GetClearCookie(models.AuthCookieKey, "/"))
http.Redirect(w, r, fmt.Sprintf("%s/?error=unauthorized", m.config.Server.BasePath), http.StatusFound)
}
2019-05-06 01:40:41 +03:00
return
}
m.cache.Set(user.ID, user, cache.DefaultExpiration)
ctx := context.WithValue(r.Context(), models.UserKey, user)
next(w, r.WithContext(ctx))
}
func (m *AuthenticateMiddleware) tryGetUserByApiKey(r *http.Request) (*models.User, error) {
key, err := utils.ExtractBearerAuth(r)
2019-05-06 01:40:41 +03:00
if err != nil {
return nil, err
2019-05-06 01:40:41 +03:00
}
var user *models.User
userKey := strings.TrimSpace(key)
cachedUser, ok := m.cache.Get(userKey)
if !ok {
user, err = m.userSrvc.GetUserByKey(userKey)
if err != nil {
return nil, err
}
} else {
user = cachedUser.(*models.User)
2019-05-06 01:40:41 +03:00
}
return user, nil
}
2019-05-06 01:40:41 +03:00
func (m *AuthenticateMiddleware) tryGetUserByCookie(r *http.Request) (*models.User, error) {
login, err := utils.ExtractCookieAuth(r, m.config)
if err != nil {
return nil, err
}
cachedUser, ok := m.cache.Get(login.Username)
if ok {
return cachedUser.(*models.User), nil
}
user, err := m.userSrvc.GetUserById(login.Username)
if err != nil {
return nil, err
}
if !CheckAndMigratePassword(user, login, m.config.Security.PasswordSalt, &m.userSrvc) {
return nil, errors.New("invalid password")
}
return user, nil
2019-05-06 01:40:41 +03:00
}
// migrate old md5-hashed passwords to new salted bcrypt hashes for backwards compatibility
func CheckAndMigratePassword(user *models.User, login *models.Login, salt string, userServiceRef *services.IUserService) bool {
if utils.IsMd5(user.Password) {
2020-10-16 17:11:14 +03:00
if utils.CompareMd5(user.Password, login.Password, "") {
log.Printf("migrating old md5 password to new bcrypt format for user '%s'", user.ID)
(*userServiceRef).MigrateMd5Password(user, login)
return true
}
return false
}
2020-10-16 17:11:14 +03:00
return utils.CompareBcrypt(user.Password, login.Password, salt)
}