61 lines
937 B
Go
61 lines
937 B
Go
package lib
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
type User struct {
|
|
Username string
|
|
Password string
|
|
Cookie string
|
|
}
|
|
|
|
func GetUser(c *fiber.Ctx) (User, error) {
|
|
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")
|
|
}
|
|
|
|
func LoadUsers() ([]User, error) {
|
|
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
|
|
}
|
|
|
|
func UpdateUser(u User) error {
|
|
smt, err := Db.Prepare("UPDATE users SET password=?, cookie=? WHERE username=?")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = smt.Exec(u.Password, u.Cookie, u.Username)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|