Gisle Aune
5 years ago
2 changed files with 91 additions and 1 deletions
@ -0,0 +1,58 @@ |
|||
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 cookie expiration
|
|||
if cookie.Expires.IsZero() || time.Now().After(cookie.Expires) { |
|||
http.SetCookie(w, clearCookie) |
|||
next.ServeHTTP(w, r) |
|||
return |
|||
} |
|||
|
|||
// Check session existence
|
|||
session, err := repo.FindSessionByID(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()))) |
|||
}) |
|||
} |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue