|
| 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 | +} |
0 commit comments