| 72 | } |
| 73 | |
| 74 | func fetchGoogleUserInfo(ctx context.Context, token string) (*GoogleUserInfo, error) { |
| 75 | url := fmt.Sprintf("https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=%s", token) |
| 76 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 77 | if err != nil { |
| 78 | return nil, fmt.Errorf("failed to create request: %v", err) |
| 79 | } |
| 80 | client := &http.Client{} |
| 81 | resp, err := client.Do(req) |
| 82 | if err != nil { |
| 83 | return nil, fmt.Errorf("failed to validate token: %v", err) |
| 84 | } |
| 85 | defer resp.Body.Close() |
| 86 | if resp.StatusCode != http.StatusOK { |
| 87 | bodyBytes, _ := io.ReadAll(resp.Body) |
| 88 | return nil, fmt.Errorf("invalid token, status code: %d, response: %s", resp.StatusCode, string(bodyBytes)) |
| 89 | } |
| 90 | |
| 91 | url = "https://www.googleapis.com/oauth2/v2/userinfo" |
| 92 | req, err = http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 93 | if err != nil { |
| 94 | return nil, fmt.Errorf("failed to create request: %v", err) |
| 95 | } |
| 96 | req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) |
| 97 | client = &http.Client{} |
| 98 | resp, err = client.Do(req) |
| 99 | if err != nil { |
| 100 | return nil, fmt.Errorf("failed to validate token: %v", err) |
| 101 | } |
| 102 | defer resp.Body.Close() |
| 103 | if resp.StatusCode != http.StatusOK { |
| 104 | bodyBytes, _ := io.ReadAll(resp.Body) |
| 105 | return nil, fmt.Errorf("invalid token, status code: %d, response: %s", resp.StatusCode, string(bodyBytes)) |
| 106 | } |
| 107 | |
| 108 | var userInfo GoogleUserInfo |
| 109 | if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil { |
| 110 | return nil, fmt.Errorf("failed to decode user info: %v", err) |
| 111 | } |
| 112 | |
| 113 | return &userInfo, nil |
| 114 | } |