Added oauth for gitea
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
func (_ *OauthLoginHandler) GoToGiteaLogin(c *gin.Context) {
|
||||
c.Redirect(http.StatusFound, auth.GiteaOauth2HandlerInstance.GetGiteaLoginURL(c.Request.Host))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user