security/lib/user.go

61 lines
937 B
Go
Raw Permalink Normal View History

2024-03-21 20:20:24 +00:00
package lib
import (
"fmt"
"github.com/gofiber/fiber/v2"
)
type User struct {
2024-08-13 19:25:36 +00:00
Username string
Password string
Cookie string
2024-03-21 20:20:24 +00:00
}
func GetUser(c *fiber.Ctx) (User, error) {
2024-08-13 19:25:36 +00:00
users, err := LoadUsers()
if err != nil {
return User{}, err
}
for i, u := range users {
if c.Cookies("auth") == u.Cookie {
return users[i], nil
}
}
return User{}, fmt.Errorf("user not found")
2024-03-21 20:20:24 +00:00
}
func LoadUsers() ([]User, error) {
2024-08-13 19:25:36 +00:00
var users []User
rows, err := Db.Query("SELECT * FROM users")
if err != nil {
return users, err
}
defer rows.Close()
for rows.Next() {
var u User
rows.Scan(&u.Username, &u.Password, &u.Cookie)
users = append(users, u)
}
return users, nil
2024-03-21 20:20:24 +00:00
}
func UpdateUser(u User) error {
2024-08-13 19:25:36 +00:00
smt, err := Db.Prepare("UPDATE users SET password=?, cookie=? WHERE username=?")
if err != nil {
return err
}
2024-03-21 20:20:24 +00:00
2024-08-13 19:25:36 +00:00
_, err = smt.Exec(u.Password, u.Cookie, u.Username)
if err != nil {
return err
}
2024-03-21 20:20:24 +00:00
2024-08-13 19:25:36 +00:00
return nil
2024-03-21 20:20:24 +00:00
}