From 633175f5bef4088eeb6af86156dba65d1c1183bf Mon Sep 17 00:00:00 2001 From: tolelom <98kimsungmin@naver.com> Date: Tue, 24 Feb 2026 14:28:33 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=ED=99=98=EA=B2=BD=EB=B3=80=EC=88=98?= =?UTF-8?q?=EB=A1=9C=20=EC=B4=88=EA=B8=B0=20admin=20=EA=B3=84=EC=A0=95=20?= =?UTF-8?q?=EC=9E=90=EB=8F=99=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 서버 시작 시 ADMIN_USERNAME, ADMIN_PASSWORD 환경변수 기반으로 admin 계정이 없을 경우 자동 생성 (이미 있으면 스킵) Co-Authored-By: Claude Sonnet 4.6 --- .env.example | 5 ++++- internal/auth/service.go | 15 +++++++++++++++ main.go | 7 +++++++ pkg/config/config.go | 4 ++++ 4 files changed, 30 insertions(+), 1 deletion(-) 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"), } }