Files
CatsOfMastodonGo/internal/web/handlers/oauth.go
Mohammad Mahdi 94694741a7 modernize the codebase
Run the modernize linter across the codebase.
Change generated by running:

```
go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...
```

Ref:
https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize
2025-09-23 09:13:29 +03:30

74 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]any{"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",
})
}