/
login.go
112 lines (92 loc) · 2.42 KB
/
login.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"flag"
"log"
"net/http"
"strings"
"github.com/bbhmakerlab/openinnovation/response"
"github.com/bbhmakerlab/openinnovation/session"
"github.com/bbhmakerlab/openinnovation/store"
"github.com/google/google-api-go-client/plus/v1"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var redirectURL = flag.String("url", "http://localhost:8080", "Google OAuth2 redirect URL")
func Login(w http.ResponseWriter, r *http.Request) {
var conf = &oauth2.Config{
ClientID: "320643691401-5m3ipff7ghamacndnvipda0uqi3eranu.apps.googleusercontent.com",
ClientSecret: "Eb6_-XWDGeO5NqD1snPkoGX6",
RedirectURL: *redirectURL,
Endpoint: google.Endpoint,
}
log.Println("Using", *redirectURL, "as redirect URL for Google API OAuth2")
authCode := r.FormValue("code")
tok, err := conf.Exchange(oauth2.NoContext, authCode)
if err != nil {
response.ClientError(w, http.StatusBadRequest)
return
}
loginGoogle(w, r, conf, tok)
}
func loginGoogle(w http.ResponseWriter, r *http.Request, conf *oauth2.Config, tok *oauth2.Token) {
client := conf.Client(oauth2.NoContext, tok)
service, err := plus.New(client)
if err != nil {
response.ServerError(w, err)
return
}
call := service.People.Get("me")
person, err := call.Do()
if err != nil {
response.ServerError(w, err)
return
}
email := ""
for _, em := range person.Emails {
if em.Type == "account" {
email = em.Value
break
}
}
if !strings.HasSuffix(email, "@bartleboglehegarty.com") && email != "aqiank@gmail.com" {
response.ClientError(w, http.StatusForbidden)
return
}
if store.HasUserWithEmail(email) {
loginSuccess(w, r, email)
return
}
firstname := person.Name.GivenName
lastname := person.Name.FamilyName
description := person.AboutMe
imageURL := ""
if !person.Image.IsDefault {
imageURL = person.Image.Url
if idx := strings.LastIndexFunc(
imageURL,
func(r rune) bool {
return r == '?'
},
); idx >= 0 {
imageURL = imageURL[:idx]
}
}
fullname := firstname
if lastname != "" {
fullname += " " + lastname
}
if err := store.Register(email, "", fullname, "", description, imageURL); err != nil {
response.ServerError(w, err)
return
}
loginSuccess(w, r, email)
}
func loginSuccess(w http.ResponseWriter, r *http.Request, email string) {
session.Set(w, r, email)
user := store.CurrentUser(r)
if !user.Exists() {
response.ClientError(w, http.StatusForbidden)
return
}
response.OK(w, user)
}