Skip to content

Commit bde8bf2

Browse files
authored
Merge pull request markbates#105 from VagantemNumen/discord-oauth2
Adds Discord provider.
2 parents 75b41c4 + 83e325d commit bde8bf2

File tree

5 files changed

+347
-0
lines changed

5 files changed

+347
-0
lines changed

examples/main.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"github.com/markbates/goth/providers/dailymotion"
1919
"github.com/markbates/goth/providers/deezer"
2020
"github.com/markbates/goth/providers/digitalocean"
21+
"github.com/markbates/goth/providers/discord"
2122
"github.com/markbates/goth/providers/dropbox"
2223
"github.com/markbates/goth/providers/facebook"
2324
"github.com/markbates/goth/providers/fitbit"
@@ -90,6 +91,7 @@ func main() {
9091
gitlab.New(os.Getenv("GITLAB_KEY"), os.Getenv("GITLAB_SECRET"), "http://localhost:3000/auth/gitlab/callback"),
9192
dailymotion.New(os.Getenv("DAILYMOTION_KEY"), os.Getenv("DAILYMOTION_SECRET"), "http://localhost:3000/auth/dailymotion/callback", "email"),
9293
deezer.New(os.Getenv("DEEZER_KEY"), os.Getenv("DEEZER_SECRET"), "http://localhost:3000/auth/deezer/callback", "email"),
94+
discord.New(os.Getenv("DISCORD_KEY"), os.Getenv("DISCORD_SECRET"), "http://localhost:3000/auth/discord/callback", discord.ScopeIdentify, discord.ScopeEmail),
9395
)
9496

