go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/session_middleware.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package web 9 10 // SessionAware is an action that injects the session into the context. 11 func SessionAware(action Action) Action { 12 return func(ctx Context) Result { 13 session, err := ctx.App().VerifyOrExtendSession(ctx) 14 if err != nil && !IsErrSessionInvalid(err) { 15 return AcceptedProvider(ctx).InternalError(err) 16 } 17 return action(ctx.WithSession(session)) 18 } 19 } 20 21 // SessionAwareStable is an action that injects the session into the context, but does 22 // not extend it if there is a session lifetime handler on the auth manager. 23 // 24 // It is typically used for logout endpoints, where you don't want a session 25 // extension `Set-Cookie` response header to compete with the expiry header. 26 func SessionAwareStable(action Action) Action { 27 return func(ctx Context) Result { 28 _, session, err := ctx.App().VerifySession(ctx) 29 if err != nil && !IsErrSessionInvalid(err) { 30 return AcceptedProvider(ctx).InternalError(err) 31 } 32 return action(ctx.WithSession(session)) 33 } 34 } 35 36 // SessionRequired is an action that requires a session to be present 37 // or identified in some form on the request. 38 func SessionRequired(action Action) Action { 39 return func(ctx Context) Result { 40 session, err := ctx.App().VerifyOrExtendSession(ctx) 41 if err != nil && !IsErrSessionInvalid(err) { 42 return AcceptedProvider(ctx).InternalError(err) 43 } 44 if session == nil { 45 return ctx.App().LoginRedirect(ctx) 46 } 47 return action(ctx.WithSession(session)) 48 } 49 }