auth

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

20:0ccace901036 Go to Latest

auth/session.go

Check session before rendering confirmation page. The confirmation page should not be rendered until the session is set. Check the request method, then check the session, then finally render the confirmation page, should we need to.

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 }