auth

Paddy 2014-08-16 Parent:9a1e62c24903 Child:51700827b6ee

19:9fe684b33b3d Go to Latest

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.

History
1 package auth
3 import (
4 "errors"
5 "net/http"
6 "time"
8 "secondbit.org/uuid"
9 )
11 const sessionCookie = "session"
13 var (
14 ErrSessionNotFound = errors.New("Session not found.")
15 )
17 type Session struct {
18 Token string
19 User uuid.ID
20 Expires time.Time
21 Created time.Time
22 IP string
23 }
25 func validateSession(r *http.Request, c Context) error {
26 cookie, err := r.Cookie(sessionCookie)
27 if err == http.ErrNoCookie {
28 return ErrSessionNotFound
29 }
30 _, err = c.Sessions.GetSession(cookie.Value)
31 return err
32 }
34 func HandleLoginRequest(w http.ResponseWriter, r *http.Request, ctx Context) {
35 if r.Method == "GET" {
36 ctx.RenderLogin(w, r)
37 return
38 } else if r.Method != "POST" {
39 // TODO: return bad method error
40 return
41 }
43 if r.FormValue("username") == "" || r.FormValue("password") == "" {
44 // TODO: return unauthenticated error
45 return
46 }
47 id, err := ctx.Profiles.GetProfile(r.FormValue("username"), r.FormValue("password"))
48 if err != nil {
49 if err == ErrProfileNotFound {
50 // TODO: return unauthenticated error
51 return
52 }
53 // TODO: return internal server error
54 return
55 }
56 session := Session{
57 Token: newToken(),
58 User: id,
59 Expires: time.Now().Add(ctx.Config.SessionLength),
60 Created: time.Now(),
61 IP: r.Header.Get(ctx.Config.RequestIPHeader),
62 }
63 err = ctx.Sessions.SetSession(session)
64 if err != nil {
65 // TODO: return internal server error
66 return
67 }
68 http.SetCookie(w, &http.Cookie{
69 Name: sessionCookie,
70 Value: session.Token,
71 Expires: session.Expires,
72 Secure: true,
73 HttpOnly: true,
74 })
75 // TODO: redirect
76 }