google.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package auth
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. )
  9. type GoogleUser struct {
  10. ID string `json:"id,omitempty"`
  11. Email string `json:"email,omitempty"`
  12. Name string `json:"name,omitempty"`
  13. }
  14. const InfoURL = "https://www.googleapis.com/oauth2/v2/userinfo"
  15. func GetGoogleSignInURL() string {
  16. return fmt.Sprintf(
  17. "%s?client_id=%s&redirect_uri=%s&response_type=code&scope=openid email profile",
  18. googleConfig.Endpoint.AuthURL,
  19. googleConfig.ClientID,
  20. googleConfig.RedirectURL,
  21. )
  22. }
  23. func GetGoogleAccessToken(code string) (string, error) {
  24. getTokenURL := fmt.Sprintf(
  25. "%s?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s",
  26. googleConfig.Endpoint.TokenURL, googleConfig.ClientID, googleConfig.ClientSecret, googleConfig.RedirectURL, code,
  27. )
  28. fmt.Println(getTokenURL)
  29. tokenRequest, err := http.NewRequest("POST", getTokenURL, nil)
  30. if err != nil {
  31. return "", err
  32. }
  33. tokenClient := &http.Client{}
  34. tokenResponse, err := tokenClient.Do(tokenRequest)
  35. if err != nil {
  36. return "", err
  37. }
  38. defer tokenResponse.Body.Close()
  39. tokenBody, _ := ioutil.ReadAll(tokenResponse.Body)
  40. var tokenObject map[string]interface{}
  41. json.Unmarshal(tokenBody, &tokenObject)
  42. return tokenObject["access_token"].(string), nil
  43. }
  44. func GetGoogleUserInfo(code string) (*GoogleUser, error) {
  45. if len(code) <= 0 {
  46. return nil, errors.New("invalid parameter value")
  47. }
  48. token, err := GetGoogleAccessToken(code)
  49. if err != nil {
  50. return nil, err
  51. }
  52. //GET USER INFO
  53. getUserInfoURL := fmt.Sprintf(
  54. "%s?access_token=%s",
  55. InfoURL,
  56. token,
  57. )
  58. userInfoRequest, err := http.NewRequest("GET", getUserInfoURL, nil)
  59. if err != nil {
  60. return nil, err
  61. }
  62. userInfoClient := &http.Client{}
  63. userInfoResponse, err := userInfoClient.Do(userInfoRequest)
  64. if err != nil {
  65. return nil, err
  66. }
  67. defer userInfoResponse.Body.Close()
  68. userInfoBody, _ := ioutil.ReadAll(userInfoResponse.Body)
  69. var userInfoObject map[string]interface{}
  70. json.Unmarshal(userInfoBody, &userInfoObject)
  71. if userInfoResponse.StatusCode != 200 {
  72. return nil, errors.New("invalid access token")
  73. }
  74. return &GoogleUser{
  75. ID: userInfoObject["id"].(string),
  76. Name: userInfoObject["name"].(string),
  77. Email: userInfoObject["email"].(string),
  78. }, nil
  79. }