github.com/blend/go-sdk@v1.20220411.3/web/session_middleware.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  // SessionAware is an action that injects the session into the context.
    11  func SessionAware(action Action) Action {
    12  	return func(ctx *Ctx) Result {
    13  		session, err := ctx.App.Auth.VerifyOrExtendSession(ctx)
    14  		if err != nil && !IsErrSessionInvalid(err) {
    15  			return ctx.DefaultProvider.InternalError(err)
    16  		}
    17  		ctx.Session = session
    18  		ctx.WithContext(WithSession(ctx.Context(), session))
    19  		return action(ctx)
    20  	}
    21  }
    22  
    23  // SessionAwareForLogout is an action that injects the session into the context, but does
    24  // not extend it if there is a session lifetime handler on the auth manager.
    25  func SessionAwareForLogout(action Action) Action {
    26  	return func(ctx *Ctx) Result {
    27  		_, session, err := ctx.App.Auth.VerifySession(ctx)
    28  		if err != nil && !IsErrSessionInvalid(err) {
    29  			return ctx.DefaultProvider.InternalError(err)
    30  		}
    31  		ctx.Session = session
    32  		ctx.WithContext(WithSession(ctx.Context(), session))
    33  		return action(ctx)
    34  	}
    35  }
    36  
    37  // SessionRequired is an action that requires a session to be present
    38  // or identified in some form on the request.
    39  func SessionRequired(action Action) Action {
    40  	return func(ctx *Ctx) Result {
    41  		session, err := ctx.App.Auth.VerifyOrExtendSession(ctx)
    42  		if err != nil && !IsErrSessionInvalid(err) {
    43  			return ctx.DefaultProvider.InternalError(err)
    44  		}
    45  		if session == nil {
    46  			return ctx.App.Auth.LoginRedirect(ctx)
    47  		}
    48  		ctx.Session = session
    49  		ctx.WithContext(WithSession(ctx.Context(), session))
    50  		return action(ctx)
    51  	}
    52  }
    53  
    54  // SessionMiddleware implements a custom notAuthorized action.
    55  func SessionMiddleware(notAuthorized Action) Middleware {
    56  	return func(action Action) Action {
    57  		return func(ctx *Ctx) Result {
    58  			session, err := ctx.App.Auth.VerifyOrExtendSession(ctx)
    59  			if err != nil && !IsErrSessionInvalid(err) {
    60  				return ctx.DefaultProvider.InternalError(err)
    61  			}
    62  
    63  			if session == nil {
    64  				if notAuthorized != nil {
    65  					return notAuthorized(ctx)
    66  				}
    67  				return ctx.App.Auth.LoginRedirect(ctx)
    68  			}
    69  			ctx.Session = session
    70  			ctx.WithContext(WithSession(ctx.Context(), session))
    71  			return action(ctx)
    72  		}
    73  	}
    74  }