This repository has been archived by the owner on Sep 8, 2023. It is now read-only.
forked from disgoorg/disgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
126 lines (111 loc) · 3.44 KB
/
example.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"fmt"
"math/rand"
"net/http"
"os"
"time"
"github.com/disgoorg/json"
"github.com/disgoorg/log"
"github.com/disgoorg/snowflake/v2"
"github.com/sabafly/disgo"
"github.com/sabafly/disgo/discord"
"github.com/sabafly/disgo/oauth2"
"github.com/sabafly/disgo/rest"
)
var (
letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
clientID = snowflake.GetEnv("client_id")
clientSecret = os.Getenv("client_secret")
baseURL = os.Getenv("base_url")
logger = log.Default()
httpClient = http.DefaultClient
client oauth2.Client
sessions map[string]oauth2.Session
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
logger.SetLevel(log.LevelDebug)
logger.Info("starting example...")
logger.Infof("disgo %s", disgo.Version)
client = oauth2.New(clientID, clientSecret, oauth2.WithLogger(logger), oauth2.WithRestClientConfigOpts(rest.WithHTTPClient(httpClient)))
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
mux.HandleFunc("/login", handleLogin)
mux.HandleFunc("/trylogin", handleTryLogin)
_ = http.ListenAndServe(":6969", mux)
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
var body string
cookie, err := r.Cookie("token")
if err == nil {
session, ok := sessions[cookie.Value]
if ok {
var user *discord.OAuth2User
user, err = client.GetUser(session)
if err != nil {
writeError(w, "error while getting user data", err)
return
}
var userJSON []byte
userJSON, err = json.MarshalIndent(user, "<br />", " ")
if err != nil {
writeError(w, "error while formatting user data", err)
return
}
var connections []discord.Connection
connections, err = client.GetConnections(session)
if err != nil {
writeError(w, "error while getting connections data", err)
return
}
var connectionsJSON []byte
connectionsJSON, err = json.MarshalIndent(connections, "<br />", " ")
if err != nil {
writeError(w, "error while formatting connections data", err)
return
}
body = fmt.Sprintf("user:<br />%s<br />connections: <br />%s", userJSON, connectionsJSON)
}
}
if body == "" {
body = `<button><a href="/login">login</a></button>`
}
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(body))
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, client.GenerateAuthorizationURL(baseURL+"/trylogin", discord.PermissionsNone, 0, false, discord.OAuth2ScopeIdentify, discord.OAuth2ScopeGuilds, discord.OAuth2ScopeEmail, discord.OAuth2ScopeConnections, discord.OAuth2ScopeWebhookIncoming), http.StatusSeeOther)
}
func handleTryLogin(w http.ResponseWriter, r *http.Request) {
var (
query = r.URL.Query()
code = query.Get("code")
state = query.Get("state")
)
if code != "" && state != "" {
identifier := randStr(32)
session, _, err := client.StartSession(code, state)
if err != nil {
writeError(w, "error while starting session", err)
return
}
sessions[identifier] = session
http.SetCookie(w, &http.Cookie{Name: "token", Value: identifier})
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
func writeError(w http.ResponseWriter, text string, err error) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(text + ": " + err.Error()))
}
func randStr(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}