-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
555 lines (468 loc) · 14.8 KB
/
main.go
File metadata and controls
555 lines (468 loc) · 14.8 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/likexian/whois"
"google.golang.org/api/idtoken"
"github.com/pquerna/otp/totp"
"github.com/rs/cors"
"github.com/joho/godotenv"
)
const COOKIE_DOMAIN = ".metakgp.org"
var (
ErrJwtSecretKeyNotFound = errors.New("ERROR: JWT SECRET KEY NOT FOUND")
ErrJwtTokenExpired = errors.New("ERROR: JWT TOKEN EXPIRED")
ErrJwtTokenInvalid = errors.New("ERROR: JWT TOKEN INVALID")
usersMap map[string]*User = make(map[string]*User)
)
type LoginJwtFields struct {
Email string `json:"email"`
}
type LoginJwtClaims struct {
LoginJwtFields
jwt.RegisteredClaims
}
type User struct {
Email string `json:"email"`
Secret string `json:"secret"`
LastUsed int64 `json:"last_used"`
}
type OtpResponse struct {
Email string `json:"email"`
OtpStatus bool `json:"otp_status"`
Timestamp int `json:"timestamp"`
}
type responseRecorder struct {
http.ResponseWriter
status int
size int
}
func (r *responseRecorder) WriteHeader(statusCode int) {
r.status = statusCode
r.ResponseWriter.WriteHeader(statusCode)
}
func LoggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
recorder := &responseRecorder{w, http.StatusOK, 0}
next.ServeHTTP(recorder, r)
log.Printf("INFO:\t%s - %q %s %d %s\n", r.Header.Get("X-Real-IP"), r.Method, r.RequestURI, recorder.status, http.StatusText(recorder.status))
})
}
func getJwtKey() (string, error) {
jwtKey := os.Getenv("JWT_SECRET_KEY")
if jwtKey == "" {
return "", ErrJwtSecretKeyNotFound
}
return jwtKey, nil
}
func jwtKeyFunc(*jwt.Token) (interface{}, error) {
key, err := getJwtKey()
if err != nil {
return nil, err
}
return []byte(key), err
}
// isDevelopmentMode returns true when DEVELOPMENT_MODE env var is set to a truthy value.
// Accepted truthy values (case-insensitive): true
// Any other value (including empty / unset) returns false (production mode).
func isDevelopmentMode() bool {
val := strings.ToLower(strings.TrimSpace(os.Getenv("DEVELOPMENT_MODE")))
return val == "true"
}
func isAllowedInstituteEmail(email string) bool {
email = strings.ToLower(strings.TrimSpace(email))
return strings.HasSuffix(email, "@kgpian.iitkgp.ac.in") || strings.HasSuffix(email, "@iitkgp.ac.in")
}
func issueLoginCookie(res http.ResponseWriter, email string) error {
signingKey, err := getJwtKey()
if err != nil {
return err
}
expiryDays, err := strconv.Atoi(os.Getenv("JWT_EXPIRY_DAYS"))
if err != nil || expiryDays < 1 { // keep 1 day as minimum valid period
fmt.Println("Invalid JWT_EXPIRY_DAYS env set. Defaulting to 90 days (3 months)")
expiryDays = 90 // Default to 90 days (3 months)
}
issueTime := time.Now()
expiryTime := issueTime.AddDate(0, 0, expiryDays)
claims := &LoginJwtClaims{
LoginJwtFields: LoginJwtFields{Email: email},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(issueTime),
ExpiresAt: jwt.NewNumericDate(expiryTime),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(signingKey))
if err != nil {
return err
}
// Cookie configuration adapts to development mode to simplify local testing.
dev := isDevelopmentMode()
cookieDomain := COOKIE_DOMAIN
secureCookie := true
sameSiteMode := http.SameSiteNoneMode
if dev {
// In development we typically run on http://localhost so Secure cookies would be dropped by browsers.
cookieDomain = "localhost"
secureCookie = false
// Lax prevents most CSRF while still allowing form navigations; suitable for local dev.
sameSiteMode = http.SameSiteLaxMode
}
cookie := http.Cookie{
Name: "heimdall",
Value: tokenString,
Expires: expiryTime,
HttpOnly: true,
Secure: secureCookie,
SameSite: sameSiteMode,
Path: "/",
Domain: cookieDomain,
}
http.SetCookie(res, &cookie)
return nil
}
func clearLoginCookie(res http.ResponseWriter) {
dev := isDevelopmentMode()
cookieDomain := COOKIE_DOMAIN
secureCookie := true
sameSiteMode := http.SameSiteNoneMode
if dev {
cookieDomain = "localhost"
secureCookie = false
sameSiteMode = http.SameSiteLaxMode
}
// To delete a cookie reliably, set MaxAge < 0 and an Expires date in the past.
cookie := http.Cookie{
Name: "heimdall",
Value: "",
Expires: time.Unix(0, 0),
MaxAge: -1,
HttpOnly: true,
Secure: secureCookie,
SameSite: sameSiteMode,
Path: "/",
Domain: cookieDomain,
}
http.SetCookie(res, &cookie)
}
func generateOtp(user User) (bool, error) {
validPeriod, err := strconv.Atoi(os.Getenv("OTP_VALIDITY_PERIOD"))
if err != nil || validPeriod < 30 { // keep 30s as minimum valid period
fmt.Println("Invalid OTP_VALIDITY_PERIOD env set. Defaulting to 600 seconds (10 minutes)")
validPeriod = 600
}
secret, err := totp.Generate(totp.GenerateOpts{
Issuer: "Heimdall",
AccountName: user.Email,
Period: uint(validPeriod),
})
if err != nil {
fmt.Println(err)
return false, errors.New("error generating OTP")
}
otp, err := totp.GenerateCode(secret.Secret(), time.Now())
if err != nil {
fmt.Println(err)
return false, errors.New("error generating OTP")
}
otp_status, err := sendOTP(user.Email, otp)
if err != nil || !otp_status {
fmt.Println(err)
return false, errors.New("error generating OTP")
}
currentTime := int(time.Now().Unix())
user.Secret = secret.Secret()
user.LastUsed = int64(currentTime)
usersMap[user.Email] = &user
return otp_status, nil
}
func handleCampusCheck(res http.ResponseWriter, req *http.Request) {
clientIP := req.Header.Get("X-Real-IP")
if strings.Contains(clientIP, ",") {
ips := strings.Split(clientIP, ",")
clientIP = strings.TrimSpace(ips[0])
}
whoisResponse, err := whois.Whois(clientIP)
if err != nil {
fmt.Println(err)
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
// Define a regular expression pattern to match the netname
pattern := `netname:\s+(.*)`
// Compile the regular expression
re := regexp.MustCompile(pattern)
// Find the netname using the regular expression
match := re.FindStringSubmatch(whoisResponse)
response := make(map[string]bool)
if len(match) >= 2 {
netname := match[1]
fmt.Println("[NETNAME FOUND] ~", netname)
if netname == "IITKGP-IN" {
response["is_inside_kgp"] = true
res.WriteHeader(http.StatusAccepted)
} else {
response["is_inside_kgp"] = false
res.WriteHeader(http.StatusUnauthorized)
}
} else {
fmt.Println("[NETNAME NOT FOUND]")
response["is_inside_kgp"] = false
res.WriteHeader(http.StatusUnauthorized)
}
res.Header().Set("Content-Type", "application/json")
res.Header().Set("Access-Control-Allow-Origin", "*")
jsonResp, err := json.Marshal(response)
if err != nil {
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
}
res.Write(jsonResp)
}
func handleGetOtp(res http.ResponseWriter, req *http.Request) {
email := req.FormValue("email")
if email == "" {
http.Error(res, "Missing email parameter", http.StatusBadRequest)
return
}
// check for institute email
if !isAllowedInstituteEmail(email) {
http.Error(res, "Invalid email domain. Only @kgpian.iitkgp.ac.in & @iitkgp.ac.in are allowed", http.StatusBadRequest)
return
}
user, ok := usersMap[email]
if ok {
cooldown, err := strconv.Atoi(os.Getenv("RESEND_OTP_COOLDOWN"))
if err != nil {
fmt.Println("Invalid RESEND_OTP_COOLDOWN env set. Defaulting to 60 seconds (1 minute)")
cooldown = 60 // keep 30s as minimum cooldown
}
cooldownDuration := time.Duration(cooldown) * time.Second
if time.Now().Unix()-user.LastUsed < int64(cooldownDuration.Seconds()) {
http.Error(res, fmt.Sprintf("You requested OTP recently. Please wait %d seconds before requesting again.", cooldown), http.StatusBadRequest)
return
} else {
otp_status, err := generateOtp(*user)
if err != nil || !otp_status {
fmt.Println(err)
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
response := OtpResponse{
Timestamp: int(user.LastUsed),
Email: email,
OtpStatus: otp_status,
}
respJson, err := json.Marshal(response)
if err != nil {
fmt.Println(err)
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
// Return JSON response with OTP
res.Header().Set("Content-Type", "application/json")
res.Write(respJson)
return
}
}
var newUser User
newUser.Email = email
otp_status, err := generateOtp(newUser)
if err != nil {
fmt.Println(err)
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
response := OtpResponse{
Timestamp: int(newUser.LastUsed),
Email: email,
OtpStatus: otp_status,
}
respJson, err := json.Marshal(response)
if err != nil {
fmt.Println(err)
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
// Return JSON response with OTP
res.Header().Set("Content-Type", "application/json")
res.Write(respJson)
}
func handleVerifyOtp(res http.ResponseWriter, req *http.Request) {
email := req.FormValue("email")
if email == "" {
http.Error(res, "Missing email parameter", http.StatusBadRequest)
return
}
otp := req.FormValue("otp")
if otp == "" {
http.Error(res, "Missing otp parameter", http.StatusBadRequest)
return
}
user, ok := usersMap[email]
if !ok {
http.Error(res, "Please Request OTP first", http.StatusBadRequest)
return
}
valid := totp.Validate(otp, user.Secret)
if !valid {
http.Error(res, "Invalid OTP", http.StatusBadRequest)
return
}
if err := issueLoginCookie(res, user.Email); err != nil {
fmt.Println(err)
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
res.WriteHeader(http.StatusOK)
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("OTP Verified Successfully"))
}
type googleAuthRequest struct {
Credential string `json:"credential"`
}
type googleAuthResponse struct {
Email string `json:"email"`
}
func handleGoogleAuth(res http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodOptions {
res.WriteHeader(http.StatusNoContent)
return
}
var body googleAuthRequest
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
http.Error(res, "Invalid request body", http.StatusBadRequest)
return
}
if strings.TrimSpace(body.Credential) == "" {
http.Error(res, "Missing credential", http.StatusBadRequest)
return
}
clientID := strings.TrimSpace(os.Getenv("GOOGLE_OAUTH_CLIENT_ID"))
if clientID == "" {
http.Error(res, "Google OAuth client not configured", http.StatusInternalServerError)
return
}
payload, err := idtoken.Validate(context.Background(), body.Credential, clientID)
if err != nil {
http.Error(res, "Invalid Google credential", http.StatusUnauthorized)
return
}
email, _ := payload.Claims["email"].(string)
verified, _ := payload.Claims["email_verified"].(bool)
if !verified {
http.Error(res, "Google account email not verified", http.StatusUnauthorized)
return
}
if !isAllowedInstituteEmail(email) {
http.Error(res, "Invalid email domain. Only @kgpian.iitkgp.ac.in & @iitkgp.ac.in are allowed", http.StatusUnauthorized)
return
}
if err := issueLoginCookie(res, email); err != nil {
fmt.Println(err)
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
_ = json.NewEncoder(res).Encode(googleAuthResponse{Email: email})
}
func handleLogout(res http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodOptions {
res.WriteHeader(http.StatusNoContent)
return
}
clearLoginCookie(res)
res.Header().Set("Content-Type", "text/plain")
res.WriteHeader(http.StatusOK)
res.Write([]byte("Logged out"))
}
func handleValidateJwt(res http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie("heimdall")
if err != nil {
http.Error(res, "No JWT session token found.", http.StatusUnauthorized)
return
}
tokenString := cookie.Value
var loginClaims = LoginJwtClaims{}
token, err := jwt.ParseWithClaims(tokenString, &loginClaims, jwtKeyFunc)
if err != nil {
if err == jwt.ErrSignatureInvalid {
http.Error(res, "Invalid token signature", http.StatusBadRequest)
return
}
if err.Error() == fmt.Sprintf("%s: %s", jwt.ErrTokenInvalidClaims.Error(), jwt.ErrTokenExpired.Error()) {
http.Error(res, ErrJwtTokenExpired.Error(), http.StatusUnauthorized)
return
}
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
if !token.Valid {
http.Error(res, ErrJwtTokenInvalid.Error(), http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(*LoginJwtClaims)
if !ok {
http.Error(res, ErrJwtTokenInvalid.Error(), http.StatusBadRequest)
return
}
claimsJSON, err := json.Marshal(claims)
if err != nil {
fmt.Println(res, "Error marshalling claims to JSON: %v", err)
http.Error(res, ErrJwtTokenInvalid.Error(), http.StatusUnauthorized)
return
}
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(claimsJSON)
}
func main() {
// Load environment variables from .env if present. Existing env vars override .env.
if err := godotenv.Load(); err != nil {
// Not fatal if .env is missing (e.g., production container with real env vars)
fmt.Println("No .env file found or could not be loaded, proceeding with existing environment")
}
initMailer()
dev := isDevelopmentMode()
var allowedOrigins []string
if dev {
// Typical local development ports for Vite or other dev servers.
allowedOrigins = []string{"http://localhost", "http://localhost:5173"}
} else {
allowedOrigins = []string{"https://heimdall.metakgp.org"}
}
generalCors := cors.New(cors.Options{
AllowedOrigins: allowedOrigins,
AllowCredentials: true,
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions},
AllowedHeaders: []string{"Content-Type"},
})
specialCors := cors.AllowAll()
mux := http.NewServeMux()
mux.Handle("/", specialCors.Handler(http.HandlerFunc(handleCampusCheck)))
mux.Handle("/get-otp", generalCors.Handler(http.HandlerFunc(handleGetOtp)))
mux.Handle("/verify-otp", generalCors.Handler(http.HandlerFunc(handleVerifyOtp)))
mux.Handle("/auth/google", generalCors.Handler(http.HandlerFunc(handleGoogleAuth)))
mux.Handle("/logout", generalCors.Handler(http.HandlerFunc(handleLogout)))
mux.Handle("/validate-jwt", generalCors.Handler(http.HandlerFunc(handleValidateJwt)))
handler := mux
fmt.Println("Heimdall Server running on port : 3333")
err := http.ListenAndServe(":3333", LoggerMiddleware(handler))
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
os.Exit(1)
}
}