Skip to content

Commit 0eafe5b

Browse files
committed
done refactoring and auth
1 parent e2a5bbc commit 0eafe5b

File tree

11 files changed

+197
-41
lines changed

11 files changed

+197
-41
lines changed

.phlow

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
issue_url = https://api.github.com
66
pipeline_url = http://concourse.bosh.praqma.cloud/teams/main/pipelines/git-phlow
77
delivery_branch_prefix = ready
8+
89
[jira]
9-
service = sd
10-
integration_branch = gh_pages
11-
remote = fork
12-
repo_url = jira
10+
integration_branch = master
11+
remote = origin
12+
service = http://jira.teamsinspace.com:8080
1313
issue_url = jira
14-
delivery_branch_prefix = integrateme
14+
pipeline_url = http://concourse.bosh.praqma.cloud/teams/main/pipelines/git-phlow
15+
delivery_branch_prefix = ready

ci/test/test.sh

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ export PATH=$PATH:$GOPATH/bin
77

88
# RESOLVE DEPENDENCIES - TEST AND PRODUCTION
99
cd $GOPATH/src/github.com/praqma/git-phlow
10-
go get -t -d -v ./...
10+
go get -t -v ./...
1111

1212
#install ginkgo
1313
go install github.com/onsi/ginkgo/ginkgo
1414

1515

1616
# run tests
17-
go test -p 1 -v ./...
17+
go test -v ./...
1818

1919

2020

cmd/auth.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,28 @@ import (
66
"github.com/praqma/git-phlow/phlow"
77
"github.com/praqma/git-phlow/ui"
88
"github.com/spf13/cobra"
9+
"github.com/praqma/git-phlow/options"
910
)
1011

1112
//enable command
1213
var authCmd = &cobra.Command{
1314
Use: "auth",
14-
Short: "authenticate with github",
15+
Short: "authenticate with different services",
1516
Long: fmt.Sprintf(`
16-
%s is required to enable 'workon' with issue management.
17-
Auth will prompt you for a GitHub username and password to generate a token.
18-
Don't worry, the token does not include admininstrator rights, only access to manage issues for public repositories.
17+
%s will authenticate to a service specified in your .phlow or .gitconfig files. It will use the default service if no other is specified.
18+
Auth supports two services:
19+
- Jira
20+
- GitHub
1921
`, ui.Format.Bold("auth")),
2022
Run: func(cmd *cobra.Command, args []string) {
23+
2124
phlow.AuthCaller()
25+
2226
},
2327
}
2428

2529
func init() {
2630
RootCmd.AddCommand(authCmd)
31+
32+
authCmd.Flags().StringVarP(&options.GlobalFlagTarget, "target", "t", "", "the name of the INI block in your .phlow files")
2733
}

docs/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
### phlow auth
2+
```
3+
git phlow auth -t <target>
4+
```
5+
Git phlow auth, authorizes towards a chosen service which can be either `github` or `jira`. Auth is used by git phlow to access and manage issues in your chosen provider.
6+
7+
Auth is dependent on a configuration file unless you are using GitHub.com for your issues and Repositories, in that case you can complete omit using the `--target` flag
8+
9+
#### Self hosted services or Jira
10+
To authenticate with your own hosted service or Jira you _must_ provide a valid configuration (see **Configuration** section). Your configuration must contain a base url to where your service is hosted and the name of the service. When authenticating set your `--target` to the name of the configuration e.g.
11+
12+
```ini
13+
[myjiraconfig]
14+
integration_branch = master
15+
remote = origin
16+
service = jira
17+
issue_url = https://my.jira.instance.com
18+
delivery_branch_prefix = ready
19+
```
20+
```bash
21+
git phlow auth --target myjiraconfig
22+
```
23+
124
### Configuration
225
git phlow is configured via `.phlow`, or `.gitignore` files., in your local workspace or in the home folder of your computer. The configuration is standard INI files, just like gitconfig.
326

githandler/git.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,16 @@ func (os *Git) Merge(argv ...string) (string, error) {
7474
return os.Run("git", "merge", argv...)
7575
}
7676

77+
//Config ...
78+
//Executes local git config with params
79+
func (os *Git) Config(argv ...string) (string, error) {
80+
stdOut, stdErr := os.Run("git", "config", argv...)
81+
if stdErr != nil {
82+
return "", stdErr
83+
}
84+
return strings.Replace(stdOut, "\n", "", -1), nil
85+
}
86+
7787
//DEPRECATESD SECTION ---------------------------------------------------------------
7888
//FormatPatch ...
7989
//dry runs patch to see if we can auto merge

