-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
288 lines (272 loc) · 7.23 KB
/
main.go
File metadata and controls
288 lines (272 loc) · 7.23 KB
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package main
import (
"bytes"
"embed"
_ "embed"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"net/mail"
"os"
"strings"
)
//go:embed templates
var templates embed.FS
//go:embed static
var staticFiles embed.FS
func validateEmail(email string) bool {
parsed, err := mail.ParseAddress(email)
return err == nil && parsed.Address == email
}
func getToken() (string, error) {
url := os.Getenv("LLDAP_URL") + "/auth/simple/login"
data := map[string]string{
"username": os.Getenv("LLDAP_USER"),
"password": os.Getenv("LLDAP_PASS"),
}
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
defer resp.Body.Close()
var res map[string]any
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return "", err
}
token, ok := res["token"].(string)
if !ok {
return "", fmt.Errorf("no token in response")
}
return token, nil
}
func graphqlQuery(query string, variables map[string]any) (map[string]any, error) {
token, err := getToken()
if err != nil {
return nil, err
}
url := os.Getenv("LLDAP_URL") + "/api/graphql"
data := map[string]any{
"query": query,
"variables": variables,
}
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var res map[string]any
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
return res, nil
}
func checkUserExists(username, email string) (bool, error) {
query := `
query($filters: RequestFilter!) {
users(filters: $filters) {
id
}
}
`
variables := map[string]any{
"filters": map[string]any{
"any": []any{
map[string]any{
"eq": map[string]string{
"field": "id",
"value": username,
},
},
map[string]any{
"eq": map[string]string{
"field": "email",
"value": email,
},
},
},
},
}
res, err := graphqlQuery(query, variables)
if err != nil {
return false, err
}
data, ok := res["data"].(map[string]any)
if !ok {
return false, fmt.Errorf("no data in response")
}
users, ok := data["users"].([]any)
if !ok {
return false, fmt.Errorf("no users in data")
}
return len(users) > 0, nil
}
func createUser(username, email string) error {
mutation := `
mutation($user: CreateUserInput!) {
createUser(user: $user) {
id
}
}
`
variables := map[string]any{
"user": map[string]any{
"id": username,
"email": email,
"displayName": username,
},
}
_, err := graphqlQuery(mutation, variables)
return err
}
func resetPassword(userId string) error {
url := os.Getenv("LLDAP_URL") + "/auth/reset/step1/" + userId
resp, err := http.Post(url, "application/json", bytes.NewBufferString(""))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("status %s", resp.Status)
}
return nil
}
func showError(w http.ResponseWriter, msg template.HTML) {
template, err := template.ParseFS(templates, "templates/base.html", "templates/error.html")
if err != nil {
log.Printf("Error while parsing template: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = template.ExecuteTemplate(w, "base.html", msg)
if err != nil {
log.Printf("Error while rendering template: %s", err)
return
}
}
func showSuccess(w http.ResponseWriter) {
template, err := template.ParseFS(templates, "templates/base.html", "templates/success.html")
if err != nil {
log.Printf("Error while parsing template: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = template.ExecuteTemplate(w, "base.html", nil)
if err != nil {
log.Printf("Error while rendering template: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
template, err := template.ParseFS(templates, "templates/base.html", "templates/form.html")
if err != nil {
log.Printf("Error while parsing template: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = template.ExecuteTemplate(w, "base.html", nil)
if err != nil {
log.Printf("Error while rendering template: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
case "POST":
if err := r.ParseForm(); err != nil {
showError(w, "Invalid form")
return
}
pali := strings.ToLower(strings.TrimSpace(r.FormValue("pali")))
if pali != "ni" {
showError(w, `Please answer the spam prevention question correctly to prevent spam. Notice that you must answer with just the <a href="https://sona.pona.la/wiki/Names">proper adjective</a>.`)
return
}
username := strings.TrimSpace(r.FormValue("username"))
email := strings.TrimSpace(r.FormValue("email"))
if username == "" || email == "" {
showError(w, "Username and email are required")
return
}
if strings.Contains(username, " ") {
showError(w, "Username may not contain spaces")
return
}
if !validateEmail(email) {
showError(w, "Invalid email format")
return
}
exists, err := checkUserExists(username, email)
if err != nil {
log.Printf("Error checking user: %v", err)
showError(w, "Internal Server Error\nPlease contact soko Ni using the link on the navigation bar.")
return
}
if exists {
showError(w, "Username or email is already reserved")
return
}
err = createUser(username, email)
if err != nil {
log.Printf("Error creating user: %v", err)
showError(w, "Internal Server Error\nPlease contact soko Ni using the link on the navigation bar.")
return
}
err = resetPassword(username)
if err != nil {
log.Printf("Error resetting password: %v", err)
showError(w, "Internal Server Error\nPlease contact soko Ni using the link on the navigation bar.")
return
}
showSuccess(w)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func main() {
// Ensure required environment variables are set
// Yes i know it could've been three more clear lines. DRY or something shut up man get a job.
requiredEnv := []string{"LLDAP_URL", "LLDAP_USER", "LLDAP_PASS"}
for _, env := range requiredEnv {
if os.Getenv(env) == "" {
log.Fatalf("Environment variable %s is required", env)
}
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
registerPath := os.Getenv("REGISTER_PATH")
if registerPath == "" {
registerPath = "/"
}
if !strings.HasPrefix(registerPath, "/") {
registerPath = "/" + registerPath
}
if registerPath != "/" && !strings.HasSuffix(registerPath, "/") {
registerPath += "/"
}
http.HandleFunc(registerPath, registerHandler)
http.Handle(registerPath+"static/", http.StripPrefix(
registerPath+"static/",
http.FileServer(http.FS(staticFiles)),
))
log.Printf("Starting server on http://0.0.0.0:%s%s", port, registerPath)
log.Fatal(http.ListenAndServe(":"+port, nil))
}