Try new method to expose Token

This commit is contained in:
nemunaire 2022-09-05 00:54:33 +02:00
parent 5efc6d1aaa
commit bbfa9d3084
2 changed files with 17 additions and 10 deletions

View File

@ -25,7 +25,7 @@ var (
gitlabClientID = ""
gitlabSecret = ""
gitlaboauth2Config oauth2.Config
gitlabToken *oauth2.Token
gitlabToken func() *oauth2.Token
)
func init() {
@ -62,12 +62,7 @@ func initializeGitLabOIDC(router *gin.Engine, authrouter *gin.RouterGroup, admin
log.Println("Unable to load OAuth2 Token:", err.Error())
}
tsource := oauth2.ReuseTokenSource(gitlabToken, gitlaboauth2Config.TokenSource(context.Background(), tk))
gitlabToken, err = tsource.Token()
if err != nil {
log.Fatal("Unable to regenerate GitLab token:", err)
}
log.Println(gitlabToken)
prepareOAuth2Token(tk)
}
}
@ -85,6 +80,18 @@ func loadOAuth2Token(file string) (*oauth2.Token, error) {
return &tok, err
}
func prepareOAuth2Token(tk *oauth2.Token) {
tsource := oauth2.ReuseTokenSource(tk, gitlaboauth2Config.TokenSource(context.Background(), tk))
gitlabToken = func() *oauth2.Token {
t, err := tsource.Token()
if err != nil {
log.Println("Unable to regenerate GitLab token:", err)
}
return t
}
}
func saveOAuth2Token(file string, tok *oauth2.Token) error {
fd, err := os.Create(file)
if err != nil {
@ -125,13 +132,13 @@ func GitLab_OAuth_complete(c *gin.Context) {
return
}
gitlabToken = oauth2Token
err = saveOAuth2Token(OAUTH_GITLAB_FILE, oauth2Token)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Unable to save OAuth2 token: " + err.Error()})
return
}
prepareOAuth2Token(oauth2Token)
log.Println("New GitLab OAuth2 session opened")
if source, ok := session.GetKey("gitlab-oidc-source"); ok {
@ -221,7 +228,7 @@ func GitLab_GetMyRepositories(c *gin.Context) {
}*/
func GitLab_getUsersRepositories(c context.Context, u *User) ([]*GitLabRepository, error) {
client := oauth2.NewClient(c, oauth2.ReuseTokenSource(gitlabToken, gitlaboauth2Config.TokenSource(c, gitlabToken)))
client := gitlaboauth2Config.Client(c, gitlabToken())
req, err := http.NewRequest("GET", gitlabBaseURL+fmt.Sprintf("/api/v4/users/%s/projects?per_page=100", u.Login), nil)
if err != nil {

View File

@ -108,7 +108,7 @@ func main() {
log.Print("The service is shutting down...")
a.Stop()
if gitlabToken != nil {
saveOAuth2Token(OAUTH_GITLAB_FILE, gitlabToken)
saveOAuth2Token(OAUTH_GITLAB_FILE, gitlabToken())
}
log.Println("done")
}