This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathLoginManager.cs
More file actions
262 lines (236 loc) · 10.1 KB
/
LoginManager.cs
File metadata and controls
262 lines (236 loc) · 10.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
using System;
using System.Net;
using System.Threading.Tasks;
using GitHub.Extensions;
using GitHub.Primitives;
using Octokit;
namespace GitHub.Api
{
/// <summary>
/// Provides services for logging into a GitHub server.
/// </summary>
public class LoginManager : ILoginManager
{
readonly string[] scopes = { "user", "repo", "gist", "write:public_key" };
readonly IKeychain keychain;
readonly Lazy<ITwoFactorChallengeHandler> twoFactorChallengeHandler;
readonly string clientId;
readonly string clientSecret;
readonly string authorizationNote;
readonly string fingerprint;
/// <summary>
/// Initializes a new instance of the <see cref="LoginManager"/> class.
/// </summary>
/// <param name="keychain">The keychain in which to store credentials.</param>
/// <param name="twoFactorChallengeHandler">The handler for 2FA challenges.</param>
/// <param name="clientId">The application's client API ID.</param>
/// <param name="clientSecret">The application's client API secret.</param>
/// <param name="authorizationNote">An note to store with the authorization.</param>
/// <param name="fingerprint">The machine fingerprint.</param>
public LoginManager(
IKeychain keychain,
Lazy<ITwoFactorChallengeHandler> twoFactorChallengeHandler,
string clientId,
string clientSecret,
string authorizationNote = null,
string fingerprint = null)
{
Guard.ArgumentNotNull(keychain, nameof(keychain));
Guard.ArgumentNotNull(twoFactorChallengeHandler, nameof(twoFactorChallengeHandler));
Guard.ArgumentNotEmptyString(clientId, nameof(clientId));
Guard.ArgumentNotEmptyString(clientSecret, nameof(clientSecret));
this.keychain = keychain;
this.twoFactorChallengeHandler = twoFactorChallengeHandler;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.authorizationNote = authorizationNote;
this.fingerprint = fingerprint;
}
/// <inheritdoc/>
public async Task<User> Login(
HostAddress hostAddress,
IGitHubClient client,
string userName,
string password)
{
Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
Guard.ArgumentNotNull(client, nameof(client));
Guard.ArgumentNotEmptyString(userName, nameof(userName));
Guard.ArgumentNotEmptyString(password, nameof(password));
// Start by saving the username and password, these will be used by the `IGitHubClient`
// until an authorization token has been created and acquired:
await keychain.Save(userName, password, hostAddress).ConfigureAwait(false);
var newAuth = new NewAuthorization
{
Scopes = scopes,
Note = authorizationNote,
Fingerprint = fingerprint,
};
ApplicationAuthorization auth = null;
do
{
try
{
auth = await CreateAndDeleteExistingApplicationAuthorization(client, newAuth, null)
.ConfigureAwait(false);
EnsureNonNullAuthorization(auth);
}
catch (TwoFactorAuthorizationException e)
{
auth = await HandleTwoFactorAuthorization(hostAddress, client, newAuth, e)
.ConfigureAwait(false);
}
catch (Exception e)
{
// Some enterpise instances don't support OAUTH, so fall back to using the
// supplied password - on intances that don't support OAUTH the user should
// be using a personal access token as the password.
if (EnterpriseWorkaround(hostAddress, e))
{
auth = new ApplicationAuthorization(password);
}
else
{
await keychain.Delete(hostAddress).ConfigureAwait(false);
throw;
}
}
} while (auth == null);
await keychain.Save(userName, auth.Token, hostAddress).ConfigureAwait(false);
var retry = 0;
while (true)
{
try
{
return await client.User.Current().ConfigureAwait(false);
}
catch (AuthorizationException)
{
if (retry++ == 3) throw;
}
// It seems that attempting to use a token immediately sometimes fails, retry a few
// times with a delay of of 1s to allow the token to propagate.
await Task.Delay(1000);
}
}
/// <inheritdoc/>
public Task<User> LoginFromCache(HostAddress hostAddress, IGitHubClient client)
{
Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
Guard.ArgumentNotNull(client, nameof(client));
return client.User.Current();
}
/// <inheritdoc/>
public async Task Logout(HostAddress hostAddress, IGitHubClient client)
{
Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
Guard.ArgumentNotNull(client, nameof(client));
await keychain.Delete(hostAddress);
}
async Task<ApplicationAuthorization> CreateAndDeleteExistingApplicationAuthorization(
IGitHubClient client,
NewAuthorization newAuth,
string twoFactorAuthenticationCode)
{
ApplicationAuthorization result;
var retry = 0;
do
{
if (twoFactorAuthenticationCode == null)
{
result = await client.Authorization.GetOrCreateApplicationAuthentication(
clientId,
clientSecret,
newAuth).ConfigureAwait(false);
}
else
{
result = await client.Authorization.GetOrCreateApplicationAuthentication(
clientId,
clientSecret,
newAuth,
twoFactorAuthenticationCode).ConfigureAwait(false);
}
if (result.Token == string.Empty)
{
if (twoFactorAuthenticationCode == null)
{
await client.Authorization.Delete(result.Id);
}
else
{
await client.Authorization.Delete(result.Id, twoFactorAuthenticationCode);
}
}
} while (result.Token == string.Empty && retry++ == 0);
return result;
}
async Task<ApplicationAuthorization> HandleTwoFactorAuthorization(
HostAddress hostAddress,
IGitHubClient client,
NewAuthorization newAuth,
TwoFactorAuthorizationException exception)
{
for (;;)
{
var challengeResult = await twoFactorChallengeHandler.Value.HandleTwoFactorException(exception);
if (challengeResult == null)
{
throw new InvalidOperationException(
"ITwoFactorChallengeHandler.HandleTwoFactorException returned null.");
}
if (!challengeResult.ResendCodeRequested)
{
try
{
var auth = await CreateAndDeleteExistingApplicationAuthorization(
client,
newAuth,
challengeResult.AuthenticationCode).ConfigureAwait(false);
return EnsureNonNullAuthorization(auth);
}
catch (TwoFactorAuthorizationException e)
{
exception = e;
}
catch (Exception e)
{
await twoFactorChallengeHandler.Value.ChallengeFailed(e);
await keychain.Delete(hostAddress).ConfigureAwait(false);
throw;
}
}
else
{
return null;
}
}
}
ApplicationAuthorization EnsureNonNullAuthorization(ApplicationAuthorization auth)
{
// If a mock IGitHubClient is not set up correctly, it can return null from
// IGutHubClient.Authorization.Create - this will cause an infinite loop in Login()
// so prevent that.
if (auth == null)
{
throw new InvalidOperationException("IGutHubClient.Authorization.Create returned null.");
}
return auth;
}
bool EnterpriseWorkaround(HostAddress hostAddress, Exception e)
{
// Older Enterprise hosts either don't have the API end-point to PUT an authorization, or they
// return 422 because they haven't white-listed our client ID. In that case, we just ignore
// the failure, using basic authentication (with username and password) instead of trying
// to get an authorization token.
// Since enterprise 2.1 and https://github.com/github/github/pull/36669 the API returns 403
// instead of 404 to signal that it's not allowed. In the name of backwards compatibility we
// test for both 404 (NotFoundException) and 403 (ForbiddenException) here.
var apiException = e as ApiException;
return !hostAddress.IsGitHubDotCom() &&
(e is NotFoundException ||
e is ForbiddenException ||
apiException?.StatusCode == (HttpStatusCode)422);
}
}
}