auth
auth/session.go
Implement session management and move login. Add a session store interface to validate and retrieve data about sessions. Implement session management in endpoints that need session support. Move the login functionality from inlined into the OAuth flow into its own handler, that the OAuth flow will redirect to. The login functionality should take a redirect URL parameter to return to the OAuth flow when login is completed.
1.1 --- a/session.go Sat Aug 16 18:05:55 2014 -0400 1.2 +++ b/session.go Sat Aug 16 20:02:52 2014 -0400 1.3 @@ -1,8 +1,76 @@ 1.4 package auth 1.5 1.6 -import "net/http" 1.7 +import ( 1.8 + "errors" 1.9 + "net/http" 1.10 + "time" 1.11 + 1.12 + "secondbit.org/uuid" 1.13 +) 1.14 + 1.15 +const sessionCookie = "session" 1.16 + 1.17 +var ( 1.18 + ErrSessionNotFound = errors.New("Session not found.") 1.19 +) 1.20 + 1.21 +type Session struct { 1.22 + Token string 1.23 + User uuid.ID 1.24 + Expires time.Time 1.25 + Created time.Time 1.26 + IP string 1.27 +} 1.28 1.29 func validateSession(r *http.Request, c Context) error { 1.30 - // TODO: return an error if the user does not have a valid session 1.31 - return nil 1.32 + cookie, err := r.Cookie(sessionCookie) 1.33 + if err == http.ErrNoCookie { 1.34 + return ErrSessionNotFound 1.35 + } 1.36 + _, err = c.Sessions.GetSession(cookie.Value) 1.37 + return err 1.38 } 1.39 + 1.40 +func HandleLoginRequest(w http.ResponseWriter, r *http.Request, ctx Context) { 1.41 + if r.Method == "GET" { 1.42 + ctx.RenderLogin(w, r) 1.43 + return 1.44 + } else if r.Method != "POST" { 1.45 + // TODO: return bad method error 1.46 + return 1.47 + } 1.48 + 1.49 + if r.FormValue("username") == "" || r.FormValue("password") == "" { 1.50 + // TODO: return unauthenticated error 1.51 + return 1.52 + } 1.53 + id, err := ctx.Profiles.GetProfile(r.FormValue("username"), r.FormValue("password")) 1.54 + if err != nil { 1.55 + if err == ErrProfileNotFound { 1.56 + // TODO: return unauthenticated error 1.57 + return 1.58 + } 1.59 + // TODO: return internal server error 1.60 + return 1.61 + } 1.62 + session := Session{ 1.63 + Token: newToken(), 1.64 + User: id, 1.65 + Expires: time.Now().Add(ctx.Config.SessionLength), 1.66 + Created: time.Now(), 1.67 + IP: r.Header.Get(ctx.Config.RequestIPHeader), 1.68 + } 1.69 + err = ctx.Sessions.SetSession(session) 1.70 + if err != nil { 1.71 + // TODO: return internal server error 1.72 + return 1.73 + } 1.74 + http.SetCookie(w, &http.Cookie{ 1.75 + Name: sessionCookie, 1.76 + Value: session.Token, 1.77 + Expires: session.Expires, 1.78 + Secure: true, 1.79 + HttpOnly: true, 1.80 + }) 1.81 + // TODO: redirect 1.82 +}