StaleBot for Gitea
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB

// staletea
// Copyright (C) 2019 Jonas Franz
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package web
import (
"code.gitea.io/sdk/gitea"
"context"
"gitea.com/jonasfranz/staletea/auth"
"gitea.com/jonasfranz/staletea/config"
"gitea.com/jonasfranz/staletea/models"
"gitea.com/jonasfranz/staletea/utils"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
)
func handleLogin(ctx *gin.Context) {
session := sessions.Default(ctx)
state, err := utils.NewSecret(32)
if err != nil {
_ = ctx.AbortWithError(500, err)
return
}
session.Set("state", state)
if err := session.Save(); err != nil {
_ = ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
redirectURL := auth.Config().AuthCodeURL(state)
ctx.Redirect(http.StatusTemporaryRedirect, redirectURL)
}
func handleCallback(ctx *gin.Context) {
session := sessions.Default(ctx)
state := ctx.Query("state")
savedState := session.Get("state")
if savedState == nil {
ctx.String(http.StatusUnauthorized, "Invalid state")
return
}
session.Delete("state")
if parsedState, ok := savedState.(string); !ok || parsedState != state {
ctx.String(http.StatusUnauthorized, "Invalid state")
return
}
token, err := auth.Config().Exchange(ctx, ctx.Query("code"))
if err != nil {
_ = ctx.AbortWithError(http.StatusUnauthorized, err)
return
}
client := gitea.NewClient(config.GiteaURL.Get().(string), "")
client.SetHTTPClient(auth.Config().Client(context.Background(), token))
user, err := client.GetMyUserInfo()
if err != nil {
_ = ctx.AbortWithError(http.StatusUnauthorized, err)
return
}
storedUser := &models.User{
ID: user.ID,
Username: user.UserName,
Token: token,
}
session.Set("user", storedUser)
6 years ago
if err := session.Save(); err != nil {
_ = ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
ctx.Redirect(http.StatusTemporaryRedirect, config.BaseURL.Get().(string))
}