github.com/google/martian/v3@v3.3.3/auth/context.go (about) 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 15 package auth 16 17 import ( 18 "sync" 19 20 "github.com/google/martian/v3" 21 ) 22 23 const key = "auth.Context" 24 25 // Context contains authentication information. 26 type Context struct { 27 mu sync.RWMutex 28 id string 29 err error 30 } 31 32 // FromContext retrieves the auth.Context from the session. 33 func FromContext(ctx *martian.Context) *Context { 34 if v, ok := ctx.Session().Get(key); ok { 35 return v.(*Context) 36 } 37 38 actx := &Context{} 39 ctx.Session().Set(key, actx) 40 41 return actx 42 } 43 44 // ID returns the ID. 45 func (ctx *Context) ID() string { 46 ctx.mu.RLock() 47 defer ctx.mu.RUnlock() 48 49 return ctx.id 50 } 51 52 // SetID sets the ID. 53 func (ctx *Context) SetID(id string) { 54 ctx.mu.Lock() 55 defer ctx.mu.Unlock() 56 57 ctx.err = nil 58 59 if id == "" { 60 return 61 } 62 63 ctx.id = id 64 } 65 66 // SetError sets the error and resets the ID. 67 func (ctx *Context) SetError(err error) { 68 ctx.mu.Lock() 69 defer ctx.mu.Unlock() 70 71 ctx.id = "" 72 ctx.err = err 73 } 74 75 // Error returns the error. 76 func (ctx *Context) Error() error { 77 ctx.mu.RLock() 78 defer ctx.mu.RUnlock() 79 80 return ctx.err 81 }