- 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>
73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"CatsOfMastodonBotGo/internal/auth"
|
|
"CatsOfMastodonBotGo/internal/config"
|
|
"CatsOfMastodonBotGo/internal/web/dto"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type OauthLoginHandler struct {
|
|
jwt *auth.JwtTokenGenerator
|
|
oauthHandler *auth.GiteaOAuth2Handler
|
|
cfg *config.Config
|
|
}
|
|
|
|
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.oauthHandler.GetGiteaLoginURL(c.Request.URL.Scheme + c.Request.Host)
|
|
if redirectURL != "" {
|
|
c.Redirect(http.StatusFound, redirectURL)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get gitea login url"})
|
|
|
|
}
|
|
|
|
func (olh *OauthLoginHandler) LoginWithGitea(c *gin.Context) {
|
|
|
|
var input dto.GiteaLoginInput
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
userEmail, err := olh.oauthHandler.GetGiteaUserEmailByCode(input.Code)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
// 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"})
|
|
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})
|
|
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",
|
|
})
|
|
} |