-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
405 lines (338 loc) · 10.4 KB
/
main.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
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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/likexian/whois"
"github.com/pquerna/otp/totp"
"github.com/rs/cors"
)
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
}
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 !strings.HasSuffix(email, "@kgpian.iitkgp.ac.in") && !strings.HasSuffix(email, "@iitkgp.ac.in") {
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
}
signingKey, err := getJwtKey()
if err != nil {
fmt.Println(err)
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
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: user.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 {
fmt.Println("Could not parse sign token")
http.Error(res, "Internal Server Error", http.StatusInternalServerError)
return
}
cookie := http.Cookie{
Name: "heimdall",
Value: tokenString,
Expires: expiryTime,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteNoneMode,
Path: "/",
Domain: COOKIE_DOMAIN,
}
http.SetCookie(res, &cookie)
res.WriteHeader(http.StatusOK)
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("OTP Verified Successfully"))
}
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() {
initMailer()
generalCors := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost", "https://heimdall.metakgp.org"},
AllowCredentials: true,
})
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("/validate-jwt", generalCors.Handler(http.HandlerFunc(handleValidateJwt)))
handler := cors.AllowAll().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)
}
}