add users

This commit is contained in:
u80864958
2025-04-30 16:41:30 +02:00
parent f4adfb6a62
commit eed1718a7e
17 changed files with 538 additions and 60 deletions

View File

@ -1,9 +1,14 @@
package auth
import (
"log"
"time"
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
jwt "github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Config struct {
@ -11,6 +16,7 @@ type Config struct {
ValidDuration time.Duration `env:"VALID_DURATION"`
AdminName string `env:"ADMIN_NAME"`
AdminPassword string `env:"ADMIN_PASSWORD"`
DefaultRole model.Role `env:"DEFAULT_ROLE"`
}
type Service struct {
@ -19,8 +25,33 @@ type Service struct {
}
func New(cfg *Config, db *gorm.DB) *Service {
user := model.NewUser()
var err error
if user.Password, err = bcrypt.GenerateFromPassword([]byte(cfg.AdminName), 6); err != nil {
log.Fatalf("Error while creating default user: %v", err)
}
user.Name = cfg.AdminName
user.Role = model.RoleAdmin
// add default user
_ = db.Clauses(clause.OnConflict{DoNothing: true}).Save(&user).Error
return &Service{
cfg,
db,
}
}
type Claims struct {
Role model.Role `json:"rl"`
UserID uint `json:"uid"`
jwt.RegisteredClaims
}
type Login struct {
Name string `json:"name"`
Password string `json:"Password"`
}
type LoginResponse struct {
Token string `json:"token"`
}