-
Notifications
You must be signed in to change notification settings - Fork 0
/
Authentification_example.go
300 lines (255 loc) · 7.92 KB
/
Authentification_example.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/edgedb/edgedb-go"
"github.com/gofiber/fiber/v2"
)
type DiscoveryDocument struct {
UserInfoEndpoint string `json:"userinfo_endpoint"`
}
type UserProfile struct {
Email string `json:"email"`
Name string `json:"name"`
AvatarGitHub string `json:"avatar_url"`
AvatarGoogle string `json:"picture"`
}
type TokenResponse struct {
AuthToken string `json:"auth_token"`
IdentityID string `json:"identity_id"`
ProviderToken string `json:"provider_token"`
}
func getGoogleUserProfile(providerToken string) (string, string, string) {
// Fetch the discovery document
resp, err := http.Get("https://accounts.google.com/.well-known/openid-configuration")
if err != nil {
fmt.Println("Error fetching discovery document")
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Println("Error fetching discovery document")
panic(resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading discovery document")
panic(err)
}
var discoveryDocument DiscoveryDocument
if err := json.Unmarshal(body, &discoveryDocument); err != nil {
fmt.Println("Error unmarshalling discovery document")
panic(err)
}
// Fetch the user profile
req, err := http.NewRequest("GET", discoveryDocument.UserInfoEndpoint, nil)
if err != nil {
fmt.Println("Error fetching user profile")
panic(err)
}
req.Header.Set("Authorization", "Bearer "+providerToken)
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err = client.Do(req)
if err != nil {
fmt.Println("Error fetching user profile")
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic("Error fetching user profile")
}
body, err = io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading user profile")
panic(err)
}
var userProfile UserProfile
if err := json.Unmarshal(body, &userProfile); err != nil {
fmt.Println("Error unmarshalling user profile")
panic(err)
}
return userProfile.Email, userProfile.Name, userProfile.AvatarGoogle
}
func getGitHubUserProfile(providerToken string) (string, string, string) {
// Create the request to fetch the user profile
req, err := http.NewRequest("GET", "https://api.github.com/user", nil)
if err != nil {
fmt.Println("failed to create request: user profile")
panic(err)
}
req.Header.Set("Authorization", "Bearer "+providerToken)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("failed to execute request")
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Println("failed to fetch user profile: status code")
panic(resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("failed to read response body")
panic(err)
}
var userProfile UserProfile
if err := json.Unmarshal(body, &userProfile); err != nil {
fmt.Println("failed to unmarshal user profile")
panic(err)
}
return userProfile.Email, userProfile.Name, userProfile.AvatarGitHub
}
func generatePKCE() (string, string) {
verifier_source := make([]byte, 32)
_, err := rand.Read(verifier_source)
if err != nil {
fmt.Println("failed to generate PKCE")
panic(err)
}
verifier := base64.RawURLEncoding.EncodeToString(verifier_source)
challenge := sha256.Sum256([]byte(verifier))
return verifier, base64.RawURLEncoding.EncodeToString(challenge[:])
}
func handleUiSignIn(c *fiber.Ctx) error {
verifier, challenge := generatePKCE()
c.Cookie(&fiber.Cookie{
Name: "my-cookie-name-verifier",
Value: verifier,
HTTPOnly: true,
Path: "/",
Secure: true,
})
return c.Redirect(fmt.Sprintf("%s/ui/signup?challenge=%s", os.Getenv("EDGEDB_AUTH_BASE_URL"), challenge), fiber.StatusTemporaryRedirect)
}
func handleCallbackSignup(c *fiber.Ctx) error {
code := c.Query("code")
if code == "" {
err := c.Query("error")
fmt.Println("OAuth callback is missing 'code'. OAuth provider responded with error")
panic(err)
}
verifier := c.Cookies("my-cookie-name-verifier", "")
if verifier == "" {
panic("Could not find 'verifier' in the cookie store. Is this the same user agent/browser that started the authorization flow?")
}
codeExchangeURL := fmt.Sprintf("%s/token?code=%s&verifier=%s", os.Getenv("EDGEDB_AUTH_BASE_URL"), code, verifier)
resp, err := http.Get(codeExchangeURL)
if err != nil {
fmt.Println("Error exchanging code for access token")
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != fiber.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Println("Error exchanging code for access token")
panic(string(body))
}
var tokenResponse TokenResponse
err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
if err != nil {
fmt.Println("Error decoding auth server response")
panic(err)
}
c.Cookie(&fiber.Cookie{
Name: "my-cookie-name-auth-token",
Value: tokenResponse.AuthToken,
HTTPOnly: true,
Path: "/",
Secure: true,
})
// Get the issuer of the identity
var identity Identity
identityUUID, err := edgedb.ParseUUID(tokenResponse.IdentityID)
if err != nil {
fmt.Println("Error parsing UUID")
panic(err)
}
err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": c.Cookies("jade-edgedb-auth-token")}).QuerySingle(edgeCtx, `
SELECT ext::auth::Identity {
issuer
} FILTER .id = <uuid>$0
`, &identity, identityUUID)
if err != nil {
fmt.Println("Error fetching identity")
panic(err)
}
var (
providerEmail string
providerName string
providerAvatar string
)
// Get the email and name from the provider
if identity.Issuer == "https://accounts.google.com" {
providerEmail, providerName, providerAvatar = getGoogleUserProfile(tokenResponse.ProviderToken)
} else if identity.Issuer == "https://github.com" {
providerEmail, providerName, providerAvatar = getGitHubUserProfile(tokenResponse.ProviderToken)
}
// Here you handle User creation. I put this as an example
err = edgeGlobalClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": tokenResponse.AuthToken}).Execute(edgeCtx, `
INSERT User {
email := <str>$0,
name := <str>$1,
avatar := <str>$2,
identity := (SELECT ext::auth::Identity FILTER .id = <uuid>$3)
}
`, providerEmail, providerName, providerAvatar, identityUUID)
if err != nil {
fmt.Println("Error creating user")
panic(err)
}
return c.Redirect("/", fiber.StatusPermanentRedirect)
}
func handleCallback(c *fiber.Ctx) error {
code := c.Query("code")
if code == "" {
err := c.Query("error")
fmt.Println("OAuth callback is missing 'code'. OAuth provider responded with error")
panic(err)
}
verifier := c.Cookies("my-cookie-name-verifier", "")
if verifier == "" {
panic("Could not find 'verifier' in the cookie store. Is this the same user agent/browser that started the authorization flow?")
}
codeExchangeURL := fmt.Sprintf("%s/token?code=%s&verifier=%s", os.Getenv("EDGEDB_AUTH_BASE_URL"), code, verifier)
resp, err := http.Get(codeExchangeURL)
if err != nil {
fmt.Println("Error exchanging code for access token")
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != fiber.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Println("Error exchanging code for access token")
panic(string(body))
}
var tokenResponse TokenResponse
err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
if err != nil {
fmt.Println("Error decoding auth server response")
panic(err)
}
c.Cookie(&fiber.Cookie{
Name: "my-cookie-name-auth-token",
Value: tokenResponse.AuthToken,
HTTPOnly: true,
Path: "/",
Secure: true,
SameSite: "Strict",
})
return c.Redirect("/", fiber.StatusPermanentRedirect)
}
func handleSignOut(c *fiber.Ctx) error {
c.ClearCookie("my-cookie-name-auth-token")
return c.Redirect("/", fiber.StatusTemporaryRedirect)
}