miniflux/middleware/user_session.go

75 lines
1.8 KiB
Go
Raw Normal View History

2017-12-17 03:07:53 +01:00
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package middleware
import (
"context"
"net/http"
"github.com/miniflux/miniflux/http/cookie"
"github.com/miniflux/miniflux/http/route"
2017-12-17 03:07:53 +01:00
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model"
"github.com/gorilla/mux"
)
2018-04-28 05:38:46 +02:00
// UserSession handles the user session middleware.
func (m *Middleware) UserSession(next http.Handler) http.Handler {
2017-12-17 03:07:53 +01:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2018-04-28 05:38:46 +02:00
session := m.getSessionFromCookie(r)
2017-12-17 03:07:53 +01:00
if session == nil {
logger.Debug("[Middleware:UserSession] Session not found")
2018-04-28 05:38:46 +02:00
if m.isPublicRoute(r) {
2017-12-17 03:07:53 +01:00
next.ServeHTTP(w, r)
} else {
2018-04-28 05:38:46 +02:00
http.Redirect(w, r, route.Path(m.router, "login"), http.StatusFound)
2017-12-17 03:07:53 +01:00
}
} else {
logger.Debug("[Middleware:UserSession] %s", session)
ctx := r.Context()
ctx = context.WithValue(ctx, UserIDContextKey, session.UserID)
ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
ctx = context.WithValue(ctx, UserSessionTokenContextKey, session.Token)
next.ServeHTTP(w, r.WithContext(ctx))
}
})
}
2018-04-28 05:38:46 +02:00
func (m *Middleware) isPublicRoute(r *http.Request) bool {
2017-12-17 03:07:53 +01:00
route := mux.CurrentRoute(r)
switch route.GetName() {
case "login",
"checkLogin",
"stylesheet",
"javascript",
"oauth2Redirect",
"oauth2Callback",
"appIcon",
"favicon",
"webManifest":
2017-12-17 03:07:53 +01:00
return true
default:
return false
}
}
2018-04-28 05:38:46 +02:00
func (m *Middleware) getSessionFromCookie(r *http.Request) *model.UserSession {
2017-12-17 03:07:53 +01:00
sessionCookie, err := r.Cookie(cookie.CookieUserSessionID)
if err == http.ErrNoCookie {
return nil
}
2018-04-28 05:38:46 +02:00
session, err := m.store.UserSessionByToken(sessionCookie.Value)
2017-12-17 03:07:53 +01:00
if err != nil {
logger.Error("[Middleware:UserSession] %v", err)
return nil
}
return session
}