-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
79 lines (66 loc) · 1.76 KB
/
db.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
package main
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/crypto/bcrypt"
)
type User struct {
Name string `form:"name" binding:"required"`
Pass string `form:"pass" binding:"required"`
}
func (u User) InsertDb(db *sql.DB) error {
// Hash the password before storing it in the database
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Pass), bcrypt.DefaultCost)
if err != nil {
return err
}
_, err = db.Exec("INSERT INTO users (username, password) VALUES (?, ?)", u.Name, hashedPassword)
return err
}
// Function to verify login credentials
func (u User) VerifyLogin(db *sql.DB) bool {
// Retrieve the hashed password from the database
var hashedPassword string
err := db.QueryRow("SELECT password FROM users WHERE username = ?", u.Name).Scan(&hashedPassword)
if err != nil {
return false
}
// Compare the provided password with the hashed password
err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(u.Pass))
return err == nil
}
// Function to query all users from the database
func QueryUsers(db *sql.DB) ([]string, error) {
rows, err := db.Query("SELECT username FROM users")
if err != nil {
return nil, err
}
defer rows.Close()
var names []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
names = append(names, name)
}
return names, nil
}
func InitDB() (*sql.DB, error) {
db, err := sql.Open("sqlite3", "/tmp/db.sqlite3")
if err != nil {
return nil, err
}
// Create the users table if it doesn't exist
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
)
`)
if err != nil {
return nil, err
}
return db, nil
}