main.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package main
22

3-
import (
4-
"github.com/praqma/git-phlow/cmd"
5-
)
3+
import "github.com/praqma/git-phlow/cmd"
64

75
func main() {
86
cmd.Execute()

options/option.go

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ var (
3535
//GlobalFlagForce ...
3636
GlobalFlagForceMessage string
3737

38+
//GlobalFlagTarget ...
39+
GlobalFlagTarget string
40+
3841
//Sha1 git commit hash
3942
Sha1 string
4043

@@ -43,16 +46,10 @@ var (
4346

4447
//Date date of build
4548
Date string
46-
)
47-
48-
func init() {
49-
50-
}
51-
52-
func windows() {
53-
54-
}
5549

56-
func unix() {
50+
//AuthFlagJira ...
51+
AuthFlagJira = false
5752

58-
}
53+
//AuthFlagGitHub ...
54+
AuthFlagGitHub = false
55+
)

phlow/auth.go

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,41 @@ import (
1212
"github.com/praqma/git-phlow/plugins"
1313
"github.com/praqma/git-phlow/executor"
1414
"github.com/praqma/git-phlow/setting"
15+
"github.com/praqma/git-phlow/githandler"
16+
"github.com/praqma/git-phlow/options"
1517
)
1618

1719
//AuthCaller
1820
//Wraps auth and injects dependencies
1921
func AuthCaller() {
20-
cf := setting.GitConfig{Run: executor.RunCommand}
21-
Auth(cf)
22+
INIBlock := options.GlobalFlagTarget
23+
conf := setting.NewProjectStg(INIBlock)
24+
25+
if "jira" == strings.ToLower(conf.Service) {
26+
Auth(INIBlock, plugins.AuthorizeJIRA, plugins.AuthenticateJIRA, "phlow.jirauser", "phlow.jiratoken", conf.Service)
27+
}
28+
29+
Auth(INIBlock, plugins.AuthorizeGitHub, plugins.AuthenticateGitHub, "phlow.user", "phlow.token", conf.Service)
2230
}
2331

2432
//Auth ...
25-
//Authenticates the user
26-
func Auth(cf setting.Configurator) {
27-
token := cf.Get(setting.PhlowToken)
28-
user := cf.Get(setting.PhlowUser)
33+
func Auth(INIBlock string, authorization plugins.Authorization, authentication plugins.Authentication, configUser string, configToken string, service string) {
34+
conf := setting.NewProjectStg(INIBlock)
35+
git := githandler.Git{Run: executor.RunGit}
36+
37+
token, err := git.Config("--get", configToken)
38+
user, err := git.Config("--get", configUser)
2939

3040
if token != "" && user != "" {
31-
fmt.Println("Checking token validity...")
32-
isAuthenticated, err := plugins.GitHub.CheckAuth()
41+
fmt.Printf("Checking token validity for %s... \n", service)
42+
isAuthenticated, err := authentication(conf.IssueURL, user, token)
3343
if !isAuthenticated {
3444
fmt.Println("Token test expected HTTP code 200 but received " + err.Error())
3545
if ReadInput("Delete local token and reauthenticate? (y/n): ", os.Stdin) == "y" {
3646
fmt.Println("Deleting local token and reauthenticating...")
37-
cf.Unset(setting.PhlowToken)
38-
cf.Unset(setting.PhlowUser)
39-
AuthCaller()
47+
git.Config("--global", "--unset", configUser)
48+
git.Config("--global", "--unset", configToken)
49+
Auth(conf.INIBlock, authorization, authentication, configUser, configToken, service)
4050
} else {
4151
fmt.Println("Aborting...")
4252
}
@@ -46,21 +56,21 @@ func Auth(cf setting.Configurator) {
4656
return
4757
}
4858

49-
fmt.Fprintf(os.Stdout, "Enter credentials for %s \n", "GitHub")
59+
fmt.Fprintf(os.Stdout, "Enter credentials for %s \n", service)
5060

5161
//Read user input username
5262
username := ReadInput("username: ", os.Stdin)
5363
//Read user input password
5464
password := ReadPassword("password: ")
5565

56-
token, err := plugins.GitHub.Auth(username, password)
66+
_, err = authorization(conf.IssueURL, username, password)
5767
if err != nil {
5868
fmt.Println()
5969
fmt.Println(err)
6070
return
6171
}
62-
cf.Set(setting.PhlowUser, username)
63-
cf.Set(setting.PhlowToken, token)
72+
_, err = git.Config("--global", configUser, password)
73+
_, err = git.Config("--global", configToken, username)
6474

6575
fmt.Println("")
6676
fmt.Println(fmt.Sprintf("%s Successfully authorized: 'git phlow' is now enabled", username))

plugins/gh.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,64 @@ func init() {
5555
}
5656
}
5757

58+
//AuthorizeGitHub ...
59+
//Retrieve token from github for authorization
60+
func AuthorizeGitHub(githubBaseURL, user, pass string) (token string, err error) {
61+
62+
perm, err := createGHPermissions()
63+
if err != nil {
64+
return "", err
65+
}
66+
67+
req, _ := http.NewRequest("POST", githubBaseURL+"/authorizations", bytes.NewBuffer([]byte(perm)))
68+
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
69+
req.SetBasicAuth(user, pass)
70+
client := http.DefaultClient
71+
72+
res, err := client.Do(req)
73+
if err != nil {
74+
return "", err
75+
}
76+
77+
err = requestStatus(res)
78+
if err != nil {
79+
return "", err
80+
}
81+
defer res.Body.Close()
82+
83+
re := Auth{}
84+
err = json.NewDecoder(res.Body).Decode(re)
85+
if err != nil {
86+
return "", err
87+
}
88+
return re.Token, nil
89+
}
90+
91+
//AuthenticateGitHub
92+
//Checks personal access token validity by requesting private repositories and checking status code
93+
func AuthenticateGitHub(githubBaseURL string, user, token string) (bool, error) {
94+
95+
req, _ := http.NewRequest("GET", githubBaseURL+"/user/repos", nil)
96+
q := req.URL.Query()
97+
q.Add("access_token", token)
98+
req.URL.RawQuery = q.Encode()
99+
client := http.DefaultClient
100+
101+
res, err := client.Do(req)
102+
if err != nil {
103+
return false, err
104+
}
105+
defer res.Body.Close()
106+
107+
if res.StatusCode != http.StatusOK {
108+
return false, errors.New(strconv.Itoa(res.StatusCode))
109+
}
110+
return true, nil
111+
}
112+
113+
114+
// ------------------------------------------ DEPRECATE SECTION
115+
58116
//GetIssues ...
59117
func (g *GitHubImpl) GetIssues() (issues []Issue, err error) {
60118
URL := fmt.Sprintf(g.URLNoEsc(urls.issueURL), g.org, g.repo)
@@ -98,6 +156,7 @@ func (g *GitHubImpl) SetLabel(label string, issue int) (labels []Label, err erro
98156
return re, nil
99157
}
100158

159+
101160
//Default ...
102161
//Get default branch of a GitHub issue
103162
func (g *GitHubImpl) Default() (defaultBranch string, err error) {

plugins/jira.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package plugins
2+
3+
import (
4+
"net/http"
5+
"github.com/go-errors/errors"
6+
)
7+
8+
9+
//AuthenticateJIRA ...
10+
func AuthenticateJIRA(url, user, pass string) (bool, error) {
11+
verifyURL := "/rest/api/latest/mypermissions"
12+
req, _ := http.NewRequest("GET", url+verifyURL, nil)
13+
req.Header.Set("Content-Type", "application/json")
14+
req.SetBasicAuth(user, pass)
15+
client := http.DefaultClient
16+
17+
res, err := client.Do(req)
18+
if err != nil {
19+
return false, err
20+
}
21+
defer res.Body.Close()
22+
23+
if res.StatusCode != 200 {
24+
return false, errors.New("Could not verify credentials")
25+
}
26+
return true, nil
27+
}
28+
29+
//AuthorizeJIRA ...
30+
//JIRA basic auth do not require authorization, so we just validate the user have giving right credentials with AuthenticateJIRA
31+
func AuthorizeJIRA(URL, user, pass string) (token string, err error) {
32+
33+
authorized, err := AuthenticateJIRA(URL, user, pass)
34+
if err != nil {
35+
return "", err
36+
}
37+
38+
if authorized == false {
39+
return "", errors.New("not authorized")
40+
}
41+
42+
return pass, nil
43+
}

0 commit comments

Comments
 (0)