-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle_handler.go
63 lines (48 loc) · 1.28 KB
/
google_handler.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
package handler
import (
"errors"
"github.com/laqiiz/airac/conn"
"google.golang.org/api/oauth2/v2"
"google.golang.org/api/option"
"html/template"
"net/http"
)
type GoogleHandler struct {
}
type GoogleCallbackRequest struct {
Code string
State string
}
func (h *GoogleHandler) AuthRedirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, conn.GetGoogleConnect().AuthCodeURL(""), 302)
}
func (h *GoogleHandler) Callback(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var request = GoogleCallbackRequest{
Code: r.URL.Query().Get("code"),
State: r.URL.Query().Get("state"),
}
connect := conn.GetGoogleConnect()
tok, err := connect.Exchange(ctx, request.Code)
if err != nil {
panic(err)
}
if tok.Valid() == false {
panic(errors.New("valid token"))
}
service, err := oauth2.NewService(ctx, option.WithHTTPClient(connect.Client(ctx, tok)))
if err != nil {
panic(err)
}
tokenInfo, err := service.Tokeninfo().AccessToken(tok.AccessToken).Context(ctx).Do()
if err != nil {
panic(err)
}
data := map[string]interface{}{}
data["ID"] = tokenInfo.UserId
data["Email"] = tokenInfo.Email
tpl := template.Must(template.ParseFiles("view/google/callback.tpl"))
if err := tpl.Execute(w, data); err != nil {
_, _ = w.Write([]byte(err.Error()))
}
}