auth
auth/request.go
Add support for registering Clients. Add an API endpoint to register Clients, which was the last step necessary before the OAuth2 integration could be tried out.
1 package auth
3 import (
4 "encoding/json"
5 "log"
6 "net/http"
8 "bitbucket.org/ww/goautoneg"
9 )
11 const (
12 requestErrAccessDenied = "access_denied"
13 requestErrInsufficient = "insufficient"
14 requestErrOverflow = "overflow"
15 requestErrInvalidValue = "invalid_value"
16 requestErrInvalidFormat = "invalid_format"
17 requestErrMissing = "missing"
18 requestErrNotFound = "not_found"
19 requestErrConflict = "conflict"
20 requestErrActOfGod = "act_of_god"
21 )
23 var (
24 actOfGodResponse = response{Errors: []requestError{requestError{Slug: requestErrActOfGod}}}
25 invalidFormatResponse = response{Errors: []requestError{requestError{Slug: requestErrInvalidFormat, Field: "/"}}}
27 encoders = []string{"application/json"}
28 )
30 type response struct {
31 Errors []requestError `json:"errors,omitempty"`
32 Logins []Login `json:"logins,omitempty"`
33 Profiles []Profile `json:"profiles,omitempty"`
34 Clients []Client `json:"clients,omitempty"`
35 Endpoints []Endpoint `json:"endpoints,omitempty"`
36 }
38 type requestError struct {
39 Slug string `json:"error,omitempty"`
40 Field string `json:"field,omitempty"`
41 Param string `json:"param,omitempty"`
42 Header string `json:"header,omitempty"`
43 }
45 func negotiate(h http.Handler) http.Handler {
46 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
47 contentType := goautoneg.Negotiate(r.Header.Get("Accept"), encoders)
48 if contentType == "" {
49 w.WriteHeader(http.StatusNotAcceptable)
50 log.Println("Unsupported Accept header:", r.Header.Get("Accept"))
51 w.Write([]byte("Unsupported content type requested: " + r.Header.Get("Accept")))
52 return
53 }
54 h.ServeHTTP(w, r)
55 })
56 }
58 func encode(w http.ResponseWriter, r *http.Request, status int, resp response) {
59 contentType := goautoneg.Negotiate(r.Header.Get("Accept"), encoders)
60 w.Header().Set("content-type", contentType)
61 w.WriteHeader(status)
62 var err error
63 switch contentType {
64 case "application/json":
65 enc := json.NewEncoder(w)
66 err = enc.Encode(resp)
67 }
68 if err != nil {
69 log.Println(err)
70 }
71 }
73 func wrap(context Context, f func(w http.ResponseWriter, r *http.Request, context Context)) http.Handler {
74 return negotiate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
75 f(w, r, context)
76 }))
77 }