forked from code-golf/code-golf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.go
110 lines (95 loc) · 2.48 KB
/
oauth.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
package oauth
import (
"net/url"
"os"
"strings"
"github.com/bwmarrin/discordgo"
"github.com/code-golf/code-golf/db"
"github.com/code-golf/code-golf/null"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/gitlab"
"golang.org/x/oauth2/stackoverflow"
)
type Config struct {
oauth2.Config
Name, UserEndpoint string
}
type Connection struct {
Connection, Username string
Discriminator null.Int
ID int
Public bool
}
var Providers = map[string]*Config{
// https://discord.com/developers/applications
"discord": {
Name: "Discord",
UserEndpoint: discordgo.EndpointUser("@me"),
Config: oauth2.Config{
Scopes: []string{"identify"},
Endpoint: oauth2.Endpoint{
AuthStyle: oauth2.AuthStyleInParams,
AuthURL: discordgo.EndpointOauth2 + "authorize",
TokenURL: discordgo.EndpointOauth2 + "token",
},
},
},
// https://github.com/settings/developers
"github": {
Name: "GitHub",
Config: oauth2.Config{Endpoint: github.Endpoint},
},
// https://gitlab.com/-/profile/applications
"gitlab": {
Name: "GitLab",
UserEndpoint: "https://gitlab.com/oauth/userinfo",
Config: oauth2.Config{
Endpoint: gitlab.Endpoint,
Scopes: []string{"openid"},
},
},
// https://stackapps.com/apps/oauth
"stack-overflow": {
Name: "Stack Overflow",
Config: oauth2.Config{Endpoint: stackoverflow.Endpoint},
UserEndpoint: "https://api.stackexchange.com/me?site=stackoverflow",
},
}
func init() {
host := "code.golf"
if _, dev := os.LookupEnv("DEV"); dev {
host = "localhost"
}
for id, config := range Providers {
prefix := strings.ReplaceAll(strings.ToUpper(id), "-", "_")
config.ClientID = os.Getenv(prefix + "_CLIENT_ID")
config.ClientSecret = os.Getenv(prefix + "_CLIENT_SECRET")
config.RedirectURL = "https://" + host + "/golfer/connect/" + id
// Add a key to UserEndpoint if we have one.
if key := os.Getenv(prefix + "_KEY"); key != "" {
u, err := url.Parse(config.UserEndpoint)
if err != nil {
panic(err)
}
q := u.Query()
q.Set("key", key)
u.RawQuery = q.Encode()
config.UserEndpoint = u.String()
}
}
}
func GetConnections(db db.Queryable, golferID int, onlyPublic bool) (c []Connection) {
if err := db.Select(
&c,
` SELECT connection, discriminator, id, public, username
FROM connections
WHERE user_id = $1 AND public IN (true, $2)
ORDER BY connection`,
golferID,
onlyPublic,
); err != nil {
panic(err)
}
return
}