-
Notifications
You must be signed in to change notification settings - Fork 5
/
auth.go
182 lines (154 loc) · 4.13 KB
/
auth.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"github.com/KarpelesLab/rest"
)
const clientID = "oaap-wyslxk-7aqv-gbva-57y7-einuc2a4"
type authInfo struct {
token *rest.Token
name string
filepath string
}
func checkLogin() (*authInfo, error) {
// let's check if we have a token stored in config
auth := &authInfo{
name: "default",
}
if v := os.Getenv("SHELLS_PROFILE"); v != "" {
auth.name = v
}
if err := auth.init(); err != nil {
return nil, err
}
if err := auth.load(); err != nil {
// attempt to do auth
if errors.Is(err, os.ErrNotExist) {
log.Printf("no login information found, logging in...")
} else {
log.Printf("failed to load login (%s), logging in...", err)
}
err = auth.login()
if err != nil {
return nil, err
}
err = auth.save()
if err != nil {
return nil, err
}
}
return auth, nil
}
func (auth *authInfo) init() error {
cnf, err := os.UserConfigDir()
if err != nil {
return fmt.Errorf("failed to locate conf dir: %w", err)
}
cnf = filepath.Join(cnf, "shells-cli")
os.MkdirAll(cnf, 0700) // make sure dir exists
cnf = filepath.Join(cnf, "auth-"+auth.name+".json")
auth.filepath = cnf
return nil
}
func (auth *authInfo) load() error {
// no error, file exists. Load it
data, err := os.ReadFile(auth.filepath)
if err != nil {
return fmt.Errorf("failed to read auth: %w", err)
}
if err := json.Unmarshal(data, &auth.token); err != nil {
return err
}
auth.token.ClientID = clientID
return nil
}
func (auth *authInfo) save() error {
if auth.token == nil {
return os.ErrNotExist
}
// save token
data, err := json.Marshal(auth.token)
if err != nil {
return err
}
return os.WriteFile(auth.filepath, data, 0600)
}
func (auth *authInfo) login() error {
// prepare to login
// we need a realtime token
var res map[string]any
err := rest.Apply(context.Background(), "OAuth2/App/"+clientID+":token_create", "POST", map[string]any{}, &res)
if err != nil {
return err
}
tok, ok := res["polltoken"].(string)
if !ok {
return fmt.Errorf("failed to fetch polltoken")
}
// see: https://www.shells.com/.well-known/openid-configuration?pretty
tokuri := url.QueryEscape("polltoken:" + tok)
fulluri := fmt.Sprintf("https://www.shells.com/_rest/OAuth2:auth?response_type=code&client_id=%s&redirect_uri=%s&scope=profile", clientID, tokuri)
if u, ok := res["xox"].(string); ok {
fulluri = u
}
log.Printf("Please open this URL in order to access shells:\n%s", fulluri)
// wait for login to complete
for {
var res map[string]any
err := rest.Apply(context.Background(), "OAuth2/App/"+clientID+":token_poll", "POST", map[string]any{"polltoken": tok}, &res)
if err != nil {
return err
}
v, ok := res["response"]
if !ok {
time.Sleep(time.Second) // just in case
continue
}
resp, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid response from api, response of invalid type")
}
code, ok := resp["code"].(string)
if !ok {
return fmt.Errorf("invalid response from api, response not containing code")
}
log.Printf("fetching auth token...")
// https://www.shells.com/_special/rest/OAuth2:token
httpresp, err := http.PostForm("https://www.shells.com/_special/rest/OAuth2:token", url.Values{"client_id": {clientID}, "grant_type": {"authorization_code"}, "code": {code}})
if err != nil {
return fmt.Errorf("while fetching token: %w", err)
}
defer httpresp.Body.Close()
if httpresp.StatusCode != 200 {
return fmt.Errorf("invalid status code from server: %s", httpresp.Status)
}
body, err := io.ReadAll(httpresp.Body)
if err != nil {
return fmt.Errorf("while reading token: %w", err)
}
// decode token
err = json.Unmarshal(body, &auth.token)
if err != nil {
return fmt.Errorf("while decoding token: %w", err)
}
auth.token.ClientID = clientID
return nil
}
}
func (auth *authInfo) Apply(ctx context.Context, p, m string, arg map[string]any, target interface{}) error {
err := rest.Apply(auth.token.Use(ctx), p, m, arg, target)
if err != nil {
return err
}
auth.save() // perform save just in case token was updated
return nil
}