Skip to content

Commit ded1066

Browse files
committed
Adds Discord provider.
Fields not in the goth.User struct disabled.
1 parent 75b41c4 commit ded1066

File tree

4 files changed

+335
-0
lines changed

4 files changed

+335
-0
lines changed

providers/discord/discord.go

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

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)