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

     1  package google
     2  
     3  import (
     4  	ctx "context"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"reflect"
    11  	"strings"
    12  
    13  	"github.com/germla/auth"
    14  	"github.com/germla/auth/auth_identity"
    15  	"github.com/germla/auth/claims"
    16  	"github.com/qor/qor/utils"
    17  	"golang.org/x/oauth2"
    18  	"golang.org/x/oauth2/google"
    19  )
    20  
    21  var UserInfoURL = "https://www.googleapis.com/oauth2/v3/userinfo"
    22  
    23  // GoogleProvider provide login with google method
    24  type GoogleProvider struct {
    25  	*Config
    26  }
    27  
    28  // Config google Config
    29  type Config struct {
    30  	ClientID         string
    31  	ClientSecret     string
    32  	AuthorizeURL     string
    33  	TokenURL         string
    34  	RedirectURL      string
    35  	Scopes           []string
    36  	AllowedDomains   []string
    37  	AuthorizeHandler func(context *auth.Context) (*claims.Claims, error)
    38  }
    39  
    40  func New(config *Config) *GoogleProvider {
    41  	if config == nil {
    42  		config = &Config{}
    43  	}
    44  
    45  	provider := &GoogleProvider{Config: config}
    46  
    47  	if config.ClientID == "" {
    48  		panic(errors.New("Google's ClientID can't be blank"))
    49  	}
    50  
    51  	if config.ClientSecret == "" {
    52  		panic(errors.New("Google's ClientSecret can't be blank"))
    53  	}
    54  
    55  	if config.AuthorizeURL == "" {
    56  		config.AuthorizeURL = google.Endpoint.AuthURL
    57  	}
    58  
    59  	if config.TokenURL == "" {
    60  		config.TokenURL = google.Endpoint.TokenURL
    61  	}
    62  
    63  	if len(config.Scopes) == 0 {
    64  		config.Scopes = []string{"https://www.googleapis.com/auth/userinfo.email"}
    65  	}
    66  
    67  	if config.AuthorizeHandler == nil {
    68  		config.AuthorizeHandler = func(context *auth.Context) (*claims.Claims, error) {
    69  			var (
    70  				req          = context.Request
    71  				schema       auth.Schema
    72  				authInfo     auth_identity.Basic
    73  				tx           = context.Auth.GetDB(req)
    74  				authIdentity = reflect.New(utils.ModelType(context.Auth.Config.AuthIdentityModel)).Interface()
    75  			)
    76  
    77  			state := req.URL.Query().Get("state")
    78  			claims, err := context.Auth.SessionStorer.ValidateClaims(state)
    79  
    80  			if err != nil || claims.Valid() != nil || claims.Subject != "state" {
    81  				return nil, auth.ErrUnauthorized
    82  			}
    83  
    84  			if err == nil {
    85  				oauthCfg := provider.OAuthConfig(context)
    86  				tkn, err := oauthCfg.Exchange(oauth2.NoContext, req.URL.Query().Get("code"))
    87  
    88  				if err != nil {
    89  					return nil, err
    90  				}
    91  
    92  				{
    93  					client := oauthCfg.Client(oauth2.NoContext, tkn)
    94  					resp, err := client.Get(UserInfoURL)
    95  					if err != nil {
    96  						return nil, err
    97  					}
    98  
    99  					defer resp.Body.Close()
   100  					body, _ := ioutil.ReadAll(resp.Body)
   101  					userInfo := UserInfo{}
   102  					json.Unmarshal(body, &userInfo)
   103  					schema.Provider = provider.GetName()
   104  					schema.UID = userInfo.Email
   105  					schema.Email = userInfo.Email
   106  					schema.FirstName = userInfo.GivenName
   107  					schema.LastName = userInfo.FamilyName
   108  					schema.Image = userInfo.Picture
   109  					schema.Name = userInfo.Name
   110  					schema.RawInfo = userInfo
   111  				}
   112  
   113  				if !isDomainAllowed(schema.Email, config.AllowedDomains) {
   114  					return nil, auth.ErrUnauthorized
   115  				}
   116  
   117  				authInfo.Provider = provider.GetName()
   118  				authInfo.UID = schema.UID
   119  
   120  				if tx.NewSelect().Model(authIdentity).Where("provider = ? AND uid = ?", provider.GetName(), schema.UID).Scan(ctx.Background(), &authInfo); err == nil {
   121  					return authInfo.ToClaims(), nil
   122  				}
   123  
   124  				if _, userID, err := context.Auth.UserStorer.Save(&schema, context); err == nil {
   125  					if userID != "" {
   126  						authInfo.UserID = userID
   127  					}
   128  				} else {
   129  					return nil, err
   130  				}
   131  
   132  				if err := tx.NewSelect().Model(authIdentity).Where("provider = ? AND uid = ?", provider.GetName(), schema.UID).Scan(ctx.Background(), &authInfo); err == nil {
   133  					// Create a new user
   134  					if _, err := tx.NewInsert().Model(authIdentity).Set("provider", provider.GetName()).Set("uid", schema.UID).Exec(ctx.Background()); err == nil {
   135  						return authInfo.ToClaims(), nil
   136  					}
   137  				}
   138  
   139  				// Convert above from GORM to Bun
   140  
   141  			}
   142  
   143  			return nil, err
   144  		}
   145  	}
   146  	return provider
   147  }
   148  
   149  func isDomainAllowed(email string, domains []string) bool {
   150  	if len(domains) == 0 {
   151  		return true
   152  	}
   153  
   154  	for _, domain := range domains {
   155  		if strings.HasSuffix(email, fmt.Sprintf("@%s", domain)) {
   156  			return true
   157  		}
   158  	}
   159  	return false
   160  }
   161  
   162  // GetName return provider name
   163  func (GoogleProvider) GetName() string {
   164  	return "google"
   165  }
   166  
   167  // ConfigAuth config auth
   168  func (provider GoogleProvider) ConfigAuth(*auth.Auth) {
   169  }
   170  
   171  // OAuthConfig return oauth config based on configuration
   172  func (provider GoogleProvider) OAuthConfig(context *auth.Context) *oauth2.Config {
   173  	var (
   174  		config = provider.Config
   175  		scheme = context.Request.URL.Scheme
   176  	)
   177  
   178  	if scheme == "" {
   179  		scheme = "http://"
   180  	}
   181  
   182  	return &oauth2.Config{
   183  		ClientID:     config.ClientID,
   184  		ClientSecret: config.ClientSecret,
   185  		Endpoint: oauth2.Endpoint{
   186  			AuthURL:  config.AuthorizeURL,
   187  			TokenURL: config.TokenURL,
   188  		},
   189  		RedirectURL: scheme + context.Request.Host + context.Auth.AuthURL("google/callback"),
   190  		Scopes:      config.Scopes,
   191  	}
   192  }
   193  
   194  // Login implemented login with google provider
   195  func (provider GoogleProvider) Login(context *auth.Context) {
   196  	claims := claims.Claims{}
   197  	claims.Subject = "state"
   198  	signedToken := context.Auth.SessionStorer.SignedToken(&claims)
   199  
   200  	url := provider.OAuthConfig(context).AuthCodeURL(signedToken)
   201  	http.Redirect(context.Writer, context.Request, url, http.StatusFound)
   202  }
   203  
   204  // Logout implemented logout with google provider
   205  func (GoogleProvider) Logout(context *auth.Context) {
   206  }
   207  
   208  // Register implemented register with google provider
   209  func (provider GoogleProvider) Register(context *auth.Context) {
   210  	provider.Login(context)
   211  }
   212  
   213  // Callback implement Callback with google provider
   214  func (provider GoogleProvider) Callback(context *auth.Context) {
   215  	context.Auth.LoginHandler(context, provider.AuthorizeHandler)
   216  }
   217  
   218  // ServeHTTP implement ServeHTTP with google provider
   219  func (GoogleProvider) ServeHTTP(*auth.Context) {
   220  }
   221  
   222  // UserInfo google user info structure
   223  type UserInfo struct {
   224  	Sub           string `json:"sub"`
   225  	Name          string `json:"name"`
   226  	GivenName     string `json:"given_name"`
   227  	FamilyName    string `json:"family_name"`
   228  	Picture       string `json:"picture"`
   229  	Profile       string `json:"profile"`
   230  	Email         string `json:"email"`
   231  	EmailVerified bool   `json:"email_verified"`
   232  	Gender        string `json:"gender"`
   233  }