-
Notifications
You must be signed in to change notification settings - Fork 0
/
providers.go
104 lines (88 loc) · 2.3 KB
/
providers.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
package main
import (
"fmt"
"net/http"
"net/url"
"os"
"time"
)
const (
timestampFormat string = time.UnixDate
timestampLayout string = "Mon Jan 2 15:04:05 CDT 2006"
outputCookieDelim string = "---"
)
type OAuthProvider interface {
Name() ProviderName
Redirect(w http.ResponseWriter, r *http.Request)
}
func NewOAuthProvider(providerName ProviderName) OAuthProvider {
switch providerName {
case ProviderNameDiscord:
return DiscordProvider{}
case ProviderNameGoogle:
return GoogleProvider{}
}
return nil
}
type DiscordProvider struct{}
func (dp DiscordProvider) Name() ProviderName {
return ProviderNameDiscord
}
func (dp DiscordProvider) Redirect(w http.ResponseWriter, r *http.Request) {
var (
clientID = os.Getenv(EnvDiscordClientID)
protocol = os.Getenv(EnvProtocol)
hostname = os.Getenv(EnvHostname)
redirectUri = url.QueryEscape(fmt.Sprintf("%s//%s/callback/discord", protocol, hostname))
)
url := fmt.Sprintf(
"https://discord.com/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=email+identify",
clientID,
redirectUri,
)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func (dpr DiscordProviderResp) ToSubscriber(emailListID string) Subscriber {
return Subscriber{
ID: NewUUID(),
EmailListID: emailListID,
Name: dpr.Username,
EmailAddr: dpr.Email,
}
}
func (dpr DiscordProviderResp) Result() ProviderResult {
return ProviderResult{
Name: dpr.Username,
EmailAddr: dpr.Email,
}
}
type GoogleProvider struct{}
func (gp GoogleProvider) Name() ProviderName {
return ProviderNameGoogle
}
func (gp GoogleProvider) Redirect(w http.ResponseWriter, r *http.Request) {
url := GoogleConfig().AuthCodeURL(googleOAuthStateStr())
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func (gpr GoogleProviderResp) ToSubscriber(emailListID string) Subscriber {
return Subscriber{
ID: NewUUID(),
EmailListID: emailListID,
Name: gpr.Name,
EmailAddr: gpr.Email,
}
}
func (gpr GoogleProviderResp) Result() ProviderResult {
return ProviderResult{
Name: gpr.Name,
EmailAddr: gpr.Email,
}
}
func ToProviderName(str string) (ProviderName, error) {
for _, pn := range providerNames {
if string(pn) == str {
return pn, nil
}
}
return "", fmt.Errorf("invalid ProviderName %s", str)
}