auth

Paddy 2015-04-11 Parent:3223a8e679db Child:849f3820b164

160:48200d8c4036 Go to Latest

auth/profile.go

Start to support deleting profiles through the API. Create a removeLoginsByProfile method on the profileStore, to allow an easy way to bulk-delete logins associated with a Profile after the Profile has been deleted. Create postgres and memstore implementations of the removeLoginsByProfile method. Create a cleanUpAfterProfileDeletion helper method that will clean up the child objects of a Profile (its Sessions, Tokens, Clients, etc.). The intended usage is to call this in a goroutine after a Profile has been deleted, to try and get things back in order. Detect when the UpdateProfileHandler API is used to set the Deleted flag of a Profile to true, and clean up after the Profile when that's the case. Add a DeleteProfileHandler API endpoint that is a shortcut to setting the Deleted flag of a Profile to true and cleaning up after the Profile. The problem with our approach thus far is that some of it is reversible and some is not. If a Profile is maliciously/accidentally deleted, it's simple enough to use the API as a superuser to restore the Profile. But doing that will not (and cannot) restore the Logins associated with that Profile, for example. While it would be nice to add a Deleted flag to our Logins that we could simply toggle, that would wreak havoc with our database constraints and ensuring uniqueness of Login values. I still don't have a solution for this, outside the superuser manually restoring a Login for the Profile, after which the user can authenticate themselves and add more Logins as desired. But there has to be a better way. I suppose since the passphrase is being stored with the Profile and not the Login, we could offer an endpoint that would automate this, but... well, that would be tricky. It would require the user remembering their Profile ID, and let's be honest, nobody's going to remember a UUID. Maybe such an endpoint would help from a customer service standpoint: we identify their Profile manually, then send them to /profiles/ID/restorelogin or something, and that lets them add a Login back to the Profile. I'll figure it out later. For now, we know we at least have enough information to identify a user is who they say they are and resolve the situation manually.

