/
oauth.go
107 lines (86 loc) · 2.53 KB
/
oauth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"context"
"fmt"
"github.com/urfave/cli"
"github.com/manifoldco/manifold-cli/analytics"
"github.com/manifoldco/manifold-cli/api"
"github.com/manifoldco/manifold-cli/config"
"github.com/manifoldco/manifold-cli/errs"
"github.com/manifoldco/manifold-cli/prompts"
"github.com/manifoldco/manifold-cli/session"
)
var (
linkedOK = "Your Manifold account is now linked"
)
func init() {
oauthCmd := cli.Command{
Name: "oauth",
Usage: "Authenticate with an OAuth provider to register, login or link accounts",
Category: "AUTHENTICATION",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "github",
Usage: "Use the web flow for GitHub authentication",
},
},
Action: oauth,
}
cmds = append(cmds, oauthCmd)
}
func oauth(cliCtx *cli.Context) error {
ctx := context.Background()
if cliCtx.NumFlags() < 1 {
return errs.NewUsageExitError(cliCtx,
cli.NewExitError("You must provide an authentication mechanism", -1))
}
cfg, a, err := loadConfigAndAnalytics()
if err != nil {
return cli.NewExitError(fmt.Sprintf("Unable to load configuration: %s", err), -1)
}
s, err := session.Retrieve(ctx, cfg)
if err != nil {
cli.NewExitError(fmt.Sprintf("Could not retrieve session: %s", err), -1)
}
if s.Authenticated() {
// link
_, err := prompts.Confirm("Do you wish to link your GitHub account to Manifold")
if err != nil {
return cli.NewExitError(fmt.Sprintf("Could not link accounts: %s", err), -1)
}
err = authenticateOAuth(ctx, cliCtx, cfg, a, "link")
if err != nil {
return cli.NewExitError(fmt.Sprintf("Unable to link accounts: %s", err), -1)
}
return cli.NewExitError(linkedOK, 0)
}
// registration + login
err = authenticateOAuth(ctx, cliCtx, cfg, a, "login")
if err != nil {
return cli.NewExitError(fmt.Sprintf("Could not login with OAuth provider: %s", err), -1)
}
fmt.Println("You are logged in, hooray!")
return nil
}
func loadConfigAndAnalytics() (*config.Config, *analytics.Analytics, error) {
cfg, err := config.Load()
if err != nil {
return nil, nil, cli.NewExitError(fmt.Sprintf("Unable to load config: %s", err), -1)
}
a, err := api.New(api.Analytics)
if err != nil {
return nil, nil, cli.NewExitError("A problem occurred: "+err.Error(), -1)
}
return cfg, a.Analytics, nil
}
func authenticateOAuth(ctx context.Context, cliCtx *cli.Context, cfg *config.Config,
a *analytics.Analytics, stateType string) error {
var err error
if cliCtx.Bool("github") {
err = githubWithCallback(ctx, cfg, a, stateType)
if err != nil {
return err
}
}
return nil
}