github.com/germla/auth@v0.0.0-20230505173936-bc9a4159cf17/auth.go (about)

     1  package auth
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/germla/auth/auth_identity"
     8  	"github.com/germla/auth/claims"
     9  	jwt "github.com/golang-jwt/jwt/v4"
    10  	"github.com/qor/mailer"
    11  	"github.com/qor/mailer/logger"
    12  	"github.com/qor/redirect_back"
    13  	"github.com/qor/render"
    14  	"github.com/qor/session/manager"
    15  	"github.com/uptrace/bun"
    16  )
    17  
    18  // Auth auth struct
    19  type Auth struct {
    20  	*Config
    21  	// Embed SessionStorer to match Authority's AuthInterface
    22  	SessionStorerInterface
    23  	providers []Provider
    24  }
    25  
    26  // Config auth config
    27  type Config struct {
    28  	// Default Database, which will be used in Auth when do CRUD, you can change a request's DB isntance by setting request Context's value, refer https://github.com/germla/auth/blob/master/utils.go#L32
    29  	DB *bun.DB
    30  	// AuthIdentityModel a model used to save auth info, like email/password, OAuth token, linked user's ID, https://github.com/germla/auth/blob/master/auth_identity/auth_identity.go is the default implemention
    31  	AuthIdentityModel interface{}
    32  	// UserModel should be point of user struct's instance, it could be nil, then Auth will assume there is no user linked to auth info, and will return current auth info when get current user
    33  	UserModel interface{}
    34  	// Mount Auth into router with URLPrefix's value as prefix, default value is `/auth`.
    35  	URLPrefix string
    36  	// ViewPaths prepend views paths for auth
    37  	ViewPaths []string
    38  
    39  	// Auth is using [Render](https://github.com/qor/render) to render pages, you could configure it with your project's Render if you have advanced usage like [BindataFS](https://github.com/qor/bindatafs)
    40  	Render *render.Render
    41  	// Auth is using [Mailer](https://github.com/qor/mailer) to send email, by default, it will print email into console, you need to configure it to send real one
    42  	Mailer *mailer.Mailer
    43  	// UserStorer is an interface that defined how to get/save user, Auth provides a default one based on AuthIdentityModel, UserModel's definition
    44  	UserStorer UserStorerInterface
    45  	// SessionStorer is an interface that defined how to encode/validate/save/destroy session data and flash messages between requests, Auth provides a default method do the job, to use the default value, don't forgot to mount SessionManager's middleware into your router to save session data correctly. refer [session](https://github.com/qor/session) for more details
    46  	SessionStorer SessionStorerInterface
    47  	// Redirector redirect user to a new page after registered, logged, confirmed...
    48  	Redirector RedirectorInterface
    49  
    50  	// LoginHandler defined behaviour when request `{Auth Prefix}/login`, default behaviour defined in http://godoc.org/github.com/germla/auth#pkg-variables
    51  	LoginHandler func(*Context, func(*Context) (*claims.Claims, error))
    52  	// RegisterHandler defined behaviour when request `{Auth Prefix}/register`, default behaviour defined in http://godoc.org/github.com/germla/auth#pkg-variables
    53  	RegisterHandler func(*Context, func(*Context) (*claims.Claims, error))
    54  	// LogoutHandler defined behaviour when request `{Auth Prefix}/logout`, default behaviour defined in http://godoc.org/github.com/germla/auth#pkg-variables
    55  	LogoutHandler func(*Context)
    56  }
    57  
    58  // New initialize Auth
    59  func New(config *Config) *Auth {
    60  	if config == nil {
    61  		config = &Config{}
    62  	}
    63  
    64  	if config.URLPrefix == "" {
    65  		config.URLPrefix = "/auth/"
    66  	} else {
    67  		config.URLPrefix = fmt.Sprintf("/%v/", strings.Trim(config.URLPrefix, "/"))
    68  	}
    69  
    70  	if config.AuthIdentityModel == nil {
    71  		config.AuthIdentityModel = &auth_identity.AuthIdentity{}
    72  	}
    73  
    74  	if config.Render == nil {
    75  		config.Render = render.New(nil)
    76  	}
    77  
    78  	if config.Mailer == nil {
    79  		config.Mailer = mailer.New(&mailer.Config{
    80  			Sender: logger.New(&logger.Config{}),
    81  		})
    82  	}
    83  
    84  	if config.UserStorer == nil {
    85  		config.UserStorer = &UserStorer{}
    86  	}
    87  
    88  	if config.SessionStorer == nil {
    89  		config.SessionStorer = &SessionStorer{
    90  			SessionName:    "_auth_session",
    91  			SessionManager: manager.SessionManager,
    92  			SigningMethod:  jwt.SigningMethodHS256,
    93  		}
    94  	}
    95  
    96  	if config.Redirector == nil {
    97  		config.Redirector = &Redirector{redirect_back.New(&redirect_back.Config{
    98  			SessionManager:  manager.SessionManager,
    99  			IgnoredPrefixes: []string{config.URLPrefix},
   100  		})}
   101  	}
   102  
   103  	if config.LoginHandler == nil {
   104  		config.LoginHandler = DefaultLoginHandler
   105  	}
   106  
   107  	if config.RegisterHandler == nil {
   108  		config.RegisterHandler = DefaultRegisterHandler
   109  	}
   110  
   111  	if config.LogoutHandler == nil {
   112  		config.LogoutHandler = DefaultLogoutHandler
   113  	}
   114  
   115  	for _, viewPath := range config.ViewPaths {
   116  		config.Render.RegisterViewPath(viewPath)
   117  	}
   118  
   119  	config.Render.RegisterViewPath("github.com/germla/auth/views")
   120  
   121  	auth := &Auth{Config: config}
   122  
   123  	auth.SessionStorerInterface = config.SessionStorer
   124  
   125  	return auth
   126  }