-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
335 lines (278 loc) · 8.37 KB
/
server.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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
_ "github.com/lib/pq"
)
var db *sql.DB
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Check if user is logged in
cookie, err := r.Cookie("login")
if err == nil {
username, password, found := strings.Cut(cookie.Value, ":")
if found {
if err := authenticateUser(username, password); err == nil {
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
return
}
}
}
http.ServeFile(w, r, "static/html/index.html")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/html/about.html")
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
username := r.FormValue("username")
password := r.FormValue("password")
if username == "" || password == "" {
http.Redirect(w, r, "/?error=Username+and+password+are+required", http.StatusSeeOther)
return
}
if err := authenticateUser(username, password); err != nil {
fmt.Println("Error authenticating user:", err)
http.Redirect(w, r, "/?error=Invalid+username+or+password", http.StatusSeeOther)
return
}
// Get the current last_login timestamp
var lastLogin time.Time
err := db.QueryRow("SELECT last_login FROM users WHERE username = $1", username).Scan(&lastLogin)
if err != nil {
fmt.Println("Error fetching last_login:", err)
http.Redirect(w, r, "/?error=Failed+to+fetch+last+login", http.StatusSeeOther)
return
}
// Update last_login timestamp to the current time
loc, err := time.LoadLocation("Asia/Singapore")
if err != nil {
log.Fatal(err)
}
currentTime := time.Now().In(loc)
// Update the last_login in the database with the current time
_, err = db.Exec("UPDATE users SET last_login = $1 WHERE username = $2", currentTime, username)
if err != nil {
fmt.Println("Error updating last_login:", err)
http.Redirect(w, r, "/?error=Failed+to+update+last+login", http.StatusSeeOther)
return
}
cookie := http.Cookie{
Name: "login",
Value: fmt.Sprintf("%s:%s", username, password),
}
http.SetCookie(w, &cookie)
// Save the last login time in a cookie
lastLoginCookie := http.Cookie{
Name: "last_login",
Value: lastLogin.Format("2 Jan 2006, 15:04"),
}
http.SetCookie(w, &lastLoginCookie)
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cookie, err := r.Cookie("login")
if err != nil {
http.Redirect(w, r, "/?error=Not%20logged%20in", http.StatusSeeOther)
return
}
username, password, found := strings.Cut(cookie.Value, ":")
if !found {
http.Redirect(w, r, "/?error=Invalid%20cookie%20format", http.StatusSeeOther)
return
}
if err := authenticateUser(username, password); err != nil {
http.Redirect(w, r, "/?error=Authentication%20failed", http.StatusSeeOther)
return
}
// Fetch user's balance from the database
var balance int
query := "SELECT balance FROM users WHERE username = $1"
err = db.QueryRow(query, username).Scan(&balance)
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching balance: %v", err), http.StatusInternalServerError)
return
}
_, err = r.Cookie("last_login")
balCookie := http.Cookie{
Name: "balance",
Value: strconv.Itoa(balance),
}
http.SetCookie(w, &balCookie)
http.ServeFile(w, r, "static/html/dashboard.html")
}
func authenticateUser(username, password string) error {
var storedUsername, storedPassword string
query := "SELECT username, password FROM users WHERE username = $1 AND password = '" + password + "'"
err := db.QueryRow(query, username).Scan(&storedUsername, &storedPassword)
if err != nil {
return err
}
if storedUsername == "" || storedPassword == "" {
return fmt.Errorf("invalid username or password")
}
return nil
}
func transferHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cookie, err := r.Cookie("login")
if err != nil {
http.Redirect(w, r, "/?error=Not%20logged%20in", http.StatusSeeOther)
return
}
username, password, found := strings.Cut(cookie.Value, ":")
if !found {
http.Redirect(w, r, "/?error=Invalid%20cookie%20format", http.StatusSeeOther)
return
}
if err := authenticateUser(username, password); err != nil {
http.Redirect(w, r, "/?error=Authentication%20failed", http.StatusSeeOther)
return
}
amount := r.FormValue("amount")
recipient := r.FormValue("recipient")
if amount == "" || recipient == "" {
http.Redirect(w, r, "/dashboard?error=Amount%20and%20recipient%20are%20required", http.StatusSeeOther)
return
}
if err := transferFunds(username, recipient, amount); err != nil {
http.Redirect(w, r, fmt.Sprintf("/dashboard?error=Failed%%20to%%20transfer%%20funds%%3A%%20%s", url.QueryEscape(err.Error())), http.StatusSeeOther)
return
}
http.Redirect(w, r, "/dashboard?success=Funds%20transferred%20successfully", http.StatusSeeOther)
}
func transferFunds(username, recipient, amount string) error {
// Check if recipient exists
query := "SELECT username FROM users WHERE username = $1"
var recipientUsername string
err := db.QueryRow(query, recipient).Scan(&recipientUsername)
if err == sql.ErrNoRows {
return fmt.Errorf("recipient not found")
} else if err != nil {
return err
}
// Check if user has enough balance
query = "SELECT balance FROM users WHERE username = $1"
var balance float64
err = db.QueryRow(query, username).Scan(&balance)
if err != nil {
return err
}
if balance < 0 {
return fmt.Errorf("insufficient balance")
}
amountFloat, err := strconv.ParseFloat(amount, 64)
if err != nil {
return err
}
if balance < amountFloat {
return fmt.Errorf("insufficient balance")
}
// Update balances
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
query = "UPDATE users SET balance = balance - $1 WHERE username = $2"
_, err = tx.Exec(query, amountFloat, username)
if err != nil {
return err
}
query = "UPDATE users SET balance = balance + $1 WHERE username = $2"
_, err = tx.Exec(query, amountFloat, recipient)
if err != nil {
return err
}
return tx.Commit()
}
// Function to clear all cookies and reset the database to a clean state
func resetHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Clear all cookies
http.SetCookie(w, &http.Cookie{
Name: "login",
Value: "",
MaxAge: -1,
})
http.SetCookie(w, &http.Cookie{
Name: "balance",
Value: "",
MaxAge: -1,
})
// Reset the database to a clean state
db.Exec("DELETE FROM users")
db.Exec("ALTER SEQUENCE users_id_seq RESTART WITH 1")
// Read init.sql and execute each statement
initSQL, err := os.ReadFile("init.sql")
if err != nil {
http.Error(w, fmt.Sprintf("Failed to read init.sql: %v", err), http.StatusInternalServerError)
return
}
statements := strings.Split(string(initSQL), ";")
for _, stmt := range statements {
if strings.TrimSpace(stmt) != "" {
fmt.Printf("Executing statement: %s\n", stmt)
_, err := db.Exec(stmt)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to read init.sql: %v", err), http.StatusInternalServerError)
return
}
}
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func initDB() error {
var err error
for i := 0; i < 5; i++ {
db, err = sql.Open("postgres", "host=db port=5432 user=npbankadmin password=ilovenullsec2024 dbname=bankdb sslmode=disable")
if err != nil {
time.Sleep(5 * time.Second)
continue
}
err = db.Ping()
if err == nil {
return nil
}
time.Sleep(5 * time.Second)
}
return err
}
func main() {
if err := initDB(); err != nil {
log.Fatal(err)
}
defer db.Close()
fmt.Printf("Connected to database\n")
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fileServer))
http.HandleFunc("/", indexHandler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/dashboard", dashboardHandler)
http.HandleFunc("/transfer", transferHandler)
http.HandleFunc("/reset", resetHandler)
fmt.Printf("Server started at port 80\n")
if err := http.ListenAndServe("0.0.0.0:80", nil); err != nil {
log.Fatal(err)
}
}