implemented user-adding

This commit is contained in:
z1glr
2025-01-11 16:12:02 +00:00
parent 4f203704a6
commit 059d14acc4
16 changed files with 658 additions and 334 deletions

View File

@@ -4,8 +4,10 @@ import (
"fmt"
"time"
"github.com/google/uuid"
cache "github.com/jfarleyx/go-simple-cache"
"github.com/johannesbuehl/golunteer/backend/pkg/db"
"golang.org/x/crypto/bcrypt"
)
type User struct {
@@ -17,6 +19,16 @@ type User struct {
var c *cache.Cache
// hashes a password
func hashPassword(password string) ([]byte, error) {
return bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
}
// validates a password against the password-rules
func ValidatePassword(password string) bool {
return len(password) >= 12 && len(password) <= 64
}
func Get() (map[string]User, error) {
if users, hit := c.Get("users"); !hit {
refresh()
@@ -27,6 +39,37 @@ func Get() (map[string]User, error) {
}
}
type UserAdd struct {
UserName string `json:"userName" validate:"required" db:"userName"`
Password string `json:"password" validate:"required,min=8"`
Admin bool `json:"admin" db:"admin"`
}
func Add(user UserAdd) error {
// try to hash the password
if hash, err := hashPassword(user.Password); err != nil {
return err
} else {
insertUser := struct {
UserAdd
Password []byte `db:"password"`
TokenID string `db:"tokenID"`
}{
UserAdd: user,
Password: hash,
TokenID: uuid.NewString(),
}
if _, err := db.DB.NamedExec("INSERT INTO USERS (name, password, admin, tokenID) VALUES (:userName, :password, :admin, :tokenID)", insertUser); err != nil {
return err
} else {
refresh()
return nil
}
}
}
func refresh() {
// get the usersRaw from the database
var usersRaw []User