Browse Source

Still deciding on API.

template-theme-rewrite
Benjamin Shelton 1 year ago
parent
commit
fb69fee4e0
2 changed files with 50 additions and 2 deletions
  1. +5
    -0
      auth/api.go
  2. +45
    -2
      auth/types.go

+ 5
- 0
auth/api.go View File

@ -23,6 +23,11 @@ type AuthenticatableUser interface {
type AuthMixin struct {
}
type UserCodec interface {
Encode() ([]byte, error)
Decode([]byte) (BaseUser, error)
}
// CurrentUser loads and returns user data from the routing context. This will
// examine session state whenever called.
/*func CurrentUser(ctx *routing.Context) BaseUser {


+ 45
- 2
auth/types.go View File

@ -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()

Loading…
Cancel
Save