-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
discord.go
160 lines (118 loc) · 4 KB
/
discord.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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/getsentry/sentry-go"
"github.com/hymkor/go-lazy"
"github.com/ravener/discord-oauth2"
"golang.org/x/oauth2"
"io/ioutil"
"net/http"
"os"
)
var discordOAuth = lazy.New(func() *oauth2.Config {
return &oauth2.Config{
ClientID: os.Getenv("DISCORD_OAUTH_CLIENT_ID"),
ClientSecret: os.Getenv("DISCORD_OAUTH_CLIENT_SECRET"),
Endpoint: discord.Endpoint,
RedirectURL: os.Getenv("BASE_URL") + "/oauth/discord/redirect",
Scopes: []string{discord.ScopeIdentify},
}
})
func (app *Application) DiscordOAuthInitiator(w http.ResponseWriter, r *http.Request) {
state := RandomString(16)
cookie, err := app.secureCookie.Encode("oauth_discord", state)
if err != nil {
http.Error(w, "failed to encode", http.StatusInternalServerError)
return
}
w.Header().Set("Set-Cookie", "pomu_oauth="+cookie+"; Path=/; Max-Age=300; HttpOnly")
url := discordOAuth.Value().AuthCodeURL(state)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func (app *Application) DiscordOAuthRedirect(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("pomu_oauth")
if err != nil {
http.Error(w, "no csrf token", http.StatusBadRequest)
return
}
w.Header().Set("Set-Cookie", "pomu_oauth=deleted; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT")
var csrfToken string
err = app.secureCookie.Decode("oauth_discord", cookie.Value, &csrfToken)
if err != nil {
http.Error(w, "failed to decode csrf token", http.StatusInternalServerError)
return
}
state := r.FormValue("state")
if csrfToken != state {
http.Error(w, "csrf token mismatch", http.StatusBadRequest)
return
}
token, err := discordOAuth.Value().Exchange(context.Background(), r.FormValue("code"))
if err != nil {
http.Error(w, "failed to exchange token", http.StatusBadGateway)
sentry.CaptureException(err)
return
}
id, name, avatarUrl, err := resolveUserWithDiscordToken(token)
if err != nil {
http.Error(w, "failed to get discord info", http.StatusBadGateway)
sentry.CaptureException(err)
return
}
redirectUrl, err := ValidateOrCreateUser(id, name, avatarUrl, ProviderDiscord, app.db)
if err != nil {
http.Error(w, "failed to get or create user", http.StatusInternalServerError)
sentry.CaptureException(err)
return
}
session, err := StartSession(id, ProviderDiscord, r.Header.Get("CF-IPCountry"), app.db)
if err != nil {
http.Error(w, "failed to start session", http.StatusInternalServerError)
sentry.CaptureException(err)
return
}
encodedCookie, err := app.secureCookie.Encode("session", session)
if err != nil {
http.Error(w, "failed to encode cookie", http.StatusInternalServerError)
sentry.CaptureException(err)
return
}
// 604'800 = a week
w.Header().Set("Set-Cookie", "pomu="+encodedCookie+"; Path=/; Max-Age=604800")
http.Redirect(w, r, redirectUrl, http.StatusTemporaryRedirect)
}
func resolveUserWithDiscordToken(token *oauth2.Token) (string, string, string, error) {
response, err := discordOAuth.Value().Client(context.Background(), token).Get("https://discord.com/api/users/@me")
if err != nil || response.StatusCode != 200 {
return "", "", "", err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", "", "", err
}
var responses map[string]any
if err := json.Unmarshal(body, &responses); err != nil {
return "", "", "", err
}
id := responses["id"].(string)
username := responses["username"].(string)
discriminator := responses["discriminator"].(string)
var name string
// special handling for discord username update may/june 2023: https://discord.com/blog/usernames
if discriminator == "0" {
name = username
} else {
name = fmt.Sprintf("%s#%s", username, discriminator)
}
var avatarUrl string
switch avatarHash := responses["avatar"].(type) {
case string:
avatarUrl = fmt.Sprintf("https://cdn.discordapp.com/avatars/%s/%s.png", id, avatarHash)
default:
avatarUrl = "https://cdn.discordapp.com/embed/avatars/0.png"
}
return id, name, avatarUrl, nil
}