Add a config to create new users on startup

This commit is contained in:
2026-03-01 00:15:09 +01:00
parent 18b5f0f0e1
commit 660c44992e
5 changed files with 134 additions and 46 deletions

View File

@@ -5,11 +5,9 @@ import (
"net/http"
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/createuser"
"git.artlef.fr/PersonalLibraryManager/internal/dto"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
func PostSignupHandler(ac appcontext.AppContext) {
@@ -27,43 +25,10 @@ func PostSignupHandler(ac appcontext.AppContext) {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
userDb, err := userWsToDb(user)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
var existingUser model.User
err = ac.Db.Where("name = ?", user.Username).First(&existingUser).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
if err == nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac,
myvalidator.HttpError{
StatusCode: http.StatusInternalServerError,
Err: errors.New("An user with this name already exists."),
})
return
}
err = ac.Db.Model(&model.User{}).Save(&userDb).Error
err = createuser.CreateUser(ac.Db, user.Username, user.Password)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
ac.C.String(200, "Success")
}
func userWsToDb(u dto.UserSignup) (model.User, error) {
user := model.User{
Name: u.Username,
Password: "",
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return user, err
}
user.Password = string(hashedPassword)
return user, nil
}