My Very Own CI-server
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.
 
 
 
 
 

94 lines
2.9 KiB

package hook
import (
"os"
"io"
"fmt"
"bytes"
"context"
"net/http"
"path/filepath"
"mime/multipart"
"golang.org/x/oauth2"
//"mvoCI/core"
)
var AppName = "mvoCI"
var AppWebsite = "http://localhost:4042"
func PostFile ( client *http.Client, url string, formData map[string]string, formFilename string, filename string ) ( *http.Response, error) {
file, err := os.Open( filename )
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter( body )
part, err := writer.CreateFormFile( formFilename, filepath.Base( filename ) )
if err != nil {
return nil, err
}
_, err = io.Copy( part, file )
if err != nil {
return nil, err
}
for key, val := range formData {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, _ := http.NewRequest( "POST", url, body )
req.Header.Set("Content-Type", writer.FormDataContentType())
return client.Do ( req )
}
// internal function to create the configuration for the OAuth2 library
func CreateConf ( server string, clientID string, clientSecret string, scopes []string, redirectUri string ) *oauth2.Config {
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: scopes,
RedirectURL: redirectUri,
Endpoint: oauth2.Endpoint{
AuthURL: server+"/login/oauth/authorize",
TokenURL: server+"/login/oauth/access_token",
},
}
}
// returns the OAuth2 authentification url, the user has to visit
func AuthUrl ( server string, clientID string, clientSecret string, scopes []string, redirectUri string ) string {
conf := CreateConf ( server, clientID, clientSecret, scopes, redirectUri )
url := conf.AuthCodeURL("", oauth2.AccessTypeOnline)
return url
}
// create a client-connection with a (hopefully) valid OAuth2 Auth Token
func ConnectWithToken ( server string, clientID string, clientSecret string, scopes []string, tok *oauth2.Token, redirectUri string ) (*http.Client) {
ctx := context.Background()
conf := CreateConf ( server, clientID, clientSecret, scopes, redirectUri )
client := conf.Client(ctx, tok)
return client
}
// create a client-connection with an auth-code from the user, to get a token
func Connect ( server string, clientID string, clientSecret string, scopes []string, redirectUri string, authCode string ) (*http.Client, *oauth2.Token, error) {
ctx := context.Background()
conf := CreateConf ( server, clientID, clientSecret, scopes, redirectUri )
tok, err := conf.Exchange(ctx, authCode)
if err != nil {
//die()
fmt.Printf("Error: %+v\n", err)
return nil, nil, err
} else {
client := conf.Client(ctx, tok)
return client, tok, nil
}
}