add users
This commit is contained in:
@ -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"`
|
||||
}
|
||||
|
Reference in New Issue
Block a user