History
1 package auth
3 import (
4 "encoding/json"
5 "errors"
6 "log"
7 "net/http"
8 "regexp"
9 "strings"
10 "time"
12 "code.secondbit.org/uuid.hg"
13 "github.com/gorilla/mux"
14 )
16 const (
17 // MinPassphraseLength is the minimum length, in bytes, of a passphrase, exclusive.
18 MinPassphraseLength = 6
19 // MaxPassphraseLength is the maximum length, in bytes, of a passphrase, exclusive.
20 MaxPassphraseLength = 64
21 // CurPassphraseScheme is the current passphrase scheme. Incrememnt it when we use a different passphrase scheme
22 CurPassphraseScheme = 1
23 // MaxNameLength is the maximum length, in bytes, of a name, exclusive.
24 MaxNameLength = 64
25 // MaxEmailLength is the maximum length, in bytes, of an email address, exclusive.
26 MaxEmailLength = 64
27 )
29 var (
30 // ErrNoProfileStore is returned when a Context tries to act on a profileStore without setting one first.
31 ErrNoProfileStore = errors.New("no profileStore was specified for the Context")
32 // ErrProfileAlreadyExists is returned when a Profile is added to a profileStore, but another Profile with
33 // the same ID already exists in the profileStore.
34 ErrProfileAlreadyExists = errors.New("profile already exists in profileStore")
35 // ErrProfileNotFound is returned when a Profile is requested but not found in the profileStore.
36 ErrProfileNotFound = errors.New("profile not found in profileStore")
37 // ErrLoginAlreadyExists is returned when a Login is added to a profileStore, but another Login with the same
38 // Type and Value already exists in the profileStore.
39 ErrLoginAlreadyExists = errors.New("login already exists in profileStore")
40 // ErrLoginNotFound is returned when a Login is requested but not found in the profileStore.
41 ErrLoginNotFound = errors.New("login not found in profileStore")
43 // ErrMissingPassphrase is returned when a ProfileChange is validated but does not contain a
44 // Passphrase, and requires one.
45 ErrMissingPassphrase = errors.New("missing passphrase")
46 // ErrMissingPassphraseReset is returned when a ProfileChange is validated but does not contain
47 // a PassphraseReset, and requires one.
48 ErrMissingPassphraseReset = errors.New("missing passphrase reset")
49 // ErrMissingPassphraseResetCreated is returned when a ProfileChange is validated but does not
50 // contain a PassphraseResetCreated, and requires one.
51 ErrMissingPassphraseResetCreated = errors.New("missing passphrase reset created timestamp")
52 // ErrPassphraseTooShort is returned when a ProfileChange is validated and contains a Passphrase,
53 // but the Passphrase is shorter than MinPassphraseLength.
54 ErrPassphraseTooShort = errors.New("passphrase too short")
55 // ErrPassphraseTooLong is returned when a ProfileChange is validated and contains a Passphrase,
56 // but the Passphrase is longer than MaxPassphraseLength.
57 ErrPassphraseTooLong = errors.New("passphrase too long")
59 // ErrProfileCompromised is returned when a user tries to log in with a profile that is suspected
60 // of being compromised.
61 ErrProfileCompromised = errors.New("profile compromised")
62 // ErrProfileLocked is returned when a user tries to log in with a profile that is locked for a certain
63 // duration, to prevent brute force attacks.
64 ErrProfileLocked = errors.New("profile locked")
65 )
67 // Profile represents a single user of the service,
68 // including their authentication information.
69 type Profile struct {
70 ID uuid.ID `json:"id,omitempty"`
71 Name string `json:"name,omitempty"`
72 Passphrase string `json:"-"`
73 Iterations int `json:"-"`
74 Salt string `json:"-"`
75 PassphraseScheme int `json:"-"`
76 Compromised bool `json:"-"`
77 LockedUntil time.Time `json:"-"`
78 PassphraseReset string `json:"-"`
79 PassphraseResetCreated time.Time `json:"-"`
80 Created time.Time `json:"created,omitempty"`
81 LastSeen time.Time `json:"last_seen,omitempty"`
82 Deleted bool `json:"deleted,omitempty"`
83 }
85 // ApplyChange applies the properties of the passed ProfileChange
86 // to the Profile it is called on.
87 func (p *Profile) ApplyChange(change ProfileChange) {
88 if change.Name != nil {
89 p.Name = *change.Name
90 }
91 if change.Passphrase != nil {
92 p.Passphrase = *change.Passphrase
93 }
94 if change.Iterations != nil {
95 p.Iterations = *change.Iterations
96 }
97 if change.Salt != nil {
98 p.Salt = *change.Salt
99 }
100 if change.PassphraseScheme != nil {
101 p.PassphraseScheme = *change.PassphraseScheme
102 }
103 if change.Compromised != nil {
104 p.Compromised = *change.Compromised
105 }
106 if change.LockedUntil != nil {
107 p.LockedUntil = *change.LockedUntil
108 }
109 if change.PassphraseReset != nil {
110 p.PassphraseReset = *change.PassphraseReset
111 }
112 if change.PassphraseResetCreated != nil {
113 p.PassphraseResetCreated = *change.PassphraseResetCreated
114 }
115 if change.LastSeen != nil {
116 p.LastSeen = *change.LastSeen
117 }
118 if change.Deleted != nil {
119 p.Deleted = *change.Deleted
120 }
121 }
123 // ApplyBulkChange applies the properties of the passed BulkProfileChange
124 // to the Profile it is called on.
125 func (p *Profile) ApplyBulkChange(change BulkProfileChange) {
126 if change.Compromised != nil {
127 p.Compromised = *change.Compromised
128 }
129 }
131 // ProfileChange represents a single atomic change to a Profile's mutable data.
132 type ProfileChange struct {
133 Name *string
134 Passphrase *string
135 Iterations *int
136 Salt *string
137 PassphraseScheme *int
138 Compromised *bool
139 LockedUntil *time.Time
140 PassphraseReset *string
141 PassphraseResetCreated *time.Time
142 LastSeen *time.Time
143 Deleted *bool
144 }
146 func (c ProfileChange) Empty() bool {
147 return (c.Name == nil && c.Passphrase == nil && c.Iterations == nil && c.Salt == nil && c.PassphraseScheme == nil && c.Compromised == nil && c.LockedUntil == nil && c.PassphraseReset == nil && c.PassphraseResetCreated == nil && c.LastSeen == nil && c.Deleted == nil)
148 }
150 // Validate checks the ProfileChange it is called on
151 // and asserts its internal validity, or lack thereof.
152 // A descriptive error will be returned in the case of
153 // an invalid change.
154 func (c ProfileChange) Validate() error {
155 if c.Empty() {
156 return ErrEmptyChange
157 }
158 if c.PassphraseScheme != nil && c.Passphrase == nil {
159 return ErrMissingPassphrase
160 }
161 if c.PassphraseReset != nil && c.PassphraseResetCreated == nil {
162 return ErrMissingPassphraseResetCreated
163 }
164 if c.PassphraseReset == nil && c.PassphraseResetCreated != nil {
165 return ErrMissingPassphraseReset
166 }
167 if c.Salt != nil && c.Passphrase == nil {
168 return ErrMissingPassphrase
169 }
170 if c.Iterations != nil && c.Passphrase == nil {
171 return ErrMissingPassphrase
172 }
173 return nil
174 }
176 // BulkProfileChange represents a single atomic change to many Profiles' mutable data.
177 // It is a subset of a ProfileChange, as it doesn't make sense to mutate some of the
178 // ProfileChange values across many Profiles all at once.
179 type BulkProfileChange struct {
180 Compromised *bool
181 }
183 func (b BulkProfileChange) Empty() bool {
184 return b.Compromised == nil
185 }
187 // Validate checks the BulkProfileChange it is called on
188 // and asserts its internal validity, or lack thereof.
189 // A descriptive error will be returned in the case of an
190 // invalid change.
191 func (b BulkProfileChange) Validate() error {
192 if b.Empty() {
193 return ErrEmptyChange
194 }
195 return nil
196 }
198 // Login represents a single human-friendly identifier for
199 // a given Profile that can be used to log into that Profile.
200 // Each Profile may only have one Login for each Type.
201 type Login struct {
202 Type string `json:"type,omitempty"`
203 Value string `json:"value,omitempty"`
204 ProfileID uuid.ID `json:"profile_id,omitempty"`
205 Created time.Time `json:"created,omitempty"`
206 LastUsed time.Time `json:"last_used,omitempty"`
207 }
209 type newProfileRequest struct {
210 Email string `json:"email"`
211 Passphrase string `json:"passphrase"`
212 Name string `json:"name"`
213 }
215 func validateNewProfileRequest(req *newProfileRequest) []requestError {
216 errors := []requestError{}
217 req.Name = strings.TrimSpace(req.Name)
218 req.Email = strings.TrimSpace(req.Email)
219 if len(req.Passphrase) < MinPassphraseLength {
220 errors = append(errors, requestError{
221 Slug: requestErrInsufficient,
222 Field: "/passphrase",
223 })
224 }
225 if len(req.Passphrase) > MaxPassphraseLength {
226 errors = append(errors, requestError{
227 Slug: requestErrOverflow,
228 Field: "/passphrase",
229 })
230 }
231 if len(req.Name) > MaxNameLength {
232 errors = append(errors, requestError{
233 Slug: requestErrOverflow,
234 Field: "/name",
235 })
236 }
237 if req.Email == "" {
238 errors = append(errors, requestError{
239 Slug: requestErrMissing,
240 Field: "/email",
241 })
242 }
243 if len(req.Email) > MaxEmailLength {
244 errors = append(errors, requestError{
245 Slug: requestErrOverflow,
246 Field: "/email",
247 })
248 }
249 re := regexp.MustCompile(".+@.+\\..+")
250 if !re.Match([]byte(req.Email)) {
251 errors = append(errors, requestError{
252 Slug: requestErrInvalidFormat,
253 Field: "/email",
254 })
255 }
256 return errors
257 }
259 type profileStore interface {
260 getProfileByID(id uuid.ID) (Profile, error)
261 getProfileByLogin(value string) (Profile, error)
262 saveProfile(profile Profile) error
263 updateProfile(id uuid.ID, change ProfileChange) error
264 updateProfiles(ids []uuid.ID, change BulkProfileChange) error
266 addLogin(login Login) error
267 removeLogin(value string, profile uuid.ID) error
268 removeLoginsByProfile(profile uuid.ID) error
269 recordLoginUse(value string, when time.Time) error
270 listLogins(profile uuid.ID, num, offset int) ([]Login, error)
271 }
273 func (m *memstore) getProfileByID(id uuid.ID) (Profile, error) {
274 m.profileLock.RLock()
275 defer m.profileLock.RUnlock()
276 p, ok := m.profiles[id.String()]
277 if !ok {
278 return Profile{}, ErrProfileNotFound
279 }
280 if p.Deleted {
281 return Profile{}, ErrProfileNotFound
282 }
283 return p, nil
284 }
286 func (m *memstore) getProfileByLogin(value string) (Profile, error) {
287 m.loginLock.RLock()
288 defer m.loginLock.RUnlock()
289 login, ok := m.logins[value]
290 if !ok {
291 return Profile{}, ErrLoginNotFound
292 }
293 m.profileLock.RLock()
294 defer m.profileLock.RUnlock()
295 profile, ok := m.profiles[login.ProfileID.String()]
296 if !ok {
297 return Profile{}, ErrProfileNotFound
298 }
299 if profile.Deleted {
300 return Profile{}, ErrProfileNotFound
301 }
302 return profile, nil
303 }
305 func (m *memstore) saveProfile(profile Profile) error {
306 m.profileLock.Lock()
307 defer m.profileLock.Unlock()
308 _, ok := m.profiles[profile.ID.String()]
309 if ok {
310 return ErrProfileAlreadyExists
311 }
312 m.profiles[profile.ID.String()] = profile
313 return nil
314 }
316 func (m *memstore) updateProfile(id uuid.ID, change ProfileChange) error {
317 m.profileLock.Lock()
318 defer m.profileLock.Unlock()
319 p, ok := m.profiles[id.String()]
320 if !ok {
321 return ErrProfileNotFound
322 }
323 p.ApplyChange(change)
324 m.profiles[id.String()] = p
325 return nil
326 }
328 func (m *memstore) updateProfiles(ids []uuid.ID, change BulkProfileChange) error {
329 m.profileLock.Lock()
330 defer m.profileLock.Unlock()
331 for id, profile := range m.profiles {
332 for _, i := range ids {
333 if id == i.String() {
334 profile.ApplyBulkChange(change)
335 m.profiles[id] = profile
336 break
337 }
338 }
339 }
340 return nil
341 }
343 func (m *memstore) addLogin(login Login) error {
344 m.loginLock.Lock()
345 defer m.loginLock.Unlock()
346 _, ok := m.logins[login.Value]
347 if ok {
348 return ErrLoginAlreadyExists
349 }
350 m.logins[login.Value] = login
351 m.profileLoginLookup[login.ProfileID.String()] = append(m.profileLoginLookup[login.ProfileID.String()], login.Value)
352 return nil
353 }
355 func (m *memstore) removeLogin(value string, profile uuid.ID) error {
356 m.loginLock.Lock()
357 defer m.loginLock.Unlock()
358 l, ok := m.logins[value]
359 if !ok {
360 return ErrLoginNotFound
361 }
362 if !l.ProfileID.Equal(profile) {
363 return ErrLoginNotFound
364 }
365 delete(m.logins, value)
366 pos := -1
367 for p, id := range m.profileLoginLookup[profile.String()] {
368 if id == value {
369 pos = p
370 break
371 }
372 }
373 if pos >= 0 {
374 m.profileLoginLookup[profile.String()] = append(m.profileLoginLookup[profile.String()][:pos], m.profileLoginLookup[profile.String()][pos+1:]...)
375 }
376 return nil
377 }
379 func (m *memstore) removeLoginsByProfile(profile uuid.ID) error {
380 m.loginLock.Lock()
381 defer m.loginLock.Unlock()
382 logins, ok := m.profileLoginLookup[profile.String()]
383 if !ok {
384 return ErrProfileNotFound
385 }
386 delete(m.profileLoginLookup, profile.String())
387 for _, login := range logins {
388 delete(m.logins, login)
389 }
390 return nil
391 }
393 func (m *memstore) recordLoginUse(value string, when time.Time) error {
394 m.loginLock.Lock()
395 defer m.loginLock.Unlock()
396 l, ok := m.logins[value]
397 if !ok {
398 return ErrLoginNotFound
399 }
400 l.LastUsed = when
401 m.logins[value] = l
402 return nil
403 }
405 func (m *memstore) listLogins(profile uuid.ID, num, offset int) ([]Login, error) {
406 m.loginLock.RLock()
407 defer m.loginLock.RUnlock()
408 ids, ok := m.profileLoginLookup[profile.String()]
409 if !ok {
410 return []Login{}, nil
411 }
412 if len(ids) > num+offset {
413 ids = ids[offset : num+offset]
414 } else if len(ids) > offset {
415 ids = ids[offset:]
416 } else {
417 return []Login{}, nil
418 }
419 logins := []Login{}
420 for _, id := range ids {
421 login, ok := m.logins[id]
422 if !ok {
423 continue
424 }
425 logins = append(logins, login)
426 }
427 return logins, nil
428 }
430 func cleanUpAfterProfileDeletion(profile uuid.ID, context Context) {
431 err := context.RemoveLoginsByProfile(profile)
432 if err != nil {
433 log.Printf("Error removing logins from profile %s: %+v\n", profile, err)
434 }
435 // BUG(paddy): need to terminate all sessions associated with the Profile
436 // BUG(paddy): need to invalidate all tokens associated with the Profile
437 // BUG(paddy): need to delete all the grants associated with the Profile
438 }
440 // RegisterProfileHandlers adds handlers to the passed router to handle the profile endpoints, like registration and user retrieval.
441 func RegisterProfileHandlers(r *mux.Router, context Context) {
442 r.Handle("/profiles", wrap(context, CreateProfileHandler)).Methods("POST")
443 // BUG(paddy): We need to implement a handler that will return information about a profile or set of profiles.
444 r.Handle("/profiles/{id}", wrap(context, UpdateProfileHandler)).Methods("PATCH")
445 r.Handle("/profiles/{id}", wrap(context, DeleteProfileHandler)).Methods("DELETE")
446 // BUG(paddy): We need to implement a handler that will add a login to a profile.
447 // BUG(paddy): We need to implement a handler that will remove a login from a profile. What happens to sessions created with that login?
448 // BUG(paddy): We need to implement a handler that will list the logins attached to a profile.
449 }
451 // CreateProfileHandler is an HTTP handler for registering new profiles.
452 func CreateProfileHandler(w http.ResponseWriter, r *http.Request, context Context) {
453 scheme, ok := passphraseSchemes[CurPassphraseScheme]
454 if !ok {
455 log.Printf("Error selecting passphrase scheme #%d\n", CurPassphraseScheme)
456 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
457 return
458 }
459 var req newProfileRequest
460 errors := []requestError{}
461 decoder := json.NewDecoder(r.Body)
462 err := decoder.Decode(&req)
463 if err != nil {
464 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
465 return
466 }
467 errors = append(errors, validateNewProfileRequest(&req)...)
468 if len(errors) > 0 {
469 encode(w, r, http.StatusBadRequest, response{Errors: errors})
470 return
471 }
472 passphrase, salt, err := scheme.create(req.Passphrase, context.config.iterations)
473 if err != nil {
474 log.Printf("Error creating encoded passphrase: %#+v\n", err)
475 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
476 return
477 }
478 profile := Profile{
479 ID: uuid.NewID(),
480 Name: req.Name,
481 Passphrase: string(passphrase),
482 Iterations: context.config.iterations,
483 Salt: string(salt),
484 PassphraseScheme: CurPassphraseScheme,
485 Created: time.Now(),
486 LastSeen: time.Now(),
487 }
488 err = context.SaveProfile(profile)
489 if err != nil {
490 if err == ErrProfileAlreadyExists {
491 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/id"}}})
492 return
493 }
494 log.Printf("Error saving profile: %#+v\n", err)
495 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
496 return
497 }
498 logins := []Login{}
499 login := Login{
500 Type: "email",
501 Value: req.Email,
502 Created: profile.Created,
503 LastUsed: profile.Created,
504 ProfileID: profile.ID,
505 }
506 err = context.AddLogin(login)
507 if err != nil {
508 if err == ErrLoginAlreadyExists {
509 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/email"}}})
510 return
511 }
512 log.Printf("Error adding login: %#+v\n", err)
513 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
514 return
515 }
516 logins = append(logins, login)
517 resp := response{
518 Logins: logins,
519 Profiles: []Profile{profile},
520 }
521 encode(w, r, http.StatusCreated, resp)
522 // TODO(paddy): should we kick off the email validation flow?
523 }
525 func UpdateProfileHandler(w http.ResponseWriter, r *http.Request, context Context) {
526 errors := []requestError{}
527 vars := mux.Vars(r)
528 if vars["id"] == "" {
529 errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
530 encode(w, r, http.StatusBadRequest, response{Errors: errors})
531 return
532 }
533 id, err := uuid.Parse(vars["id"])
534 if err != nil {
535 errors = append(errors, requestError{Slug: requestErrAccessDenied})
536 encode(w, r, http.StatusBadRequest, response{Errors: errors})
537 return
538 }
539 username, password, ok := r.BasicAuth()
540 if !ok {
541 errors = append(errors, requestError{Slug: requestErrAccessDenied})
542 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
543 return
544 }
545 profile, err := authenticate(username, password, context)
546 if err != nil {
547 if isAuthError(err) {
548 errors = append(errors, requestError{Slug: requestErrAccessDenied})
549 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
550 } else {
551 errors = append(errors, requestError{Slug: requestErrActOfGod})
552 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
553 }
554 return
555 }
556 if !profile.ID.Equal(id) {
557 errors = append(errors, requestError{Slug: requestErrAccessDenied})
558 encode(w, r, http.StatusForbidden, response{Errors: errors})
559 return
560 }
561 var req ProfileChange
562 decoder := json.NewDecoder(r.Body)
563 err = decoder.Decode(&req)
564 if err != nil {
565 log.Printf("Error decoding request: %#+v\n", err)
566 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
567 return
568 }
569 req.Iterations = nil
570 req.Salt = nil
571 req.PassphraseScheme = nil
572 req.Compromised = nil // BUG(paddy): Need a way for admins to mark accounts as compromised
573 req.LockedUntil = nil
574 req.LastSeen = nil
575 if req.Passphrase != nil {
576 if len(*req.Passphrase) < MinPassphraseLength {
577 errors = append(errors, requestError{Slug: requestErrInsufficient, Field: "/passphrase"})
578 encode(w, r, http.StatusBadRequest, response{Errors: errors})
579 return
580 }
581 if len(*req.Passphrase) > MaxPassphraseLength {
582 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/passphrase"})
583 encode(w, r, http.StatusBadRequest, response{Errors: errors})
584 return
585 }
586 iterations := context.config.iterations
587 scheme, ok := passphraseSchemes[CurPassphraseScheme]
588 if !ok {
589 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
590 return
591 }
592 curScheme := CurPassphraseScheme
593 req.PassphraseScheme = &curScheme
594 passphrase, salt, err := scheme.create(*req.Passphrase, iterations)
595 if err != nil {
596 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
597 return
598 }
599 req.Passphrase = &passphrase
600 req.Salt = &salt
601 req.Iterations = &iterations
602 }
603 if req.PassphraseReset != nil {
604 now := time.Now()
605 req.PassphraseResetCreated = &now
606 }
607 err = req.Validate()
608 if err != nil {
609 var status int
610 var resp response
611 switch err {
612 case ErrEmptyChange:
613 resp.Profiles = []Profile{profile}
614 status = http.StatusOK
615 default:
616 errors = append(errors, requestError{Slug: requestErrActOfGod})
617 resp.Errors = errors
618 status = http.StatusInternalServerError
619 }
620 encode(w, r, status, resp)
621 return
622 }
623 err = context.UpdateProfile(id, req)
624 if err != nil {
625 if err == ErrProfileNotFound {
626 errors = append(errors, requestError{Slug: requestErrNotFound})
627 encode(w, r, http.StatusNotFound, response{Errors: errors})
628 return
629 }
630 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
631 return
632 }
633 if !profile.Deleted && req.Deleted != nil && *req.Deleted {
634 go cleanUpAfterProfileDeletion(profile.ID, context)
635 }
636 profile.ApplyChange(req)
637 encode(w, r, http.StatusOK, response{Profiles: []Profile{profile}})
638 return
639 }
641 func DeleteProfileHandler(w http.ResponseWriter, r *http.Request, context Context) {
642 errors := []requestError{}
643 vars := mux.Vars(r)
644 if vars["id"] == "" {
645 errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
646 encode(w, r, http.StatusBadRequest, response{Errors: errors})
647 return
648 }
649 id, err := uuid.Parse(vars["id"])
650 if err != nil {
651 errors = append(errors, requestError{Slug: requestErrAccessDenied})
652 encode(w, r, http.StatusBadRequest, response{Errors: errors})
653 return
654 }
655 username, password, ok := r.BasicAuth()
656 if !ok {
657 errors = append(errors, requestError{Slug: requestErrAccessDenied})
658 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
659 return
660 }
661 profile, err := authenticate(username, password, context)
662 if err != nil {
663 if isAuthError(err) {
664 errors = append(errors, requestError{Slug: requestErrAccessDenied})
665 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
666 } else {
667 errors = append(errors, requestError{Slug: requestErrActOfGod})
668 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
669 }
670 return
671 }
672 if !profile.ID.Equal(id) {
673 errors = append(errors, requestError{Slug: requestErrAccessDenied})
674 encode(w, r, http.StatusForbidden, response{Errors: errors})
675 return
676 }
677 var change ProfileChange
678 deleted := true
679 change.Deleted = &deleted
680 err = context.UpdateProfile(id, change)
681 if err != nil {
682 if err == ErrProfileNotFound {
683 errors = append(errors, requestError{Slug: requestErrNotFound})
684 encode(w, r, http.StatusNotFound, response{Errors: errors})
685 return
686 }
687 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
688 return
689 }
690 profile.ApplyChange(change)
691 encode(w, r, http.StatusOK, response{Profiles: []Profile{profile}})
692 go cleanUpAfterProfileDeletion(profile.ID, context)
693 }