This repository has been archived by the owner on Apr 27, 2021. It is now read-only.
forked from orenmazor/minimoozie
-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth_handler.go
94 lines (79 loc) · 2.43 KB
/
auth_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
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
package main
import "fmt"
import "encoding/json"
import "golang.org/x/oauth2"
import "golang.org/x/oauth2/google"
import "net/http"
import "github.com/satori/go.uuid"
import "github.com/gorilla/sessions"
type GoogleProfile struct {
Name string `json:"name"`
}
var store = sessions.NewCookieStore(uuid.NewV4().Bytes())
func IsAuthorized(response http.ResponseWriter, request *http.Request) bool {
session, err := store.Get(request, "minimoozie")
check(err)
if session.IsNew {
return false
} else {
token := oauth2.Token{AccessToken: session.Values["token"].(string)}
user := getUser(&token)
if user.Name == session.Values["name"] {
return true
} else {
log.Error(fmt.Sprintf("cookie username (%s) doesnt match received username (%s)", session.Values["name"], user.Name))
}
}
return false
}
func Authorize(response http.ResponseWriter, request *http.Request) bool {
if !IsAuthorized(response, request) {
oauthconf := &oauth2.Config{
ClientID: Conf.OauthClientId,
ClientSecret: Conf.OauthClientSecret,
RedirectURL: Conf.RedirectURL,
Scopes: []string{"profile"},
Endpoint: google.Endpoint,
}
url := oauthconf.AuthCodeURL("state")
http.Redirect(response, request, url, http.StatusFound)
return false
}
return true
}
func OauthCallbackHandler(response http.ResponseWriter, request *http.Request) {
oauthconf := &oauth2.Config{
ClientID: Conf.OauthClientId,
ClientSecret: Conf.OauthClientSecret,
RedirectURL: Conf.RedirectURL,
Scopes: []string{"profile"},
Endpoint: google.Endpoint,
}
code := request.FormValue("code")
tok, err := oauthconf.Exchange(oauth2.NoContext, code)
check(err)
user := getUser(tok)
session, err := store.Get(request, "minimoozie")
check(err)
session.Values["token"] = tok.AccessToken
session.Values["name"] = user.Name
err = session.Save(request, response)
check(err)
http.Redirect(response, request, "/", http.StatusFound)
}
func getUser(token *oauth2.Token) GoogleProfile {
oauthconf := &oauth2.Config{
ClientID: Conf.OauthClientId,
ClientSecret: Conf.OauthClientSecret,
RedirectURL: Conf.RedirectURL,
Scopes: []string{"profile"},
Endpoint: google.Endpoint,
}
client := oauthconf.Client(oauth2.NoContext, token)
resp, err := client.Get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
check(err)
result := new(GoogleProfile)
err = json.NewDecoder(resp.Body).Decode(result)
check(err)
return *result
}