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.
10 "code.secondbit.org/uuid"
14 // ErrNoClientStore is returned when a Context tries to act on a clientStore without setting one first.
15 ErrNoClientStore = errors.New("no clientStore was specified for the Context")
16 // ErrClientNotFound is returned when a Client is requested but not found in a clientStore.
17 ErrClientNotFound = errors.New("client not found in clientStore")
18 // ErrClientAlreadyExists is returned when a Client is added to a clientStore, but another Client with
19 // the same ID already exists in the clientStore.
20 ErrClientAlreadyExists = errors.New("client already exists in clientStore")
22 // ErrEmptyChange is returned when a Change has all its properties set to nil.
23 ErrEmptyChange = errors.New("change must have at least one property set")
24 // ErrClientNameTooShort is returned when a Client's Name property is too short.
25 ErrClientNameTooShort = errors.New("client name must be at least 2 characters")
26 // ErrClientNameTooLong is returned when a Client's Name property is too long.
27 ErrClientNameTooLong = errors.New("client name must be at most 32 characters")
28 // ErrClientLogoTooLong is returned when a Client's Logo property is too long.
29 ErrClientLogoTooLong = errors.New("client logo must be at most 1024 characters")
30 // ErrClientLogoNotURL is returned when a Client's Logo property is not a valid absolute URL.
31 ErrClientLogoNotURL = errors.New("client logo must be a valid absolute URL")
32 // ErrClientWebsiteTooLong is returned when a Client's Website property is too long.
33 ErrClientWebsiteTooLong = errors.New("client website must be at most 1024 characters")
34 // ErrClientWebsiteNotURL is returned when a Client's Website property is not a valid absolute URL.
35 ErrClientWebsiteNotURL = errors.New("client website must be a valid absolute URL")
38 // Client represents a client that grants access
39 // to the auth server, exchanging grants for tokens,
40 // and tokens for access.
51 // ApplyChange applies the properties of the passed
52 // ClientChange to the Client object it is called on.
53 func (c *Client) ApplyChange(change ClientChange) {
54 if change.Secret != nil {
55 c.Secret = *change.Secret
57 if change.OwnerID != nil {
58 c.OwnerID = change.OwnerID
60 if change.Name != nil {
63 if change.Logo != nil {
66 if change.Website != nil {
67 c.Website = *change.Website
71 // ClientChange represents a bundle of options for
72 // updating a Client's mutable data.
73 type ClientChange struct {
81 // Validate checks the ClientChange it is called on
82 // and asserts its internal validity, or lack thereof.
83 func (c ClientChange) Validate() error {
84 if c.Secret == nil && c.OwnerID == nil && c.Name == nil && c.Logo == nil && c.Website == nil {
87 if c.Name != nil && len(*c.Name) < 2 {
88 return ErrClientNameTooShort
90 if c.Name != nil && len(*c.Name) > 32 {
91 return ErrClientNameTooLong
93 if c.Logo != nil && *c.Logo != "" {
94 if len(*c.Logo) > 1024 {
95 return ErrClientLogoTooLong
97 u, err := url.Parse(*c.Logo)
98 if err != nil || !u.IsAbs() {
99 return ErrClientLogoNotURL
102 if c.Website != nil && *c.Website != "" {
103 if len(*c.Website) > 140 {
104 return ErrClientWebsiteTooLong
106 u, err := url.Parse(*c.Website)
107 if err != nil || !u.IsAbs() {
108 return ErrClientWebsiteNotURL
114 func verifyClient(w http.ResponseWriter, r *http.Request, allowPublic bool, context Context) (uuid.ID, bool) {
115 enc := json.NewEncoder(w)
116 clientIDStr, clientSecret, fromAuthHeader := r.BasicAuth()
119 w.WriteHeader(http.StatusBadRequest)
120 renderJSONError(enc, "unauthorized_client")
123 clientIDStr = r.PostFormValue("client_id")
125 clientID, err := uuid.Parse(clientIDStr)
127 w.WriteHeader(http.StatusUnauthorized)
129 w.Header().Set("WWW-Authenticate", "Basic")
131 renderJSONError(enc, "invalid_client")
134 client, err := context.GetClient(clientID)
135 if err == ErrClientNotFound {
136 w.WriteHeader(http.StatusUnauthorized)
138 w.Header().Set("WWW-Authenticate", "Basic")
140 renderJSONError(enc, "invalid_client")
142 } else if err != nil {
143 w.WriteHeader(http.StatusInternalServerError)
144 renderJSONError(enc, "server_error")
147 if client.Secret != clientSecret {
148 w.WriteHeader(http.StatusUnauthorized)
150 w.Header().Set("WWW-Authenticate", "Basic")
152 renderJSONError(enc, "invalid_client")
155 return clientID, true
158 // Endpoint represents a single URI that a Client
159 // controls. Users will be redirected to these URIs
160 // following successful authorization grants and
161 // exchanges for access tokens.
162 type Endpoint struct {
169 type sortedEndpoints []Endpoint
171 func (s sortedEndpoints) Len() int {
175 func (s sortedEndpoints) Less(i, j int) bool {
176 return s[i].Added.Before(s[j].Added)
179 func (s sortedEndpoints) Swap(i, j int) {
180 s[i], s[j] = s[j], s[i]
183 type clientStore interface {
184 getClient(id uuid.ID) (Client, error)
185 saveClient(client Client) error
186 updateClient(id uuid.ID, change ClientChange) error
187 deleteClient(id uuid.ID) error
188 listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error)
190 addEndpoint(client uuid.ID, endpoint Endpoint) error
191 removeEndpoint(client, endpoint uuid.ID) error
192 checkEndpoint(client uuid.ID, endpoint string) (bool, error)
193 listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error)
194 countEndpoints(client uuid.ID) (int64, error)
197 func (m *memstore) getClient(id uuid.ID) (Client, error) {
199 defer m.clientLock.RUnlock()
200 c, ok := m.clients[id.String()]
202 return Client{}, ErrClientNotFound
207 func (m *memstore) saveClient(client Client) error {
209 defer m.clientLock.Unlock()
210 if _, ok := m.clients[client.ID.String()]; ok {
211 return ErrClientAlreadyExists
213 m.clients[client.ID.String()] = client
214 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()], client.ID)
218 func (m *memstore) updateClient(id uuid.ID, change ClientChange) error {
220 defer m.clientLock.Unlock()
221 c, ok := m.clients[id.String()]
223 return ErrClientNotFound
225 c.ApplyChange(change)
226 m.clients[id.String()] = c
230 func (m *memstore) deleteClient(id uuid.ID) error {
231 client, err := m.getClient(id)
236 defer m.clientLock.Unlock()
237 delete(m.clients, id.String())
239 for p, item := range m.profileClientLookup[client.OwnerID.String()] {
246 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()][:pos], m.profileClientLookup[client.OwnerID.String()][pos+1:]...)
251 func (m *memstore) listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
252 ids := m.lookupClientsByProfileID(ownerID.String())
253 if len(ids) > num+offset {
254 ids = ids[offset : num+offset]
255 } else if len(ids) > offset {
258 return []Client{}, nil
260 clients := []Client{}
261 for _, id := range ids {
262 client, err := m.getClient(id)
264 return []Client{}, err
266 clients = append(clients, client)
271 func (m *memstore) addEndpoint(client uuid.ID, endpoint Endpoint) error {
272 m.endpointLock.Lock()
273 defer m.endpointLock.Unlock()
274 m.endpoints[client.String()] = append(m.endpoints[client.String()], endpoint)
278 func (m *memstore) removeEndpoint(client, endpoint uuid.ID) error {
279 m.endpointLock.Lock()
280 defer m.endpointLock.Unlock()
282 for p, item := range m.endpoints[client.String()] {
283 if item.ID.Equal(endpoint) {
289 m.endpoints[client.String()] = append(m.endpoints[client.String()][:pos], m.endpoints[client.String()][pos+1:]...)
294 func (m *memstore) checkEndpoint(client uuid.ID, endpoint string) (bool, error) {
295 m.endpointLock.RLock()
296 defer m.endpointLock.RUnlock()
297 for _, candidate := range m.endpoints[client.String()] {
298 if endpoint == candidate.URI.String() {
305 func (m *memstore) listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error) {
306 m.endpointLock.RLock()
307 defer m.endpointLock.RUnlock()
308 return m.endpoints[client.String()], nil
311 func (m *memstore) countEndpoints(client uuid.ID) (int64, error) {
312 m.endpointLock.RLock()
313 defer m.endpointLock.RUnlock()
314 return int64(len(m.endpoints[client.String()])), nil