|
|
@ -1,9 +1,14 @@ |
|
|
|
package auth |
|
|
|
|
|
|
|
import ( |
|
|
|
"context" |
|
|
|
"net/http" |
|
|
|
|
|
|
|
"git.pluggableideas.com/destrealm/go/keystar/crypto" |
|
|
|
) |
|
|
|
|
|
|
|
type UserLoader func(id int) (BaseUser, error) |
|
|
|
|
|
|
|
type contextKey struct { |
|
|
|
key string |
|
|
|
} |
|
|
@ -12,12 +17,50 @@ func (k *contextKey) String() string { |
|
|
|
return "Capstan authentication key:" + k.key |
|
|
|
} |
|
|
|
|
|
|
|
var authContextKey = &contextKey{"authentication"} |
|
|
|
|
|
|
|
type AuthenticatorMiddleware struct { |
|
|
|
// FailController indicates which controller should be used as the
|
|
|
|
// redirection target if the user's authentication fails. FailController
|
|
|
|
// string FailURL url.URL
|
|
|
|
|
|
|
|
CookieName string |
|
|
|
|
|
|
|
Codec UserCodec |
|
|
|
|
|
|
|
UserLoader UserLoader |
|
|
|
|
|
|
|
sealer crypto.Sealer |
|
|
|
} |
|
|
|
|
|
|
|
func (m *AuthenticatorMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
|
|
|
func (m *AuthenticatorMiddleware) Middleware() func(next http.Handler) http.Handler { |
|
|
|
return func(next http.Handler) http.Handler { |
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) { |
|
|
|
cookie, err := r.Cookie(m.CookieName) |
|
|
|
if err != nil { |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
user, err := m.Codec.Decode([]byte(cookie.Value)) |
|
|
|
if err != nil { |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// UserLoader may return the same user instance or it may return a
|
|
|
|
// new instance that implements the BaseUser interface. The latter
|
|
|
|
// method allows for later casting to a different interface or type
|
|
|
|
// whenever more application-specific data is needed.
|
|
|
|
user, err = m.UserLoader(user.ID()) |
|
|
|
if err != nil { |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
r = r.WithContext(context.WithValue(r.Context(), authContextKey, user)) |
|
|
|
next.ServeHTTP(w, r) |
|
|
|
} |
|
|
|
return http.HandlerFunc(fn) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
// Attach to request context?
|
|
|
|
//func WriteCookie()
|