-
Notifications
You must be signed in to change notification settings - Fork 7
/
CliWrapper.cs
247 lines (194 loc) · 7.43 KB
/
CliWrapper.cs
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
public class CliWrapper
{
ConfigData configData = new ConfigData();
public CliWrapper()
{ }
public async Task<bool> IsAuth0CliInstalled()
{
bool result = false;
try
{
string cmdOutput = await RunCommand("auth0", "--version");
string currentCliVersionString = cmdOutput.Split(" ")[2];
Version currentCliVersion = new Version(currentCliVersionString);
Displayer.DisplayVerbose($@"Auth0 CLI version: {currentCliVersionString}");
result = currentCliVersion.CompareTo(new Version("1.0.1")) >= 0;
}
catch (Exception ex)
{
Displayer.DisplayErrorVerbose(ex.Message);
}
return result;
}
public async Task<RegistrationData> Register()
{
var registrationData = new RegistrationData("", "", "", new SigningKeys[] {new SigningKeys("")});
var registrationOutputText = "";
try
{
string templateConfigurationFilePath = $@"{Path.Combine(System.AppContext.BaseDirectory, "config.json")}";
Displayer.DisplayVerbose($@"Reading template configuration from {templateConfigurationFilePath}");
string text = File.ReadAllText(templateConfigurationFilePath);
Displayer.DisplayTemplateConfiguration(text);
configData = JsonSerializer.Deserialize<ConfigData>(text);
if (configData.AppType.ToLower() == "api")
{
registrationOutputText = await RunCommand("auth0", $"apis create --name {configData.AppName} --identifier {CreateAudience(configData.AppName)} --no-input --json");
Console.WriteLine("API registered!");
}
else
{
registrationOutputText = await RunCommand("auth0", $"apps create --name {configData.AppName} --description \"{configData.AppDescription}\" --type {configData.AppType} --callbacks \"{configData.Callbacks}\" --logout-urls \"{configData.LogoutUrls}\" --no-input --reveal-secrets --json");
Console.WriteLine("Application registered!");
}
} catch (Exception ex)
{
Displayer.DisplayError(ex.Message);
}
try
{
registrationData = JsonSerializer.Deserialize<RegistrationData>(registrationOutputText)!;
}
catch (Exception ex)
{
Console.WriteLine("ERROR: ************");
Console.WriteLine($@"{ex.Message}");
Console.WriteLine();
Console.WriteLine("Registration output: -------");
Console.WriteLine($@"{registrationOutputText}");
Console.WriteLine("*******************");
}
return registrationData;
}
public async Task UpdateConfigFiles(RegistrationData registrationData)
{
foreach (var settingsFile in configData.AppSettingsFiles)
{
Displayer.DisplayVerbose($@"Reading settings from {settingsFile}");
string text = File.ReadAllText($@"{settingsFile}");
Displayer.DisplayAppSettings(text);
string currentDomain = await GetCurrentDomain(registrationData);
if (!string.IsNullOrEmpty(currentDomain))
{
text = text.Replace("yourdomain.auth0.com", currentDomain);
}
if (!string.IsNullOrEmpty(registrationData.client_id))
{
text = text.Replace("your-client-id", registrationData.client_id);
}
if (!string.IsNullOrEmpty(registrationData.identifier))
{
text = text.Replace("https://your-api-id.com", registrationData.identifier);
}
Displayer.DisplayNewAppSettings(text);
File.WriteAllText($@"{settingsFile}", text);
}
}
public async Task RemoveRegistrationFolder()
{
string registrationFolderPath = $@"{Path.Combine(System.AppContext.BaseDirectory)}";
Displayer.DisplayVerbose($@"About to remove the folder {registrationFolderPath}");
if (Environment.OSVersion.Platform == PlatformID.Unix ||
Environment.OSVersion.Platform == PlatformID.MacOSX)
{
Directory.Delete(registrationFolderPath, true);
} else
{
// Hack to bypass executable lock in Windows (https://andreasrohner.at/posts/Programming/C%23/A-platform-independent-way-for-a-C%23-program-to-update-itself/)
var delScriptName = Path.Combine(registrationFolderPath, "selfdel.bat");
using (var batFile = new StreamWriter (File.Create (delScriptName))) {
batFile.WriteLine ("@ECHO OFF");
batFile.WriteLine ("TIMEOUT /t 5 /nobreak > NUL");
batFile.WriteLine ($@"RMDIR /S /Q {registrationFolderPath}");
}
RunCommandAndForget(delScriptName, "");
Environment.Exit(0);
}
}
private async Task<string> RunCommand(string command, string args)
{
ProcessStartInfo startInfo = new()
{
FileName = command,
Arguments = args,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
Displayer.DisplayVerbose($@"About to run command: {command} {args}");
var proc = Process.Start(startInfo);
ArgumentNullException.ThrowIfNull(proc);
string output = proc.StandardOutput.ReadToEnd();
string errorText = proc.StandardError.ReadToEnd();
await proc.WaitForExitAsync();
if (!string.IsNullOrEmpty(errorText) && errorText.Contains("error"))
{
throw new Exception(errorText);
}
Displayer.DisplayCommandOutput(output);
return output;
}
private void RunCommandAndForget(string command, string args)
{
ProcessStartInfo startInfo = new()
{
FileName = command,
Arguments = args,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
Displayer.DisplayVerbose($@"About to launch command: {command} {args}");
var proc = Process.Start(startInfo);
}
private string CreateAudience(string appName)
{
Displayer.DisplayVerbose($@"Application name to tranform into audience: {appName}");
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
appName = rgx.Replace(appName, "-");
var audience = $@"https://{appName.ToLower()}.com";
Displayer.DisplayVerbose($@"Resulting audience: {audience}");
return audience;
}
private async Task<string> GetCurrentDomain(RegistrationData registrationData)
{
string currentDomain = "";
if (registrationData.signing_keys != null && registrationData.signing_keys.Length > 0 && !string.IsNullOrEmpty(registrationData.signing_keys[0].subject))
{
Displayer.DisplayVerbose($@"Certificate subject: {registrationData.signing_keys[0].subject}");
currentDomain = registrationData.signing_keys[0].subject.Replace("/CN=", "");
} else
{
currentDomain = await GetCurrentDomain();
}
Displayer.DisplayVerbose($@"Current domain: {currentDomain}");
return currentDomain;
}
private async Task<string> GetCurrentDomain()
{
string currentDomain = "";
string registrationDataListText = await RunCommand("auth0", "apis list -n 1 --json");
try
{
var registrationDataList = JsonSerializer.Deserialize<RegistrationData[]>(registrationDataListText)!;
Displayer.DisplayVerbose($@"Found {registrationDataList.Length} registered APIs.");
if (registrationDataList.Length > 0)
{
var registrationData = registrationDataList[0];
if (!string.IsNullOrEmpty(registrationData.identifier))
{
Displayer.DisplayVerbose($@"System API identifier: {registrationData.identifier}");
currentDomain = new Uri(registrationData.identifier).Host;
}
}
}
catch (Exception ex)
{
Displayer.DisplayError(ex.Message);
}
return currentDomain;
}
}