69 lines
1.7 KiB
Go
69 lines
1.7 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
|
|
OauthLoginHandler *auth.GiteaOAuth2Handler
|
|
}
|
|
|
|
var OauthLoginHandlerInstance *OauthLoginHandler
|
|
|
|
func InitOauthLoginHandler() {
|
|
OauthLoginHandlerInstance = &OauthLoginHandler{
|
|
Jwt: *auth.JwtTokenGeneratorInstance,
|
|
OauthLoginHandler: auth.GiteaOauth2HandlerInstance,
|
|
}
|
|
}
|
|
|
|
func (olh *OauthLoginHandler) GoToGiteaLogin(c *gin.Context) {
|
|
redirectURL, _ := olh.OauthLoginHandler.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.OauthLoginHandler.GetGiteaUserEmailByCode(input.Code)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
for _, email := range config.Config.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})
|
|
} else {
|
|
c.JSON(401, gin.H{
|
|
"error": "oath login faied or yyour email does not have access",
|
|
})
|
|
return
|
|
}
|
|
}
|
|
|
|
}
|