-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathContentstack.cs
More file actions
290 lines (266 loc) · 11.1 KB
/
Contentstack.cs
File metadata and controls
290 lines (266 loc) · 11.1 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Tests.Helpers;
using Contentstack.Management.Core.Tests.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Contentstack.Management.Core.Tests
{
public class Contentstack
{
private static readonly Lazy<IConfigurationRoot>
config =
new Lazy<IConfigurationRoot>(() =>
{
return new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
});
private static readonly Lazy<NetworkCredential> credential =
new Lazy<NetworkCredential>(() =>
{
return Config.GetSection("Contentstack:Credentials").Get<NetworkCredential>();
});
private static readonly Lazy<OrganizationModel> organization =
new Lazy<OrganizationModel>(() =>
{
return Config.GetSection("Contentstack:Organization").Get<OrganizationModel>();
});
private static readonly Lazy<string> mfaSecret =
new Lazy<string>(() =>
{
return Config.GetSection("Contentstack:MfaSecret").Value;
});
public static IConfigurationRoot Config{ get { return config.Value; } }
public static NetworkCredential Credential { get { return credential.Value; } }
public static OrganizationModel Organization { get { return organization.Value; } }
public static string MfaSecret { get { return mfaSecret.Value; } }
public static StackModel Stack { get; set; }
// TOTP token tracking to prevent reuse
private static readonly HashSet<string> _usedTotpTokens = new HashSet<string>();
private static DateTime _lastTotpGeneration = DateTime.MinValue;
private static readonly object _totpLock = new object();
/// <summary>
/// Checks if the exception indicates TOTP token reuse
/// </summary>
public static bool IsTotpReuse(Exception exception)
{
if (exception is ContentstackErrorException csException)
{
return csException.ErrorMessage?.Contains("Totp has already been Used") == true;
}
return false;
}
/// <summary>
/// Checks if the exception indicates an account lockout
/// </summary>
public static bool IsAccountLockout(Exception exception)
{
if (exception is ContentstackErrorException csException)
{
return csException.ErrorCode == 104 &&
(csException.ErrorMessage?.Contains("locked") == true ||
csException.ErrorMessage?.Contains("temporarily") == true);
}
return false;
}
/// <summary>
/// Ensures sufficient time has passed for fresh TOTP token generation
/// </summary>
public static void EnsureFreshTotpWindow()
{
lock (_totpLock)
{
var timeSinceLastTotp = DateTime.UtcNow - _lastTotpGeneration;
if (timeSinceLastTotp.TotalSeconds < 35)
{
int sleepMs = (int)(35000 - timeSinceLastTotp.TotalMilliseconds);
System.Threading.Thread.Sleep(sleepMs);
}
// Clean up old tokens (older than 2 minutes)
var cutoff = DateTime.UtcNow.AddMinutes(-2);
if (_lastTotpGeneration < cutoff)
{
_usedTotpTokens.Clear();
}
_lastTotpGeneration = DateTime.UtcNow;
}
}
/// <summary>
/// Executes login with retry logic for account lockouts
/// </summary>
public static ContentstackResponse LoginWithRetry(ContentstackClient client, int maxRetries = 3, int baseDelayMs = 5000)
{
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
return client.Login(Credential, null, MfaSecret);
}
catch (Exception ex) when (IsAccountLockout(ex) && attempt < maxRetries)
{
int delay = baseDelayMs * (int)Math.Pow(2, attempt); // Exponential backoff
System.Threading.Thread.Sleep(delay);
}
}
// Final attempt without catching lockout
return client.Login(Credential, null, MfaSecret);
}
/// <summary>
/// Executes async login with retry logic for account lockouts
/// </summary>
public static async Task<ContentstackResponse> LoginWithRetryAsync(ContentstackClient client, int maxRetries = 3, int baseDelayMs = 5000)
{
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
return await client.LoginAsync(Credential, null, MfaSecret);
}
catch (Exception ex) when (IsAccountLockout(ex) && attempt < maxRetries)
{
int delay = baseDelayMs * (int)Math.Pow(2, attempt); // Exponential backoff
await Task.Delay(delay);
}
}
// Final attempt without catching lockout
return await client.LoginAsync(Credential, null, MfaSecret);
}
/// <summary>
/// Executes login with TOTP-aware retry logic for token reuse and account lockouts
/// </summary>
public static ContentstackResponse LoginWithTotpRetry(ContentstackClient client, int maxRetries = 3)
{
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
// Ensure fresh TOTP window before each attempt
EnsureFreshTotpWindow();
return client.Login(Credential, null, MfaSecret);
}
catch (Exception ex) when (attempt < maxRetries)
{
if (IsTotpReuse(ex))
{
// Wait for fresh TOTP window (35+ seconds)
System.Threading.Thread.Sleep(35000);
}
else if (IsAccountLockout(ex))
{
// Exponential backoff for account lockout
int delay = 5000 * (int)Math.Pow(2, attempt);
System.Threading.Thread.Sleep(delay);
}
else
{
// For other errors, short delay before retry
System.Threading.Thread.Sleep(1000);
}
}
}
// Final attempt without catching errors
EnsureFreshTotpWindow();
return client.Login(Credential, null, MfaSecret);
}
/// <summary>
/// Executes async login with TOTP-aware retry logic for token reuse and account lockouts
/// </summary>
public static async Task<ContentstackResponse> LoginWithTotpRetryAsync(ContentstackClient client, int maxRetries = 3)
{
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
try
{
// Ensure fresh TOTP window before each attempt
EnsureFreshTotpWindow();
return await client.LoginAsync(Credential, null, MfaSecret);
}
catch (Exception ex) when (attempt < maxRetries)
{
if (IsTotpReuse(ex))
{
// Wait for fresh TOTP window (35+ seconds)
await Task.Delay(35000);
}
else if (IsAccountLockout(ex))
{
// Exponential backoff for account lockout
int delay = 5000 * (int)Math.Pow(2, attempt);
await Task.Delay(delay);
}
else
{
// For other errors, short delay before retry
await Task.Delay(1000);
}
}
}
// Final attempt without catching errors
EnsureFreshTotpWindow();
return await client.LoginAsync(Credential, null, MfaSecret);
}
/// <summary>
/// Creates a new ContentstackClient, logs in via the Login API (never from config),
/// and returns the authenticated client. Callers are responsible for calling Logout()
/// when done.
/// </summary>
public static ContentstackClient CreateAuthenticatedClient()
{
ContentstackClientOptions options = Config.GetSection("Contentstack").Get<ContentstackClientOptions>();
options.Authtoken = null;
var handler = new LoggingHttpHandler();
var httpClient = new HttpClient(handler);
var client = new ContentstackClient(httpClient, options);
LoginWithTotpRetry(client);
return client;
}
public static T serialize<T>(JsonSerializer serializer, string filePath)
{
string response = GetResourceText(filePath);
JObject jObject = JObject.Parse(response);
return jObject.ToObject<T>(serializer);
}
public static T serializeArray<T>(JsonSerializer serializer, string filePath)
{
string response = GetResourceText(filePath);
JArray jObject = JArray.Parse(response);
return jObject.ToObject<T>(serializer);
}
public static string GetResourceText(string resourceName)
{
using (StreamReader reader = new StreamReader(GetResourceStream(resourceName)))
{
return reader.ReadToEnd();
}
}
public static Stream GetResourceStream(string resourceName)
{
Assembly assembly = typeof(Contentstack).Assembly;
var resource = FindResourceName(resourceName);
Stream stream = assembly.GetManifestResourceStream(resource);
return stream;
}
public static string FindResourceName(string partialName)
{
return FindResourceName(s => s.IndexOf(partialName, StringComparison.OrdinalIgnoreCase) >= 0).Single();
}
public static IEnumerable<string> FindResourceName(Predicate<string> match)
{
Assembly assembly = typeof(Contentstack).Assembly;
var allResources = assembly.GetManifestResourceNames();
foreach (var resource in allResources)
{
if (match(resource))
yield return resource;
}
}
}
}