9597
m := make(map[string]string)
@@ -99,6 +101,7 @@ func main() {
99101
m["dailymotion"] = "Dailymotion"
100102
m["deezer"] = "Deezer"
101103
m["digitalocean"] = "Digital Ocean"
104+
m["discord"] = "Discord"
102105
m["dropbox"] = "Dropbox"
103106
m["facebook"] = "Facebook"
104107
m["fitbit"] = "Fitbit"

providers/discord/discord.go

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
// Package discord implements the OAuth2 protocol for authenticating users through Discord.
2+
// This package can be used as a reference implementation of an OAuth2 provider for Discord.
3+
package discord
4+
5+
import (
6+
"bytes"
7+
"encoding/json"
8+
"github.com/markbates/goth"
9+
"golang.org/x/oauth2"
10+
"io"
11+
"io/ioutil"
12+
13+
"net/http"
14+
)
15+
16+
const (
17+
authURL string = "https://discordapp.com/api/oauth2/authorize"
18+
tokenURL string = "https://discordapp.com/api/oauth2/token"
19+
userEndpoint string = "https://discordapp.com/api/users/@me"
20+
)
21+
22+
const (
23+
// allows /users/@me without email
24+
ScopeIdentify string = "identify"
25+
// enables /users/@me to return an email
26+
ScopeEmail string = "email"
27+
// allows /users/@me/connections to return linked Twitch and YouTube accounts
28+
ScopeConnections string = "connections"
29+
// allows /users/@me/guilds to return basic information about all of a user's guilds
30+
ScopeGuilds string = "guilds"
31+
// allows /invites/{invite.id} to be used for joining a user's guild
32+
ScopeJoinGuild string = "guilds.join"
33+
// allows your app to join users to a group dm
34+
ScopeGroupDMjoin string = "gdm.join"
35+
// for oauth2 bots, this puts the bot in the user's selected guild by default
36+
ScopeBot string = "bot"
37+
// this generates a webhook that is returned in the oauth token response for authorization code grants
38+
ScopeWebhook string = "webhook.incoming"
39+
)
40+
41+
// New creates a new Discord provider, and sets up important connection details.
42+
// You should always call `discord.New` to get a new Provider. Never try to create
43+
// one manually.
44+
func New(clientKey string, secret string, callbackURL string, scopes ...string) *Provider {
45+
p := &Provider{
46+
ClientKey: clientKey,
47+
Secret: secret,
48+
CallbackURL: callbackURL,
49+
}
50+
p.config = newConfig(p, scopes)
51+
return p
52+
}
53+
54+
// Provider is the implementation of `goth.Provider` for accessing Discord
55+
type Provider struct {
56+
ClientKey string
57+
Secret string
58+
CallbackURL string
59+
config *oauth2.Config
60+
}
61+
62+
// Name gets the name used to retrieve this provider.
63+
func (p *Provider) Name() string {
64+
return "discord"
65+
}
66+
67+
// Debug is no-op for the Discord package.
68+
func (p *Provider) Debug(debug bool) {}
69+
70+
// BeginAuth asks Discord for an authentication end-point.
71+
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
72+
73+
url := p.config.AuthCodeURL(state, oauth2.AccessTypeOnline)
74+
75+
s := &Session{
76+
AuthURL: url,
77+
}
78+
return s, nil
79+
}
80+
81+
// FetchUser will go to Discord and access basic info about the user.
82+
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
83+
84+
s := session.(*Session)
85+
86+
user := goth.User{
87+
AccessToken: s.AccessToken,
88+
Provider: p.Name(),
89+
RefreshToken: s.RefreshToken,
90+
ExpiresAt: s.ExpiresAt,
91+
}
92+
93+
req, err := http.NewRequest("GET", userEndpoint, nil)
94+
if err != nil {
95+
return user, err
96+
}
97+
req.Header.Set("Accept", "application/json")
98+
req.Header.Set("Authorization", "Bearer "+s.AccessToken)
99+
resp, err := http.DefaultClient.Do(req)
100+
if err != nil {
101+
if resp != nil {
102+
resp.Body.Close()
103+
}
104+
return user, err
105+
}
106+
defer resp.Body.Close()
107+
108+
bits, err := ioutil.ReadAll(resp.Body)
109+
if err != nil {
110+
return user, err
111+
}
112+
113+
err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData)
114+
if err != nil {
115+
return user, err
116+
}
117+
118+
err = userFromReader(bytes.NewReader(bits), &user)
119+
if err != nil {
120+
return user, err
121+
}
122+
123+
return user, err
124+
}
125+
126+
func userFromReader(r io.Reader, user *goth.User) error {
127+
u := struct {
128+
Name string `json:"username"`
129+
Email string `json:"email"`
130+
AvatarID string `json:"avatar"`
131+
MFAEnabled bool `json:"mfa_enabled"`
132+
Discriminator string `json:"discriminator"`
133+
Verified bool `json:"verified"`
134+
ID string `json:"id"`
135+
}{}
136+
137+
err := json.NewDecoder(r).Decode(&u)
138+
if err != nil {
139+
return err
140+
}
141+
142+
user.Name = u.Name
143+
user.Email = u.Email
144+
user.AvatarURL = "https://discordapp.com/api/users/" + u.ID + "/avatars/" + u.AvatarID + ".jpg"
145+
user.UserID = u.ID
146+
147+
return nil
148+
}
149+
150+
func newConfig(p *Provider, scopes []string) *oauth2.Config {
151+
c := &oauth2.Config{
152+
ClientID: p.ClientKey,
153+
ClientSecret: p.Secret,
154+
RedirectURL: p.CallbackURL,
155+
Endpoint: oauth2.Endpoint{
156+
AuthURL: authURL,
157+
TokenURL: tokenURL,
158+
},
159+
Scopes: []string{},
160+
}
161+
162+
if len(scopes) > 0 {
163+
for _, scope := range scopes {
164+
c.Scopes = append(c.Scopes, scope)
165+
}
166+
} else {
167+
c.Scopes = []string{ScopeIdentify}
168+
}
169+
170+
return c
171+
}
172+
173+
//RefreshTokenAvailable refresh token is provided by auth provider or not
174+
func (p *Provider) RefreshTokenAvailable() bool {
175+
return true
176+
}
177+
178+
//RefreshToken get new access token based on the refresh token
179+
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
180+
token := &oauth2.Token{RefreshToken: refreshToken}
181+
ts := p.config.TokenSource(oauth2.NoContext, token)
182+
newToken, err := ts.Token()
183+
if err != nil {
184+
return nil, err
185+
}
186+
return newToken, err
187+
}

