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.
51 lines
1.1 KiB
51 lines
1.1 KiB
package middlewares
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.aiterp.net/lucifer/lucifer/models"
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
// Session is a middleware that adds a Session to the request context if there
|
|
// is one.
|
|
func Session(repo models.SessionRepository) mux.MiddlewareFunc {
|
|
clearCookie := &http.Cookie{
|
|
Name: "lucifer_session",
|
|
Value: "",
|
|
Path: "/",
|
|
Expires: time.Unix(0, 0),
|
|
|
|
HttpOnly: true,
|
|
}
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Find cookie
|
|
cookie, err := r.Cookie("lucifer_session")
|
|
if err != nil || cookie == nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Check session existence
|
|
session, err := repo.FindByID(r.Context(), cookie.Value)
|
|
if err != nil {
|
|
http.SetCookie(w, clearCookie)
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Check if session has expired
|
|
if session.Expired() {
|
|
http.SetCookie(w, clearCookie)
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Proceed.
|
|
next.ServeHTTP(w, r.WithContext(session.InContext(r.Context())))
|
|
})
|
|
}
|
|
}
|