Refactor: Implement uber-go/fx dependency injection

- Replace global variable pattern with proper dependency injection
- Add uber-go/fx for automatic dependency resolution
- Refactor all services and handlers to use constructor injection
- Eliminate fragile initialization order dependencies
- Improve testability and modularity
- Add structured logging with zap

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
2025-09-16 11:41:01 +03:30
co-authored by Qwen-Coder
parent d4044b0eaf
commit f136ae58b3
15 changed files with 389 additions and 255 deletions
+22 -17
View File
@@ -10,21 +10,25 @@ import (
)
type OauthLoginHandler struct {
Jwt auth.JwtTokenGenerator
OauthLoginHandler *auth.GiteaOAuth2Handler
jwt *auth.JwtTokenGenerator
oauthHandler *auth.GiteaOAuth2Handler
cfg *config.Config
}
var OauthLoginHandlerInstance *OauthLoginHandler
func InitOauthLoginHandler() {
OauthLoginHandlerInstance = &OauthLoginHandler{
Jwt: *auth.JwtTokenGeneratorInstance,
OauthLoginHandler: auth.GiteaOauth2HandlerInstance,
func NewOauthLoginHandler(
jwt *auth.JwtTokenGenerator,
oauthHandler *auth.GiteaOAuth2Handler,
cfg *config.Config,
) *OauthLoginHandler {
return &OauthLoginHandler{
jwt: jwt,
oauthHandler: oauthHandler,
cfg: cfg,
}
}
func (olh *OauthLoginHandler) GoToGiteaLogin(c *gin.Context) {
redirectURL, _ := olh.OauthLoginHandler.GetGiteaLoginURL(c.Request.URL.Scheme + c.Request.Host)
redirectURL, _ := olh.oauthHandler.GetGiteaLoginURL(c.Request.URL.Scheme + c.Request.Host)
if redirectURL != "" {
c.Redirect(http.StatusFound, redirectURL)
return
@@ -42,27 +46,28 @@ func (olh *OauthLoginHandler) LoginWithGitea(c *gin.Context) {
return
}
userEmail, err := olh.OauthLoginHandler.GetGiteaUserEmailByCode(input.Code)
userEmail, err := olh.oauthHandler.GetGiteaUserEmailByCode(input.Code)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
for _, email := range config.Config.GiteaOauthAllowedEmails {
// Check if the user's email is in the allowed list
for _, email := range olh.cfg.GiteaOauthAllowedEmails {
if email == userEmail {
token, err := olh.Jwt.GenerateToken(map[string]interface{}{"role": "admin"})
token, err := olh.jwt.GenerateToken(map[string]interface{}{"role": "admin"})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Token generation failed"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Login successful", "token": token})
} else {
c.JSON(401, gin.H{
"error": "oath login faied or yyour email does not have access",
})
return
}
}
}
// If we get here, the email is not in the allowed list
c.JSON(401, gin.H{
"error": "oauth login failed or your email does not have access",
})
}