2014-01-09 06:42:05 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2014-01-09 23:18:49 +00:00
|
|
|
|
|
|
|
ctx "github.com/gorilla/context"
|
2014-01-10 03:21:54 +00:00
|
|
|
"github.com/jordan-wright/gophish/auth"
|
2014-01-09 06:42:05 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// GetContext wraps each request in a function which fills in the context for a given request.
|
|
|
|
// This includes setting the User and Session keys and values as necessary for use in later functions.
|
2014-01-11 04:37:42 +00:00
|
|
|
func GetContext(handler http.Handler) http.HandlerFunc {
|
2014-01-09 06:42:05 +00:00
|
|
|
// Set the context here
|
2014-01-11 04:37:42 +00:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2014-01-09 23:18:49 +00:00
|
|
|
// Set the context appropriately here.
|
2014-01-10 03:21:54 +00:00
|
|
|
// Set the session
|
|
|
|
session, _ := auth.Store.Get(r, "gophish")
|
2014-01-10 04:21:12 +00:00
|
|
|
// Put the session in the context so that
|
2014-01-10 03:21:54 +00:00
|
|
|
ctx.Set(r, "session", session)
|
2014-01-10 04:21:12 +00:00
|
|
|
if id, ok := session.Values["id"]; ok {
|
|
|
|
u, err := auth.GetUser(id.(int))
|
|
|
|
if err != nil {
|
|
|
|
ctx.Set(r, "user", nil)
|
|
|
|
}
|
|
|
|
ctx.Set(r, "user", u)
|
|
|
|
} else {
|
|
|
|
ctx.Set(r, "user", nil)
|
|
|
|
}
|
2014-01-09 06:42:05 +00:00
|
|
|
handler.ServeHTTP(w, r)
|
2014-01-10 03:21:54 +00:00
|
|
|
// Remove context contents
|
2014-01-09 23:18:49 +00:00
|
|
|
ctx.Clear(r)
|
2014-01-11 04:37:42 +00:00
|
|
|
}
|
2014-01-09 06:42:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// RequireLogin is a simple middleware which checks to see if the user is currently logged in.
|
|
|
|
// If not, the function returns a 302 redirect to the login page.
|
2014-01-11 04:37:42 +00:00
|
|
|
func RequireLogin(handler http.Handler) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2014-01-10 04:21:12 +00:00
|
|
|
if u := ctx.Get(r, "user"); u != nil {
|
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
} else {
|
|
|
|
http.Redirect(w, r, "/login", 302)
|
|
|
|
}
|
2014-01-11 04:37:42 +00:00
|
|
|
}
|
2014-01-09 06:42:05 +00:00
|
|
|
}
|