Feat(ktm-booking): Initial commit
Some checks failed
ktm-booking-bot/ktm-booking-bot/pipeline/head Something is wrong with the build of this commit
Some checks failed
ktm-booking-bot/ktm-booking-bot/pipeline/head Something is wrong with the build of this commit
This commit is contained in:
71
backend/internal/user/usercontroller.go
Normal file
71
backend/internal/user/usercontroller.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
BCRYPTCOST = 12
|
||||
)
|
||||
|
||||
func (env *Env) createUser(username string, password string) (*User, error) {
|
||||
var createdUser User
|
||||
|
||||
passwordByte := []byte(password)
|
||||
createdHashBytes, err := bcrypt.GenerateFromPassword(passwordByte, BCRYPTCOST)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to generate bcrypt")
|
||||
}
|
||||
|
||||
createdUser.Username = username
|
||||
createdUser.PasswordBcrypt = string(createdHashBytes)
|
||||
return &createdUser, nil
|
||||
}
|
||||
|
||||
func (env *Env) registerUser(username string, password string) (*User, error) {
|
||||
newUser, err := env.createUser(username, password)
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return nil, errors.New("failed to register user")
|
||||
}
|
||||
|
||||
// Check existing username
|
||||
var checkUser User
|
||||
env.DB.Where(&User{Username: username}).First(&checkUser)
|
||||
if checkUser.ID != uuid.Nil {
|
||||
log.Println(err)
|
||||
return nil, errors.New("user already exists")
|
||||
}
|
||||
|
||||
err = env.DB.Create(newUser).Error
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return nil, errors.New("failed write to database")
|
||||
}
|
||||
|
||||
return newUser, nil
|
||||
}
|
||||
|
||||
func (env *Env) checkLogin(username string, password string) (*User, error) {
|
||||
var currUser User
|
||||
env.DB.Preload("Profile").Where(&User{Username: username}).First(&currUser)
|
||||
|
||||
// Prevent username enum by parsing password
|
||||
if currUser.ID == uuid.Nil {
|
||||
bcrypt.GenerateFromPassword([]byte{}, BCRYPTCOST)
|
||||
return nil, errors.New("invalid username or password")
|
||||
}
|
||||
|
||||
err := bcrypt.CompareHashAndPassword([]byte(currUser.PasswordBcrypt), []byte(password))
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid username or password")
|
||||
} else {
|
||||
return &currUser, nil
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user