Add an endpoint to validate and register profiles.
Add a newProfileRequest object that defines the user-specified properties of a
new Profile.
Add a helper that validates a newProfileRequest and modifies it for
sanitization, mostly just removing leading and trailing whitespace.
Add MaxNameLength, MaxUsernameLength, and MaxEmailLength constants to hold the
maximum length for those properties.
Add errors to be returned when a users attempts to log in with a profile that is
compromised or locked.
Add the bare bones of a CreateProfileHandler that validates a profile
registration request adn uses it to create a Profile and at least one Login.
Create a requestError struct that is used for returning API errors, along with
constants for the slugs we'll use to signal those errors.
13 "code.secondbit.org/uuid"
15 "github.com/gorilla/mux"
19 authCookieName = "auth"
20 defaultAuthorizationCodeExpiration = 600 // default to ten minute grant expirations
21 getAuthorizationCodeTemplateName = "get_grant"
25 // ErrNoAuth is returned when an Authorization header is not present or is empty.
26 ErrNoAuth = errors.New("no authorization header supplied")
27 // ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format.
28 ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format")
29 // ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values.
30 ErrIncorrectAuth = errors.New("invalid authentication")
31 // ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used.
32 ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme")
33 // ErrNoSession is returned when no session ID is passed with a request.
34 ErrNoSession = errors.New("no session ID found")
36 grantTypesMap = grantTypes{types: map[string]GrantType{}}
39 type grantTypes struct {
40 types map[string]GrantType
44 // GrantType defines a set of functions and metadata around a specific authorization grant strategy.
46 // The Validate function will be called when requests are made that match the GrantType, and should write any
47 // errors to the ResponseWriter. It is responsible for determining if the grant is valid and a token should be issued.
48 // It must return the scope the grant was for and the ID of the Profile that issued the grant, as well as if the grant
49 // is valid or not. It must not be nil.
51 // The Invalidate function will be called when the grant has successfully generated a token and the token has successfully
52 // been conveyed to the user. The Invalidate function is always called asynchronously, outside the request. It should take
53 // care of marking the grant as used, if the GrantType requires grants to be one-time only grants. The Invalidate function
56 // IssuesRefresh determines whether the GrantType should yield a refresh token as well as an access token. If true, the client
57 // will be issued a refresh token.
59 // The ReturnToken will be called when a token is created and needs to be returned to the client. If it returns true, the token
60 // was successfully returned and the Invalidate function will be called asynchronously.
61 type GrantType struct {
62 Validate func(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool)
63 Invalidate func(r *http.Request, context Context) error
64 ReturnToken func(w http.ResponseWriter, r *http.Request, token Token, context Context) bool
68 type tokenResponse struct {
69 AccessToken string `json:"access_token"`
70 TokenType string `json:"token_type,omitempty"`
71 ExpiresIn int32 `json:"expires_in,omitempty"`
72 RefreshToken string `json:"refresh_token,omitempty"`
75 type errorResponse struct {
76 Error string `json:"error"`
77 Description string `json:"error_description,omitempty"`
78 URI string `json:"error_uri,omitempty"`
81 // RegisterGrantType associates a string with a GrantType. When the string is used as the value for "grant_type" when obtaining
82 // an access token, the associated GrantType's properties will be used.
84 // RegisterGrantType should be called in the `init()` function of packages, much like database/sql registers drivers. It will panic
85 // if a GrantType tries to register under a string that already has a GrantType registered for it.
86 func RegisterGrantType(name string, g GrantType) {
88 defer grantTypesMap.Unlock()
89 if _, ok := grantTypesMap.types[name]; ok {
90 panic("Duplicate registration of grant_type " + name)
92 grantTypesMap.types[name] = g
95 func findGrantType(name string) (GrantType, bool) {
97 defer grantTypesMap.RUnlock()
98 t, ok := grantTypesMap.types[name]
102 func renderJSONError(enc *json.Encoder, errorType string) {
103 err := enc.Encode(errorResponse{
111 // RenderJSONToken is an implementation of the ReturnToken function for GrantTypes. It returns the token using JSON
112 // according to the spec. See RFC 6479, Section 4.1.4.
113 func RenderJSONToken(w http.ResponseWriter, r *http.Request, token Token, context Context) bool {
114 enc := json.NewEncoder(w)
115 resp := tokenResponse{
116 AccessToken: token.AccessToken,
117 RefreshToken: token.RefreshToken,
118 ExpiresIn: token.ExpiresIn,
119 TokenType: token.TokenType,
121 err := enc.Encode(resp)
129 func wrap(context Context, f func(w http.ResponseWriter, r *http.Request, context Context)) http.Handler {
130 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
135 // RegisterOAuth2 adds handlers to the passed router to handle the OAuth2 endpoints.
136 func RegisterOAuth2(r *mux.Router, context Context) {
137 r.Handle("/authorize", wrap(context, GetAuthorizationCodeHandler))
138 r.Handle("/token", wrap(context, GetTokenHandler))
141 // GetAuthorizationCodeHandler presents and processes the page for asking a user to grant access
142 // to their data. See RFC 6749, Section 4.1.
143 func GetAuthorizationCodeHandler(w http.ResponseWriter, r *http.Request, context Context) {
144 session, err := checkCookie(r, context)
146 if err == ErrNoSession || err == ErrInvalidSession {
147 redir := buildLoginRedirect(r, context)
149 log.Println("No login URL configured.")
150 w.WriteHeader(http.StatusInternalServerError)
151 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
152 "internal_error": template.HTML("Missing login URL."),
156 http.Redirect(w, r, redir, http.StatusFound)
159 log.Println(err.Error())
160 w.WriteHeader(http.StatusInternalServerError)
161 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
162 "internal_error": template.HTML(err.Error()),
166 if r.URL.Query().Get("client_id") == "" {
167 w.WriteHeader(http.StatusBadRequest)
168 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
169 "error": template.HTML("Client ID must be specified in the request."),
173 clientID, err := uuid.Parse(r.URL.Query().Get("client_id"))
175 w.WriteHeader(http.StatusBadRequest)
176 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
177 "error": template.HTML("client_id is not a valid Client ID."),
181 redirectURI := r.URL.Query().Get("redirect_uri")
182 redirectURL, err := url.Parse(redirectURI)
184 w.WriteHeader(http.StatusBadRequest)
185 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
186 "error": template.HTML("The redirect_uri specified is not valid."),
190 client, err := context.GetClient(clientID)
192 if err == ErrClientNotFound {
193 w.WriteHeader(http.StatusBadRequest)
194 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
195 "error": template.HTML("The specified Client couldn’t be found."),
198 log.Println(err.Error())
199 w.WriteHeader(http.StatusInternalServerError)
200 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
201 "internal_error": template.HTML(err.Error()),
206 // TODO(paddy): checking if the redirect URI is valid should be a helper function
207 // whether a redirect URI is valid or not depends on the number of endpoints
208 // the client has registered
209 numEndpoints, err := context.CountEndpoints(clientID)
211 log.Println(err.Error())
212 w.WriteHeader(http.StatusInternalServerError)
213 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
214 "internal_error": template.HTML(err.Error()),
219 if redirectURI != "" {
220 // BUG(paddy): We really should normalize URIs before trying to compare them.
221 validURI, err = context.CheckEndpoint(clientID, redirectURI)
223 log.Println(err.Error())
224 w.WriteHeader(http.StatusInternalServerError)
225 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
226 "internal_error": template.HTML(err.Error()),
230 } else if redirectURI == "" && numEndpoints == 1 {
231 // if we don't specify the endpoint and there's only one endpoint, the
232 // request is valid, and we're redirecting to that one endpoint
234 endpoints, err := context.ListEndpoints(clientID, 1, 0)
236 log.Println(err.Error())
237 w.WriteHeader(http.StatusInternalServerError)
238 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
239 "internal_error": template.HTML(err.Error()),
243 if len(endpoints) != 1 {
246 u := endpoints[0].URI // Copy it here to avoid grabbing a pointer to the memstore
247 redirectURI = u.String()
254 w.WriteHeader(http.StatusBadRequest)
255 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
256 "error": template.HTML("The redirect_uri specified is not valid."),
260 scope := r.URL.Query().Get("scope")
261 state := r.URL.Query().Get("state")
262 if r.URL.Query().Get("response_type") != "code" {
263 q := redirectURL.Query()
264 q.Add("error", "invalid_request")
265 q.Add("state", state)
266 redirectURL.RawQuery = q.Encode()
267 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
270 if r.Method == "POST" {
271 // BUG(paddy): We need to implement CSRF protection when obtaining a grant code.
272 if r.PostFormValue("grant") == "approved" {
273 code := uuid.NewID().String()
274 authCode := AuthorizationCode{
277 ExpiresIn: defaultAuthorizationCodeExpiration,
280 RedirectURI: r.URL.Query().Get("redirect_uri"),
282 ProfileID: session.ProfileID,
284 err := context.SaveAuthorizationCode(authCode)
286 q := redirectURL.Query()
287 q.Add("error", "server_error")
288 q.Add("state", state)
289 redirectURL.RawQuery = q.Encode()
290 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
293 q := redirectURL.Query()
295 q.Add("state", state)
296 redirectURL.RawQuery = q.Encode()
297 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
300 q := redirectURL.Query()
301 q.Add("error", "access_denied")
302 q.Add("state", state)
303 redirectURL.RawQuery = q.Encode()
304 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
307 profile, err := context.GetProfileByID(session.ProfileID)
309 q := redirectURL.Query()
310 q.Add("error", "server_error")
311 q.Add("state", state)
312 redirectURL.RawQuery = q.Encode()
313 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
316 w.WriteHeader(http.StatusOK)
317 context.Render(w, getAuthorizationCodeTemplateName, map[string]interface{}{
319 "redirectURL": redirectURL,
325 // GetTokenHandler allows a client to exchange an authorization grant for an
326 // access token. See RFC 6749 Section 4.1.3.
327 func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) {
328 enc := json.NewEncoder(w)
329 grantType := r.PostFormValue("grant_type")
330 gt, ok := findGrantType(grantType)
332 w.WriteHeader(http.StatusBadRequest)
333 renderJSONError(enc, "invalid_request")
336 scope, profileID, valid := gt.Validate(w, r, context)
341 if gt.IssuesRefresh {
342 refresh = uuid.NewID().String()
345 AccessToken: uuid.NewID().String(),
346 RefreshToken: refresh,
348 ExpiresIn: defaultTokenExpiration,
349 RefreshExpiresIn: defaultRefreshTokenExpiration,
352 ProfileID: profileID,
354 err := context.SaveToken(token)
356 w.WriteHeader(http.StatusInternalServerError)
357 renderJSONError(enc, "server_error")
360 if gt.ReturnToken(w, r, token, context) && gt.Invalidate != nil {
361 go gt.Invalidate(r, context)
365 // TODO(paddy): exchange user credentials for access token
366 // TODO(paddy): exchange client credentials for access token
367 // TODO(paddy): implicit grant for access token
368 // TODO(paddy): exchange refresh token for access token