Work on gitlab connection

This commit is contained in:
nemunaire 2022-09-04 16:36:15 +02:00
parent e62ff978f9
commit 7e7608b7d1
2 changed files with 114 additions and 37 deletions

148
gitlab.go
View File

@ -5,26 +5,26 @@ import (
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"golang.org/x/oauth2"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gin-gonic/gin"
)
const (
OAUTH_GITLAB_FILE = ".gitlab-oauth-token"
gitlabBaseURL = "https://gitlab.cri.epita.fr"
)
var (
gitlabBaseURL = "https://gitlab.cri.epita.fr"
gitlabClientID = ""
gitlabSecret = ""
gitlaboauth2Config oauth2.Config
gitlaboidcVerifier *oidc.IDTokenVerifier
gitlabToken *oauth2.Token
)
@ -37,6 +37,25 @@ func initializeGitLabOIDC(router *gin.Engine, authrouter *gin.RouterGroup, admin
adminrouter.GET("/auth/gitlabcri", redirectOAuth_GitLab)
router.GET("/callback/gitlabcri/complete", GitLab_OAuth_complete)
if gitlabClientID != "" && gitlabSecret != "" {
gitlaboauth2Config = oauth2.Config{
ClientID: gitlabClientID,
ClientSecret: gitlabSecret,
RedirectURL: oidcRedirectURL + baseURL + "/callback/gitlabcri/complete",
// Discovery returns the OAuth2 endpoints.
Endpoint: oauth2.Endpoint{
AuthURL: gitlabBaseURL + "/oauth/authorize",
TokenURL: gitlabBaseURL + "/oauth/token",
},
// "openid" is a required scope for OpenID Connect flows.
Scopes: []string{"api", "read_repository", "email"},
}
authrouter.GET("/api/gitlabcri/repositories", GitLab_GetMyRepositories)
}
if _, err := os.Stat(OAUTH_GITLAB_FILE); err == nil {
gitlabToken, err = loadOAuth2Token(OAUTH_GITLAB_FILE)
if err != nil {
@ -44,31 +63,6 @@ func initializeGitLabOIDC(router *gin.Engine, authrouter *gin.RouterGroup, admin
}
}
if gitlabClientID != "" && gitlabSecret != "" {
provider, err := oidc.NewProvider(context.Background(), gitlabBaseURL)
if err != nil {
log.Fatal("Unable to setup oidc:", err)
}
gitlaboauth2Config = oauth2.Config{
ClientID: gitlabClientID,
ClientSecret: gitlabSecret,
RedirectURL: oidcRedirectURL + baseURL + "/callback/gitlabcri/complete",
// Discovery returns the OAuth2 endpoints.
Endpoint: provider.Endpoint(),
// "openid" is a required scope for OpenID Connect flows.
Scopes: []string{"api", "read_repository", "email"},
}
oidcConfig := oidc.Config{
ClientID: gitlabClientID,
}
gitlaboidcVerifier = provider.Verifier(&oidcConfig)
authrouter.GET("/api/gitlabcri/repositories", GitLab_getRepositories)
}
}
func loadOAuth2Token(file string) (*oauth2.Token, error) {
@ -142,22 +136,102 @@ func GitLab_OAuth_complete(c *gin.Context) {
session.Update()
}
func GitLab_getRepositories(c *gin.Context) {
client := gitlaboauth2Config.Client(c.Request.Context(), gitlabToken)
type GitLabRepositoryNamespace struct {
ID int
Name string
Path string
Kind string
}
req, err := http.NewRequest("GET", gitlabBaseURL+"/api/v4/projects", nil)
if err != nil {
log.Println("Unable to create NewRequest before GitLab call: ", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "An error occurs when performing the GitLab request."})
return
type GitLabRepositoryUser struct {
ID int
Username string
Name string
State string
}
type GitLabRepository struct {
ID int
Description string
Name string
Path string
PathWithNamespace string `json:"path_with_namespace"`
DefaultBranch string `json:"default_branch"`
HttpUrlToRepo string `json:"http_url_to_repo"`
AvatarURL string `json:"avatar_url"`
LastActivityAt time.Time `json:"last_activity_at,omitempty"`
Namespace GitLabRepositoryNamespace
Visibility string `json:"visibility,omitempty"`
Owner *GitLabRepositoryUser `json:"owner,omitempty"`
ForkedFromProject *GitLabRepository `json:"forked_from_project,omitempty"`
}
func GitLab_GetMyRepositories(c *gin.Context) {
var u *User
if user, ok := c.Get("user"); ok {
u = user.(*User)
} else {
u = c.MustGet("LoggedUser").(*User)
}
resp, err := client.Do(req)
repos, err := GitLab_getUsersRepositories(c.Request.Context(), u)
if err != nil {
log.Println("Unable to perform the GitLab request: ", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "An error occurs when performing the GitLab request."})
return
}
c.DataFromReader(resp.StatusCode, resp.ContentLength, resp.Header.Get("content-type"), resp.Body, nil)
var repositories []*GitLabRepository
for _, r := range repos {
if r.Owner.Username == u.Login {
repositories = append(repositories, r)
}
}
c.JSON(http.StatusOK, repos)
}
/*func GitLab_getRepositories(c context.Context) ([]*GitLabRepository, error) {
client := oauth2.NewClient(c, gitlaboauth2Config.TokenSource(c, gitlabToken))
req, err := http.NewRequest("GET", gitlabBaseURL+"/api/v4/projects?per_page=100", nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Bad status code from the API")
}
var repositories []*GitLabRepository
err = json.NewDecoder(resp.Body).Decode(&repositories)
return repositories, err
}*/
func GitLab_getUsersRepositories(c context.Context, u *User) ([]*GitLabRepository, error) {
client := oauth2.NewClient(c, oauth2.ReuseTokenSource(gitlabToken, gitlaboauth2Config.TokenSource(c, gitlabToken)))
req, err := http.NewRequest("GET", gitlabBaseURL+fmt.Sprintf("/api/v4/users/%s/projects?per_page=100", u.Login), nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Bad status code from the API")
}
var repositories []*GitLabRepository
err = json.NewDecoder(resp.Body).Decode(&repositories)
return repositories, err
}

View File

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