diff --git a/.env.example b/.env.example index a92cae5..e0b2300 100644 --- a/.env.example +++ b/.env.example @@ -10,4 +10,7 @@ REDIS_ADDR=localhost:6379 REDIS_PASSWORD= JWT_SECRET=your-secret-key-here -JWT_EXPIRY_HOURS=24 \ No newline at end of file +JWT_EXPIRY_HOURS=24 + +ADMIN_USERNAME=admin +ADMIN_PASSWORD=admin1234 \ No newline at end of file diff --git a/internal/auth/service.go b/internal/auth/service.go index 02d77fd..dc91290 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -64,3 +64,18 @@ func (s *Service) Logout(userID uint) { key := fmt.Sprintf("session:%d", userID) s.rdb.Del(context.Background(), key) } + +func (s *Service) EnsureAdmin(username, password string) error { + if _, err := s.repo.FindByUsername(username); err == nil { + return nil // 이미 존재하면 스킵 + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + return s.repo.Create(&User{ + Username: username, + PasswordHash: string(hash), + Role: RoleAdmin, + }) +} diff --git a/main.go b/main.go index 7210411..b82efb2 100644 --- a/main.go +++ b/main.go @@ -35,6 +35,13 @@ func main() { authSvc := auth.NewService(authRepo, database.RDB) authHandler := auth.NewHandler(authSvc) + // 초기 admin 계정 생성 + if err := authSvc.EnsureAdmin(config.C.AdminUsername, config.C.AdminPassword); err != nil { + log.Printf("admin 계정 생성 실패: %v", err) + } else { + log.Printf("admin 계정 확인 완료: %s", config.C.AdminUsername) + } + annRepo := announcement.NewRepository(database.DB) annSvc := announcement.NewService(annRepo) annHandler := announcement.NewHandler(annSvc) diff --git a/pkg/config/config.go b/pkg/config/config.go index 7cdb25d..0afb8eb 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -18,6 +18,8 @@ type Config struct { RedisPassword string JWTSecret string JWTExpiryHours int + AdminUsername string + AdminPassword string } var C Config @@ -37,6 +39,8 @@ func Load() { RedisPassword: getEnv("REDIS_PASSWORD", ""), JWTSecret: getEnv("JWT_SECRET", "secret"), JWTExpiryHours: hours, + AdminUsername: getEnv("ADMIN_USERNAME", "admin"), + AdminPassword: getEnv("ADMIN_PASSWORD", "admin1234"), } }