This repository has been archived by the owner on Apr 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
100 lines (85 loc) · 2.28 KB
/
auth.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
package main
import (
"encoding/json"
"net/http"
"net/url"
"os"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
)
func LogoutR(c *gin.Context) {
session := sessions.Default(c)
session.Delete("user")
if err := session.Save(); err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Redirect(http.StatusFound, "/")
}
func CallbackR(c *gin.Context) {
// dependency injection
var (
userStore = c.MustGet(UserStoreKey).(UserStore)
)
domain := "whiskee.eu.auth0.com"
redirect := url.URL{
Scheme: "http",
Host: c.Request.Host,
Path: "/auth/callback",
}
// Instantiating the OAuth2 package to exchange the Code for a Token
conf := &oauth2.Config{
ClientID: os.Getenv("AUTH0_CID"),
ClientSecret: os.Getenv("AUTH0_SECRET"),
RedirectURL: redirect.String(),
Scopes: []string{"openid", "name", "email", "nickname"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://" + domain + "/authorize",
TokenURL: "https://" + domain + "/oauth/token",
},
}
// Getting the Code that we got from Auth0
code := c.Query("code")
// Exchanging the code for a token
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// Getting now the User information
client := conf.Client(oauth2.NoContext, token)
resp, err := client.Get("https://" + domain + "/userinfo")
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// Unmarshalling the JSON of the Profile
var profile map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&profile)
resp.Body.Close()
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
user := User{
Auth0: profile["user_id"].(string),
Name: profile["name"].(string),
Email: profile["email"].(string),
Picture: profile["picture"].(string),
}
// store user in database
user, err = userStore.SaveUser(user)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// store user in session
session := sessions.Default(c)
session.Set("user", user)
if err := session.Save(); err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Redirect(http.StatusFound, "/")
}