github.com/blend/go-sdk@v1.20220411.3/web/local_session_cache.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package web 9 10 import ( 11 "context" 12 "sync" 13 ) 14 15 // NewLocalSessionCache returns a new session cache. 16 func NewLocalSessionCache() *LocalSessionCache { 17 return &LocalSessionCache{ 18 SessionLock: &sync.Mutex{}, 19 Sessions: map[string]*Session{}, 20 } 21 } 22 23 // LocalSessionCache is a memory cache of sessions. 24 // It is meant to be used in tests. 25 type LocalSessionCache struct { 26 SessionLock *sync.Mutex 27 Sessions map[string]*Session 28 } 29 30 // Apply applies the local session cache to a given auth manager. 31 func (lsc *LocalSessionCache) Apply(am *AuthManager) { 32 am.FetchHandler = lsc.FetchHandler 33 am.PersistHandler = lsc.PersistHandler 34 am.RemoveHandler = lsc.RemoveHandler 35 } 36 37 // FetchHandler is a shim to interface with the auth manager. 38 func (lsc *LocalSessionCache) FetchHandler(_ context.Context, sessionID string) (*Session, error) { 39 return lsc.Get(sessionID), nil 40 } 41 42 // PersistHandler is a shim to interface with the auth manager. 43 func (lsc *LocalSessionCache) PersistHandler(_ context.Context, session *Session) error { 44 lsc.Upsert(session) 45 return nil 46 } 47 48 // RemoveHandler is a shim to interface with the auth manager. 49 func (lsc *LocalSessionCache) RemoveHandler(_ context.Context, sessionID string) error { 50 lsc.Remove(sessionID) 51 return nil 52 } 53 54 // Upsert adds or updates a session to the cache. 55 func (lsc *LocalSessionCache) Upsert(session *Session) { 56 lsc.SessionLock.Lock() 57 defer lsc.SessionLock.Unlock() 58 lsc.Sessions[session.SessionID] = session 59 } 60 61 // Remove removes a session from the cache. 62 func (lsc *LocalSessionCache) Remove(sessionID string) { 63 lsc.SessionLock.Lock() 64 defer lsc.SessionLock.Unlock() 65 delete(lsc.Sessions, sessionID) 66 } 67 68 // Get gets a session. 69 func (lsc *LocalSessionCache) Get(sessionID string) *Session { 70 lsc.SessionLock.Lock() 71 defer lsc.SessionLock.Unlock() 72 73 if session, hasSession := lsc.Sessions[sessionID]; hasSession { 74 return session 75 } 76 return nil 77 }