Skip to content

Commit 34ef618

Browse files
committed
chore: clean code
1 parent 1661e40 commit 34ef618

File tree

5 files changed

+3
-35
lines changed

5 files changed

+3
-35
lines changed

cmd/server/main.go

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import (
1616
"mail-manager/internal/web"
1717
)
1818

19-
// Config 구조체는 서비스 운영에 필요한 설정 항목들을 포함합니다.
2019
type Config struct {
2120
Server struct {
2221
Address string `yaml:"address"`
@@ -44,7 +43,6 @@ type Config struct {
4443
} `yaml:"templates"`
4544
}
4645

47-
// loadConfig 파일을 읽어 YAML로 파싱한 후 Config 구조체를 반환합니다.
4846
func loadConfig(path string) (*Config, error) {
4947
data, err := os.ReadFile(path)
5048
if err != nil {
@@ -58,23 +56,19 @@ func loadConfig(path string) (*Config, error) {
5856
}
5957

6058
func main() {
61-
// 커맨드라인 플래그에서 설정 파일 위치를 받습니다.
6259
configFile := flag.String("config", "config/config.yaml", "path to the configuration file")
6360
flag.Parse()
6461

65-
// 설정 파일 로드
6662
cfg, err := loadConfig(*configFile)
6763
if err != nil {
6864
log.Fatalf("Error loading config: %v", err)
6965
}
7066
log.Printf("Configuration loaded: server will listen on %s", cfg.Server.Address)
7167

72-
// SESSION_KEY는 반드시 환경변수로 설정되어 있어야 함
7368
if os.Getenv("SESSION_KEY") == "" {
7469
log.Fatalf("환경변수 SESSION_KEY가 설정되어 있지 않습니다")
7570
}
7671

77-
// OIDC 서비스 생성
7872
oidcSvc, err := auth.NewOIDCService(&auth.OIDCConfig{
7973
ProviderURL: cfg.OIDC.ProviderURL,
8074
ClientID: cfg.OIDC.ClientID,
@@ -87,7 +81,6 @@ func main() {
8781
}
8882
log.Println("OIDC service initialized.")
8983

90-
// authentik 클라이언트 생성
9184
authClient, err := auth.NewAuthentikClient(&auth.AuthentikConfig{
9285
BaseURL: cfg.Authentik.BaseURL,
9386
ApiToken: cfg.Authentik.ApiToken,
@@ -97,7 +90,6 @@ func main() {
9790
}
9891
log.Println("Authentik client initialized.")
9992

100-
// SMTP 클라이언트 생성
10193
smtpClient := email.NewSMTPClient(email.SMTPConfig{
10294
Host: cfg.SMTP.Host,
10395
Port: cfg.SMTP.Port,
@@ -107,9 +99,7 @@ func main() {
10799
})
108100
log.Println("SMTP client initialized.")
109101

110-
// 이메일 템플릿용 TemplateManager 생성
111102
tmplManager := email.NewTemplateManager(cfg.Templates.Email)
112-
// load all templates
113103
files, err := os.ReadDir(cfg.Templates.Email)
114104
if err != nil {
115105
log.Fatalf("템플릿 디렉터리 읽기 실패: %v", err)
@@ -123,25 +113,19 @@ func main() {
123113
}
124114
}
125115

126-
// API 핸들러 생성
127116
apiHandler := web.NewAPIHandler(oidcSvc, tmplManager, smtpClient, authClient)
128117

129118
mux := http.NewServeMux()
130119

131-
// 공개 엔드포인트 (OIDC 로그인 및 콜백)
132120
mux.HandleFunc("/login", oidcSvc.LoginHandler)
133121
mux.HandleFunc("/login/callback", oidcSvc.CallbackHandler)
134122

135-
// 보호된 API 엔드포인트 (OIDC 미들웨어로 인증 보호)
136123
mux.Handle("/api/templates", oidcSvc.AuthMiddleware(http.HandlerFunc(apiHandler.TemplatesListHandler)))
137124
mux.Handle("/api/templates/", oidcSvc.AuthMiddleware(http.HandlerFunc(apiHandler.TemplateHandler)))
138-
// 추가: 미리보기용 엔드포인트 – URL 경로 형식: /api/templates/preview/{name}
139125
mux.Handle("/api/templates/preview/", oidcSvc.AuthMiddleware(http.HandlerFunc(apiHandler.PreviewTemplateHandler)))
140126
mux.Handle("/api/users", oidcSvc.AuthMiddleware(http.HandlerFunc(apiHandler.UsersHandler)))
141127
mux.Handle("/api/email", oidcSvc.AuthMiddleware(http.HandlerFunc(apiHandler.EmailHandler)))
142-
// 추가: 현재 로그인한 사용자 정보를 반환하는 엔드포인트
143128
mux.Handle("/api/me", oidcSvc.AuthMiddleware(http.HandlerFunc(apiHandler.MeHandler)))
144-
// 추가: 로그아웃 엔드포인트 (POST 요청)
145129
mux.Handle("/logout", http.HandlerFunc(apiHandler.LogoutHandler))
146130

147131
// 전체 핸들러에 로깅 및 복구 미들웨어 적용

internal/auth/authentik.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,15 @@ import (
77
authentik "goauthentik.io/api/v3"
88
)
99

10-
// AuthentikConfig holds the configuration parameters for connecting to the authentik API.
1110
type AuthentikConfig struct {
12-
BaseURL string // Base URL of the authentik instance (https://sso.casper.or.kr)
13-
ApiToken string // API token (Bearer) for authenticating with authentik
11+
BaseURL string
12+
ApiToken string
1413
}
1514

16-
// AuthentikClient provides methods to interact with the authentik API.
1715
type AuthentikClient struct {
1816
client *authentik.APIClient
1917
}
2018

21-
// NewAuthentikClient creates and configures an AuthentikClient with the provided settings.
2219
func NewAuthentikClient(cfg *AuthentikConfig) (*AuthentikClient, error) {
2320
if cfg.BaseURL == "" || cfg.ApiToken == "" {
2421
return nil, fmt.Errorf("invalid authentik config: missing BaseURL or ApiToken")
@@ -32,7 +29,6 @@ func NewAuthentikClient(cfg *AuthentikConfig) (*AuthentikClient, error) {
3229
}, nil
3330
}
3431

35-
// GetUserList retrieves the list of users from authentik.
3632
func (ac *AuthentikClient) GetUserList(ctx context.Context) ([]authentik.User, error) {
3733
resp, httpResp, err := ac.client.CoreApi.CoreUsersList(ctx).Execute()
3834
if err != nil {
@@ -47,7 +43,6 @@ func (ac *AuthentikClient) GetUserList(ctx context.Context) ([]authentik.User, e
4743
return filteredUsers, nil
4844
}
4945

50-
// GetUserByID retrieves a single user by its ID.
5146
func (ac *AuthentikClient) GetUserByID(ctx context.Context, id int32) (*authentik.User, error) {
5247
user, httpResp, err := ac.client.CoreApi.CoreUsersRetrieve(ctx, id).Execute()
5348
if err != nil {

internal/auth/oidc.go

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,6 @@ func (s *OIDCService) LoginHandler(w http.ResponseWriter, r *http.Request) {
107107
// It validates the state parameter, exchanges the code for tokens, verifies the ID token,
108108
// and finally saves the authenticated user information in the session.
109109
func (s *OIDCService) CallbackHandler(w http.ResponseWriter, r *http.Request) {
110-
// 세션에서 저장된 state 값 확인
111110
session, err := s.Store.Get(r, "oidc-session")
112111
if err != nil {
113112
http.Error(w, "Failed to get session", http.StatusBadRequest)
@@ -130,14 +129,12 @@ func (s *OIDCService) CallbackHandler(w http.ResponseWriter, r *http.Request) {
130129
return
131130
}
132131

133-
// 코드를 토큰으로 교환
134132
token, err := s.OAuth2Config.Exchange(r.Context(), code)
135133
if err != nil {
136134
http.Error(w, fmt.Sprintf("Failed to exchange token: %v", err), http.StatusInternalServerError)
137135
return
138136
}
139137

140-
// OAuth2 토큰에서 id_token을 추출
141138
rawIDToken, ok := token.Extra("id_token").(string)
142139
if !ok {
143140
http.Error(w, "No id_token field in oauth2 token", http.StatusInternalServerError)
@@ -160,22 +157,19 @@ func (s *OIDCService) CallbackHandler(w http.ResponseWriter, r *http.Request) {
160157
return
161158
}
162159

163-
// 인증이 완료되었으므로 세션에 사용자 정보를 저장 (실제 서비스에서는 추가적인 사용자 저장 및 처리 필요)
164160
session.Values["id_token"] = rawIDToken
165161
session.Values["email"] = claims.Email
166162
session.Values["name"] = claims.Name
167-
// state 값은 더 이상 필요 없으므로 삭제
168163
delete(session.Values, "state")
169164
if err := session.Save(r, w); err != nil {
170165
http.Error(w, "Failed to save session", http.StatusInternalServerError)
171166
return
172167
}
173168

174-
// 로그인 후 리디렉션할 URL을 지정 (예: 대시보드)
175169
http.Redirect(w, r, "/", http.StatusFound)
176170
}
177171

178-
// AuthMiddleware 보호된 엔드포인트에 접근할 때 세션에 id_token이 있는지 확인합니다.
172+
// AuthMiddleware checks if the user is authenticated by verifying the presence of an ID token in the session.
179173
func (s *OIDCService) AuthMiddleware(next http.Handler) http.Handler {
180174
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
181175
session, err := s.Store.Get(r, "oidc-session")

internal/web/handlers.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,13 @@ import (
1818
"mail-manager/internal/email"
1919
)
2020

21-
// APIHandler는 템플릿, 사용자, 이메일 발송 등 API 엔드포인트에 필요한 의존성을 보관합니다.
2221
type APIHandler struct {
2322
OIDCService *auth.OIDCService
2423
TemplateManager *email.TemplateManager
2524
SMTPClient *email.SMTPClient
2625
AuthentikClient *auth.AuthentikClient
2726
}
2827

29-
// NewAPIHandler는 APIHandler 인스턴스를 생성합니다.
3028
func NewAPIHandler(oidc *auth.OIDCService, tm *email.TemplateManager, smtp *email.SMTPClient, authClient *auth.AuthentikClient) *APIHandler {
3129
return &APIHandler{
3230
OIDCService: oidc,
@@ -170,7 +168,6 @@ func (h *APIHandler) TemplateHandler(w http.ResponseWriter, r *http.Request) {
170168
}
171169

172170
// PreviewTemplateHandler handles POST /api/templates/preview/{name}.
173-
// 클라이언트가 수정한 템플릿 내용을 받아 샘플 데이터로 렌더링한 HTML을 반환합니다.
174171
func (h *APIHandler) PreviewTemplateHandler(w http.ResponseWriter, r *http.Request) {
175172
if r.Method != http.MethodPost {
176173
http.Error(w, "지원하지 않는 메서드입니다.", http.StatusMethodNotAllowed)

internal/web/middleware.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"time"
77
)
88

9-
// LoggingMiddleware 모든 요청에 대해 URL, 메서드 및 처리시간을 로깅합니다.
109
func LoggingMiddleware(next http.Handler) http.Handler {
1110
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1211
start := time.Now()
@@ -16,7 +15,6 @@ func LoggingMiddleware(next http.Handler) http.Handler {
1615
})
1716
}
1817

19-
// RecoveryMiddleware panic 발생 시 이를 복구하고 500 에러를 반환합니다.
2018
func RecoveryMiddleware(next http.Handler) http.Handler {
2119
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2220
defer func() {

0 commit comments

Comments
 (0)