-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
114 lines (96 loc) · 2.91 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
package main
import (
"database/sql"
"encoding/csv"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
_ "github.com/mattn/go-sqlite3"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
func loadUsersFromCSV(db *sql.DB, filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
return err
}
for _, record := range records[1:] { // Skip the header
_, err := db.Exec("INSERT OR REPLACE INTO users (username, password) VALUES (?, ?)", record[0], record[1])
if err != nil {
return err
}
}
return nil
}
func main() {
// Initialize the SQLite database
db, err := sql.Open("sqlite3", "./user.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Create users table
createTableSQL := `CREATE TABLE IF NOT EXISTS users (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"username" TEXT NOT NULL UNIQUE,
"password" TEXT NOT NULL
);`
_, err = db.Exec(createTableSQL)
if err != nil {
log.Fatal(err)
}
// Define the handler
http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Reload users from CSV file
err := loadUsersFromCSV(db, "users.csv")
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
var user User
err = json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
var storedPassword string
err = db.QueryRow("SELECT password FROM users WHERE username = ?", user.Username).Scan(&storedPassword)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if user.Password != storedPassword {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Double-check user/password verification
err = db.QueryRow("SELECT password FROM users WHERE username = ?", user.Username).Scan(&storedPassword)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if user.Password != storedPassword {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Success")
})
// Start the HTTP server
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}