-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
172 lines (141 loc) · 4.96 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
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/pquerna/otp/totp"
)
type User struct {
Username string
Password string
Secret string
}
// Simple in-memory "database" for demonstration purposes
var users = map[string]*User{
"john": {Username: "john", Password: "password", Secret: ""},
}
var templates = template.Must(template.ParseGlob("templates/*.html"))
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/dashboard", dashboardHandler)
http.HandleFunc("/generate-otp", generateOTPHandler)
http.HandleFunc("/validate-otp", validateOTPHandler)
fmt.Println("Starting server at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
_ = templates.ExecuteTemplate(w, "index.html", nil)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
_ = templates.ExecuteTemplate(w, "login.html", nil)
return
}
r.ParseForm()
username := r.Form.Get("username")
password := r.Form.Get("password")
user, ok := users[username]
if !ok || user.Password != password {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if user.Secret == "" {
http.Redirect(w, r, "/generate-otp?username="+username, http.StatusFound)
return
}
_ = templates.ExecuteTemplate(w, "validate.html", struct{ Username string }{Username: username})
}
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
username, err := r.Cookie("authenticatedUser")
if err != nil || username.Value == "" {
http.Redirect(w, r, "/", http.StatusFound)
return
}
_ = templates.ExecuteTemplate(w, "dashboard.html", nil)
}
func generateOTPHandler(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("username")
password := r.URL.Query().Get("password")
user, ok := users[username]
if !ok || user.Password != password {
data := struct {
Error string
}{
Error: "Wrong username or password",
}
_ = templates.ExecuteTemplate(w, "error.html", data)
return
}
// Only generate the secret once
if user.Secret == "" {
secret, err := totp.Generate(totp.GenerateOpts{
Issuer: "Go2FADemo",
AccountName: username,
})
if err != nil {
http.Error(w, "Failed to generate TOTP secret.", http.StatusInternalServerError)
return
}
user.Secret = secret.Secret()
// Save the updated user back into the map
users[username] = user
}
// Generate the OTP URL
otpURL := fmt.Sprintf("otpauth://totp/Go2FADemo:%s?secret=%s&issuer=Go2FADemo", username, user.Secret)
// Prepare the data for rendering
data := struct {
OTPURL string
Username string
}{
OTPURL: otpURL,
Username: username,
}
// Render the qrcode template with the data
if err := templates.ExecuteTemplate(w, "qrcode.html", data); err != nil {
http.Error(w, "Failed to render template.", http.StatusInternalServerError)
}
}
func validateOTPHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
// Extract the username from the query parameters, if needed
username := r.URL.Query().Get("username")
// Render the validate.html template, passing the username to it
err := templates.ExecuteTemplate(w, "validate.html", struct{ Username string }{Username: username})
if err != nil {
http.Error(w, "Failed to render template", http.StatusInternalServerError)
}
case "POST":
// Parsing form data
if err := r.ParseForm(); err != nil {
http.Error(w, "Error parsing form", http.StatusBadRequest)
return
}
username := r.FormValue("username")
otpCode := r.FormValue("otpCode")
user, exists := users[username]
if !exists {
http.Error(w, "User does not exist", http.StatusBadRequest)
return
}
// Using the TOTP library to validate the OTP code
isValid := totp.Validate(otpCode, user.Secret)
if !isValid {
// If OTP validation fails, redirect back to the validation page
http.Redirect(w, r, fmt.Sprintf("/validate-otp?username=%s", username), http.StatusTemporaryRedirect)
return
}
// If OTP is valid, set a session cookie (simplified for this example) and redirect to dashboard
http.SetCookie(w, &http.Cookie{
Name: "authenticatedUser",
Value: "true",
Path: "/",
MaxAge: 3600, // 1 hour for example
})
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
default:
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
}