context.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package auth
  15. import (
  16. "sync"
  17. "github.com/google/martian"
  18. )
  19. const key = "auth.Context"
  20. // Context contains authentication information.
  21. type Context struct {
  22. mu sync.RWMutex
  23. id string
  24. err error
  25. }
  26. // FromContext retrieves the auth.Context from the session.
  27. func FromContext(ctx *martian.Context) *Context {
  28. if v, ok := ctx.Session().Get(key); ok {
  29. return v.(*Context)
  30. }
  31. actx := &Context{}
  32. ctx.Session().Set(key, actx)
  33. return actx
  34. }
  35. // ID returns the ID.
  36. func (ctx *Context) ID() string {
  37. ctx.mu.RLock()
  38. defer ctx.mu.RUnlock()
  39. return ctx.id
  40. }
  41. // SetID sets the ID.
  42. func (ctx *Context) SetID(id string) {
  43. ctx.mu.Lock()
  44. defer ctx.mu.Unlock()
  45. ctx.err = nil
  46. if id == "" {
  47. return
  48. }
  49. ctx.id = id
  50. }
  51. // SetError sets the error and resets the ID.
  52. func (ctx *Context) SetError(err error) {
  53. ctx.mu.Lock()
  54. defer ctx.mu.Unlock()
  55. ctx.id = ""
  56. ctx.err = err
  57. }
  58. // Error returns the error.
  59. func (ctx *Context) Error() error {
  60. ctx.mu.RLock()
  61. defer ctx.mu.RUnlock()
  62. return ctx.err
  63. }