auth

Paddy 2015-01-18 Parent:c03b5eb3179e Child:118a69954621

119:3ec7134fa211 Go to Latest

auth/session.go

Exchange resource owner credentials for access token. Well, that was easy.

History
     1.1 --- a/session.go	Sun Jan 18 01:54:11 2015 -0500
     1.2 +++ b/session.go	Sun Jan 18 01:54:53 2015 -0500
     1.3 @@ -3,6 +3,7 @@
     1.4  import (
     1.5  	"crypto/sha256"
     1.6  	"encoding/hex"
     1.7 +	"encoding/json"
     1.8  	"errors"
     1.9  	"log"
    1.10  	"net/http"
    1.11 @@ -18,6 +19,15 @@
    1.12  	loginTemplateName = "login"
    1.13  )
    1.14  
    1.15 +func init() {
    1.16 +	RegisterGrantType("password", GrantType{
    1.17 +		Validate:      credentialsValidate,
    1.18 +		Invalidate:    nil,
    1.19 +		IssuesRefresh: true,
    1.20 +		ReturnToken:   RenderJSONToken,
    1.21 +	})
    1.22 +}
    1.23 +
    1.24  var (
    1.25  	// ErrNoSessionStore is returned when a Context tries to act on a sessionStore without setting on first.
    1.26  	ErrNoSessionStore = errors.New("no sessionStore was specified for the Context")
    1.27 @@ -270,3 +280,24 @@
    1.28  		"errors": errors,
    1.29  	})
    1.30  }
    1.31 +
    1.32 +func credentialsValidate(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool) {
    1.33 +	enc := json.NewEncoder(w)
    1.34 +	username := r.PostFormValue("username")
    1.35 +	password := r.PostFormValue("password")
    1.36 +	scope = r.PostFormValue("scope")
    1.37 +	profile, err := authenticate(username, password, context)
    1.38 +	if err != nil {
    1.39 +		if err == ErrIncorrectAuth || err == ErrProfileCompromised || err == ErrProfileLocked {
    1.40 +			w.WriteHeader(http.StatusBadRequest)
    1.41 +			renderJSONError(enc, "invalid_grant")
    1.42 +			return
    1.43 +		}
    1.44 +		w.WriteHeader(http.StatusInternalServerError)
    1.45 +		w.Write([]byte(err.Error()))
    1.46 +		return
    1.47 +	}
    1.48 +	profileID = profile.ID
    1.49 +	valid = true
    1.50 +	return
    1.51 +}