-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_email.go
72 lines (69 loc) · 1.89 KB
/
get_email.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package lib
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
)
func GetToken(code string) (string, error) {
encoded := url.Values{}
encoded.Set("code", code)
encoded.Set("client_id", os.Getenv("CLIENT_ID"))
encoded.Set("client_secret", os.Getenv("CLIENT_SECRET"))
encoded.Set("grant_type", "authorization_code")
encoded.Set("redirect_uri", os.Getenv("REDIRECT_URI"))
resp, err := http.Post("https://www.googleapis.com/oauth2/v4/token", "application/x-www-form-urlencoded", strings.NewReader(encoded.Encode()))
if err != nil {
log.Print("Google HTTP request Failed")
return "", errors.New("google http request Failed")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Print("Error Decoding Response")
return "", errors.New("error decoding response")
}
var dat struct {
Access_token string `json:"access_token"`
}
err = json.Unmarshal(body, &dat)
if err != nil {
log.Println("Failed to Unmarshal JSON")
return "", err
}
return dat.Access_token, nil
}
func GetEmail(token string) (string, error) {
req, err := http.NewRequest("GET", "https://www.googleapis.com/oauth2/v3/userinfo", nil)
if err != nil {
log.Print("Error Creating HTTP Request")
return "", errors.New("error creating http request")
}
req.Header.Add("Authorization", "Bearer "+token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Print("Google HTTP request Failed")
return "", errors.New("google http request failed")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Print("Error Decoding Response")
return "", errors.New("error decoding response")
}
var dat struct {
Email string `json:"email"`
}
err = json.Unmarshal(body, &dat)
if err != nil {
log.Println("Failed to Unmarshal JSON")
return "", err
}
if dat.Email == "" {
return "", errors.New("User did not authorize email")
}
return dat.Email, nil
}