auth

Paddy 2015-04-11 Parent:026adb0c7fc4 Child:6f473576c6ae

159:cf6c1f05eb21 Go to Latest

auth/session.go

Enable terminating sessions through the API. Add a terminateSession method to the sessionStore that sets the Active property of the Session to false. Create a Context.TerminateSession wrapper for the terminateSession method on the sessionStore. Add a Sessions property to our response type so we can return a []Session in API responses. Use the URL-safe encoding when base64 encoding our session ID and CSRFToken, so the ID can be passed in the URL and so our encodings are consistent. Add a TerminateSessionHandler function that will extract a Session ID from the request URL, authenticate the user, check that the authenticated user owns the session in question, and terminate the session. Add implementations for our new terminateSession method for the memstore and postgres types. Test both the memstore and postgres implementation of our terminateSession helper in session_test.go.

History
     1.1 --- a/session.go	Sat Apr 11 14:39:51 2015 -0400
     1.2 +++ b/session.go	Sat Apr 11 15:37:41 2015 -0400
     1.3 @@ -91,6 +91,7 @@
     1.4  type sessionStore interface {
     1.5  	createSession(session Session) error
     1.6  	getSession(id string) (Session, error)
     1.7 +	terminateSession(id string) error
     1.8  	removeSession(id string) error
     1.9  	listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error)
    1.10  }
    1.11 @@ -114,6 +115,18 @@
    1.12  	return m.sessions[id], nil
    1.13  }
    1.14  
    1.15 +func (m *memstore) terminateSession(id string) error {
    1.16 +	m.sessionLock.RLock()
    1.17 +	defer m.sessionLock.RUnlock()
    1.18 +	sess, ok := m.sessions[id]
    1.19 +	if !ok {
    1.20 +		return ErrSessionNotFound
    1.21 +	}
    1.22 +	sess.Active = false
    1.23 +	m.sessions[id] = sess
    1.24 +	return nil
    1.25 +}
    1.26 +
    1.27  func (m *memstore) removeSession(id string) error {
    1.28  	m.sessionLock.Lock()
    1.29  	defer m.sessionLock.Unlock()
    1.30 @@ -150,7 +163,7 @@
    1.31  func RegisterSessionHandlers(r *mux.Router, context Context) {
    1.32  	r.Handle("/login", wrap(context, CreateSessionHandler))
    1.33  	// BUG(paddy): We need to implement a handler for listing sessions active on a profile.
    1.34 -	// BUG(paddy): We need to implement a handler for terminating sessions.
    1.35 +	r.Handle("/sessions/{id}", wrap(context, TerminateSessionHandler)).Methods("OPTIONS", "DELETE")
    1.36  }
    1.37  
    1.38  func checkCSRF(r *http.Request, s Session) error {
    1.39 @@ -280,7 +293,7 @@
    1.40  				return
    1.41  			}
    1.42  			session := Session{
    1.43 -				ID:        base64.StdEncoding.EncodeToString(sessionID),
    1.44 +				ID:        base64.URLEncoding.EncodeToString(sessionID),
    1.45  				IP:        ip,
    1.46  				UserAgent: r.UserAgent(),
    1.47  				ProfileID: profile.ID,
    1.48 @@ -288,7 +301,7 @@
    1.49  				Created:   time.Now(),
    1.50  				Expires:   time.Now().Add(time.Hour),
    1.51  				Active:    true,
    1.52 -				CSRFToken: base64.StdEncoding.EncodeToString(csrfToken),
    1.53 +				CSRFToken: base64.URLEncoding.EncodeToString(csrfToken),
    1.54  			}
    1.55  			err = context.CreateSession(session)
    1.56  			if err != nil {
    1.57 @@ -324,6 +337,64 @@
    1.58  	})
    1.59  }
    1.60  
    1.61 +// TerminateSessionHandler allows the user to end their session before it expires.
    1.62 +func TerminateSessionHandler(w http.ResponseWriter, r *http.Request, context Context) {
    1.63 +	var errors []requestError
    1.64 +	vars := mux.Vars(r)
    1.65 +	if vars["id"] == "" {
    1.66 +		errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
    1.67 +		encode(w, r, http.StatusBadRequest, response{Errors: errors})
    1.68 +		return
    1.69 +	}
    1.70 +	id := vars["id"]
    1.71 +	un, pw, ok := r.BasicAuth()
    1.72 +	if !ok {
    1.73 +		errors = append(errors, requestError{Slug: requestErrAccessDenied})
    1.74 +		encode(w, r, http.StatusUnauthorized, response{Errors: errors})
    1.75 +		return
    1.76 +	}
    1.77 +	profile, err := authenticate(un, pw, context)
    1.78 +	if err != nil {
    1.79 +		if isAuthError(err) {
    1.80 +			errors = append(errors, requestError{Slug: requestErrAccessDenied})
    1.81 +			encode(w, r, http.StatusForbidden, response{Errors: errors})
    1.82 +			return
    1.83 +		}
    1.84 +		errors = append(errors, requestError{Slug: requestErrActOfGod})
    1.85 +		encode(w, r, http.StatusInternalServerError, response{Errors: errors})
    1.86 +		return
    1.87 +	}
    1.88 +	session, err := context.GetSession(id)
    1.89 +	if err != nil {
    1.90 +		if err == ErrSessionNotFound {
    1.91 +			errors = append(errors, requestError{Slug: requestErrNotFound, Param: "id"})
    1.92 +			encode(w, r, http.StatusNotFound, response{Errors: errors})
    1.93 +			return
    1.94 +		}
    1.95 +		errors = append(errors, requestError{Slug: requestErrActOfGod})
    1.96 +		encode(w, r, http.StatusInternalServerError, response{Errors: errors})
    1.97 +		return
    1.98 +	}
    1.99 +	if !session.ProfileID.Equal(profile.ID) {
   1.100 +		errors = append(errors, requestError{Slug: requestErrAccessDenied, Param: "id"})
   1.101 +		encode(w, r, http.StatusForbidden, response{Errors: errors})
   1.102 +		return
   1.103 +	}
   1.104 +	err = context.TerminateSession(id)
   1.105 +	if err != nil {
   1.106 +		if err == ErrSessionNotFound {
   1.107 +			errors = append(errors, requestError{Slug: requestErrNotFound, Param: "id"})
   1.108 +			encode(w, r, http.StatusNotFound, response{Errors: errors})
   1.109 +			return
   1.110 +		}
   1.111 +		errors = append(errors, requestError{Slug: requestErrActOfGod})
   1.112 +		encode(w, r, http.StatusInternalServerError, response{Errors: errors})
   1.113 +		return
   1.114 +	}
   1.115 +	session.Active = false
   1.116 +	encode(w, r, http.StatusOK, response{Sessions: []Session{session}, Errors: errors})
   1.117 +}
   1.118 +
   1.119  func credentialsValidate(w http.ResponseWriter, r *http.Request, context Context) (scopes []string, profileID uuid.ID, valid bool) {
   1.120  	enc := json.NewEncoder(w)
   1.121  	username := r.PostFormValue("username")