package auth import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" ) type GoogleUser struct { ID string `json:"id,omitempty"` Email string `json:"email,omitempty"` Name string `json:"name,omitempty"` } const InfoURL = "https://www.googleapis.com/oauth2/v2/userinfo" func GetGoogleSignInURL() string { return fmt.Sprintf( "%s?client_id=%s&redirect_uri=%s&response_type=code&scope=openid email profile", googleConfig.Endpoint.AuthURL, googleConfig.ClientID, googleConfig.RedirectURL, ) } func GetGoogleAccessToken(code string) (string, error) { getTokenURL := fmt.Sprintf( "%s?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s", googleConfig.Endpoint.TokenURL, googleConfig.ClientID, googleConfig.ClientSecret, googleConfig.RedirectURL, code, ) fmt.Println(getTokenURL) tokenRequest, err := http.NewRequest("POST", getTokenURL, nil) if err != nil { return "", err } tokenClient := &http.Client{} tokenResponse, err := tokenClient.Do(tokenRequest) if err != nil { return "", err } defer tokenResponse.Body.Close() tokenBody, _ := ioutil.ReadAll(tokenResponse.Body) var tokenObject map[string]interface{} json.Unmarshal(tokenBody, &tokenObject) return tokenObject["access_token"].(string), nil } func GetGoogleUserInfo(code string) (*GoogleUser, error) { if len(code) <= 0 { return nil, errors.New("invalid parameter value") } token, err := GetGoogleAccessToken(code) if err != nil { return nil, err } //GET USER INFO getUserInfoURL := fmt.Sprintf( "%s?access_token=%s", InfoURL, token, ) userInfoRequest, err := http.NewRequest("GET", getUserInfoURL, nil) if err != nil { return nil, err } userInfoClient := &http.Client{} userInfoResponse, err := userInfoClient.Do(userInfoRequest) if err != nil { return nil, err } defer userInfoResponse.Body.Close() userInfoBody, _ := ioutil.ReadAll(userInfoResponse.Body) var userInfoObject map[string]interface{} json.Unmarshal(userInfoBody, &userInfoObject) if userInfoResponse.StatusCode != 200 { return nil, errors.New("invalid access token") } return &GoogleUser{ ID: userInfoObject["id"].(string), Name: userInfoObject["name"].(string), Email: userInfoObject["email"].(string), }, nil }