providers/discord/discord_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package discord
2+
3+
import (
4+
"os"
5+
"testing"
6+
7+
"github.com/markbates/goth"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func provider() *Provider {
12+
return New(os.Getenv("DISCORD_KEY"),
13+
os.Getenv("DISCORD_SECRET"), "/foo", "user")
14+
}
15+
16+
func Test_New(t *testing.T) {
17+
t.Parallel()
18+
a := assert.New(t)
19+
p := provider()
20+
21+
a.Equal(p.ClientKey, os.Getenv("DISCORD_KEY"))
22+
a.Equal(p.Secret, os.Getenv("DISCORD_SECRET"))
23+
a.Equal(p.CallbackURL, "/foo")
24+
}
25+
26+
func Test_ImplementsProvider(t *testing.T) {
27+
t.Parallel()
28+
a := assert.New(t)
29+
a.Implements((*goth.Provider)(nil), provider())
30+
}
31+
32+
func Test_BeginAuth(t *testing.T) {
33+
t.Parallel()
34+
a := assert.New(t)
35+
36+
p := provider()
37+
session, err := p.BeginAuth("test_state")
38+
s := session.(*Session)
39+
a.NoError(err)
40+
a.Contains(s.AuthURL, "discordapp.com/api/oauth2/authorize")
41+
}
42+
43+
func Test_SessionFromJSON(t *testing.T) {
44+
t.Parallel()
45+
a := assert.New(t)
46+
47+
p := provider()
48+
session, err := p.UnmarshalSession(`{"AuthURL":"https://discordapp.com/api/oauth2/authorize", "AccessToken":"1234567890"}`)
49+
a.NoError(err)
50+
51+
s := session.(*Session)
52+
a.Equal(s.AuthURL, "https://discordapp.com/api/oauth2/authorize")
53+
a.Equal(s.AccessToken, "1234567890")
54+
}

providers/discord/session.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package discord
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"github.com/markbates/goth"
7+
"golang.org/x/oauth2"
8+
"strings"
9+
"time"
10+
)
11+
12+
// Session stores data during the auth process with Discord
13+
type Session struct {
14+
AuthURL string
15+
AccessToken string
16+
RefreshToken string
17+
ExpiresAt time.Time
18+
}
19+
20+
// GetAuthURL will return the URL set by calling the `BeginAuth` function on
21+
// the Discord provider.
22+
func (s Session) GetAuthURL() (string, error) {
23+
if s.AuthURL == "" {
24+
return "", errors.New("Discord: An AuthURL has not been set")
25+
}
26+
return s.AuthURL, nil
27+
}
28+
29+
// Authorize completes the authorization with Discord and returns the access
30+
// token to be stored for future use.
31+
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
32+
p := provider.(*Provider)
33+
token, err := p.config.Exchange(oauth2.NoContext, params.Get("code"))
34+
if err != nil {
35+
return "", err
36+
}
37+
38+
if !token.Valid() {
39+
return "", errors.New("Invalid token received from provider")
40+
}
41+
42+
s.AccessToken = token.AccessToken
43+
s.RefreshToken = token.RefreshToken
44+
s.ExpiresAt = token.Expiry
45+
return token.AccessToken, err
46+
}
47+
48+
// Marshal marshals a session into a JSON string.
49+
func (s Session) Marshal() string {
50+
j, _ := json.Marshal(s)
51+
return string(j)
52+
}
53+
54+
// String is equivalent to Marshal. It returns a JSON representation of the
55+
// of the session.
56+
func (s Session) String() string {
57+
return s.Marshal()
58+
}
59+
60+
// UnmarshalSession will unmarshal a JSON string into a session.
61+
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
62+
s := &Session{}
63+
err := json.NewDecoder(strings.NewReader(data)).Decode(s)
64+
return s, err
65+
}

providers/discord/session_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package discord
2+
3+
import (
4+
"testing"
5+
6+
"github.com/markbates/goth"
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func Test_ImplementsSession(t *testing.T) {
11+
t.Parallel()
12+
a := assert.New(t)
13+
s := &Session{}
14+
a.Implements((*goth.Session)(nil), s)
15+
}
16+
17+
func Test_GetAuthURL(t *testing.T) {
18+
t.Parallel()
19+
a := assert.New(t)
20+
s := &Session{}
21+
22+
_, err := s.GetAuthURL()
23+
a.Error(err)
24+
25+
s.AuthURL = "/foo"
26+
27+
url, _ := s.GetAuthURL()
28+
a.Equal(url, "/foo")
29+
}
30+
31+
func Test_ToJSON(t *testing.T) {
32+
t.Parallel()
33+
a := assert.New(t)
34+
s := &Session{}
35+
36+
data := s.Marshal()
37+
a.Equal(data, `{"AuthURL":"","AccessToken":"","RefreshToken":"","ExpiresAt":"0001-01-01T00:00:00Z"}`)
38+
}

0 commit comments

Comments
 (0)