Skip to content

Commit dd991f9

Browse files
committed
Moved auth http code to HttpClientExtensions
1 parent 3d9a16c commit dd991f9

File tree

6 files changed

+118
-117
lines changed

6 files changed

+118
-117
lines changed

FirebaseAdmin/FirebaseAdmin.Tests/Auth/AuthErrorHandlerTest.cs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ public void KnownErrorCode(
4949
Content = new StringContent(json, Encoding.UTF8, "application/json"),
5050
};
5151

52-
var handler = new AuthErrorHandler();
53-
var error = Assert.Throws<FirebaseAuthException>(() => handler.ThrowIfError(resp, json));
52+
var error = Assert.Throws<FirebaseAuthException>(
53+
() => AuthErrorHandler.Instance.ThrowIfError(resp, json));
5454

5555
Assert.Equal(expectedCode, error.ErrorCode);
5656
Assert.Equal(expectedAuthCode, error.AuthErrorCode);
@@ -75,8 +75,8 @@ public void KnownErrorCodeWithDetails(
7575
Content = new StringContent(json, Encoding.UTF8, "application/json"),
7676
};
7777

78-
var handler = new AuthErrorHandler();
79-
var error = Assert.Throws<FirebaseAuthException>(() => handler.ThrowIfError(resp, json));
78+
var error = Assert.Throws<FirebaseAuthException>(
79+
() => AuthErrorHandler.Instance.ThrowIfError(resp, json));
8080

8181
Assert.Equal(expectedCode, error.ErrorCode);
8282
Assert.Equal(expectedAuthCode, error.AuthErrorCode);
@@ -99,8 +99,8 @@ public void UnknownErrorCode()
9999
Content = new StringContent(json, Encoding.UTF8, "application/json"),
100100
};
101101

102-
var handler = new AuthErrorHandler();
103-
var error = Assert.Throws<FirebaseAuthException>(() => handler.ThrowIfError(resp, json));
102+
var error = Assert.Throws<FirebaseAuthException>(
103+
() => AuthErrorHandler.Instance.ThrowIfError(resp, json));
104104

105105
Assert.Equal(ErrorCode.Internal, error.ErrorCode);
106106
Assert.Equal(
@@ -123,8 +123,8 @@ public void UnspecifiedErrorCode()
123123
Content = new StringContent(json, Encoding.UTF8, "application/json"),
124124
};
125125

126-
var handler = new AuthErrorHandler();
127-
var error = Assert.Throws<FirebaseAuthException>(() => handler.ThrowIfError(resp, json));
126+
var error = Assert.Throws<FirebaseAuthException>(
127+
() => AuthErrorHandler.Instance.ThrowIfError(resp, json));
128128

129129
Assert.Equal(ErrorCode.Internal, error.ErrorCode);
130130
Assert.Equal(
@@ -145,8 +145,8 @@ public void NoDetails()
145145
Content = new StringContent(json, Encoding.UTF8, "application/json"),
146146
};
147147

148-
var handler = new AuthErrorHandler();
149-
var error = Assert.Throws<FirebaseAuthException>(() => handler.ThrowIfError(resp, json));
148+
var error = Assert.Throws<FirebaseAuthException>(
149+
() => AuthErrorHandler.Instance.ThrowIfError(resp, json));
150150

151151
Assert.Equal(ErrorCode.Unavailable, error.ErrorCode);
152152
Assert.Equal(
@@ -167,8 +167,8 @@ public void NonJson()
167167
Content = new StringContent(text, Encoding.UTF8, "text/plain"),
168168
};
169169

170-
var handler = new AuthErrorHandler();
171-
var error = Assert.Throws<FirebaseAuthException>(() => handler.ThrowIfError(resp, text));
170+
var error = Assert.Throws<FirebaseAuthException>(
171+
() => AuthErrorHandler.Instance.ThrowIfError(resp, text));
172172

173173
Assert.Equal(ErrorCode.Unavailable, error.ErrorCode);
174174
Assert.Equal(

FirebaseAdmin/FirebaseAdmin/Auth/AuthErrorHandler.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ namespace FirebaseAdmin.Auth
2525
/// </summary>
2626
internal sealed class AuthErrorHandler : HttpErrorHandler
2727
{
28+
internal static readonly AuthErrorHandler Instance = new AuthErrorHandler();
29+
2830
private static readonly IReadOnlyDictionary<string, ErrorInfo> CodeToErrorInfo =
2931
new Dictionary<string, ErrorInfo>()
3032
{
@@ -44,6 +46,8 @@ internal sealed class AuthErrorHandler : HttpErrorHandler
4446
},
4547
};
4648

49+
private AuthErrorHandler() { }
50+
4751
protected sealed override FirebaseExceptionArgs CreateExceptionArgs(
4852
HttpResponseMessage response, string body)
4953
{

FirebaseAdmin/FirebaseAdmin/Auth/FirebaseUserManager.cs

Lines changed: 7 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@ internal class FirebaseUserManager : IDisposable
3939
private readonly ConfigurableHttpClient httpClient;
4040
private readonly string baseUrl;
4141

42-
private readonly AuthErrorHandler errorHandler;
43-
4442
internal FirebaseUserManager(FirebaseUserManagerArgs args)
4543
{
4644
if (string.IsNullOrEmpty(args.ProjectId))
@@ -51,7 +49,6 @@ internal FirebaseUserManager(FirebaseUserManagerArgs args)
5149

5250
this.httpClient = args.ClientFactory.CreateAuthorizedHttpClient(args.Credential);
5351
this.baseUrl = string.Format(IdTooklitUrl, args.ProjectId);
54-
this.errorHandler = new AuthErrorHandler();
5552
}
5653

5754
public void Dispose()
@@ -71,27 +68,6 @@ internal static FirebaseUserManager Create(FirebaseApp app)
7168
return new FirebaseUserManager(args);
7269
}
7370

74-
internal static FirebaseAuthException HandleHttpError(HttpRequestException exception)
75-
{
76-
var temp = exception.ToFirebaseException();
77-
return new FirebaseAuthException(
78-
temp.ErrorCode,
79-
temp.Message,
80-
inner: temp.InnerException,
81-
response: temp.HttpResponse);
82-
}
83-
84-
internal static FirebaseAuthException HandleParseError(
85-
Exception e, HttpResponseMessage response)
86-
{
87-
throw new FirebaseAuthException(
88-
ErrorCode.Unknown,
89-
"Error while parsing Auth service response.",
90-
AuthErrorCode.UnexpectedResponse,
91-
e,
92-
response);
93-
}
94-
9571
/// <summary>
9672
/// Gets the user data corresponding to the given user ID.
9773
/// </summary>
@@ -277,15 +253,15 @@ private async Task<UserRecord> GetUserAsync(
277253
return new UserRecord(result.Users[0]);
278254
}
279255

280-
private async Task<Extensions.ParsedResponseInfo<TResult>> PostAndDeserializeAsync<TResult>(
256+
private async Task<HttpExtensions.ParsedResponseInfo<TResult>> PostAndDeserializeAsync<TResult>(
281257
string path, object body, CancellationToken cancellationToken)
282258
{
283259
var response = await this.PostAsync(path, body, cancellationToken)
284260
.ConfigureAwait(false);
285-
return response.SafeDeserialize<TResult>(HandleParseError);
261+
return response.SafeDeserialize<TResult>();
286262
}
287263

288-
private async Task<Extensions.ResponseInfo> PostAsync(
264+
private async Task<HttpExtensions.ResponseInfo> PostAsync(
289265
string path, object body, CancellationToken cancellationToken)
290266
{
291267
var request = new HttpRequestMessage()
@@ -297,13 +273,12 @@ private async Task<UserRecord> GetUserAsync(
297273
return await this.SendAsync(request, cancellationToken).ConfigureAwait(false);
298274
}
299275

300-
private async Task<Extensions.ResponseInfo> SendAsync(
276+
private async Task<HttpExtensions.ResponseInfo> SendAsync(
301277
HttpRequestMessage request, CancellationToken cancellationToken)
302278
{
303-
var response = await this.httpClient.SendAndReadAsync(
304-
request, cancellationToken, HandleHttpError);
305-
this.errorHandler.ThrowIfError(response.HttpResponse, response.Body);
306-
return response;
279+
return await this.httpClient
280+
.SendAndReadAsync(request, cancellationToken)
281+
.ConfigureAwait(false);
307282
}
308283

309284
/// <summary>
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright 2019, Google Inc. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
using System;
16+
using System.Net.Http;
17+
using System.Threading;
18+
using System.Threading.Tasks;
19+
using Google.Apis.Http;
20+
using Google.Apis.Json;
21+
22+
namespace FirebaseAdmin.Auth
23+
{
24+
internal static class HttpExtensions
25+
{
26+
internal static async Task<ResponseInfo> SendAndReadAsync(
27+
this ConfigurableHttpClient httpClient,
28+
HttpRequestMessage request,
29+
CancellationToken cancellationToken)
30+
{
31+
try
32+
{
33+
var response = await httpClient.SendAsync(request, cancellationToken)
34+
.ConfigureAwait(false);
35+
var json = await response.Content.ReadAsStringAsync()
36+
.ConfigureAwait(false);
37+
AuthErrorHandler.Instance.ThrowIfError(response, json);
38+
39+
return new ResponseInfo()
40+
{
41+
HttpResponse = response,
42+
Body = json,
43+
};
44+
}
45+
catch (HttpRequestException e)
46+
{
47+
var temp = e.ToFirebaseException();
48+
throw new FirebaseAuthException(
49+
temp.ErrorCode,
50+
temp.Message,
51+
inner: temp.InnerException,
52+
response: temp.HttpResponse);
53+
}
54+
}
55+
56+
internal class ResponseInfo
57+
{
58+
internal HttpResponseMessage HttpResponse { get; set; }
59+
60+
internal string Body { get; set; }
61+
62+
internal ParsedResponseInfo<TResult> SafeDeserialize<TResult>()
63+
{
64+
try
65+
{
66+
var parsed = NewtonsoftJsonSerializer.Instance.Deserialize<TResult>(this.Body);
67+
return new ParsedResponseInfo<TResult>()
68+
{
69+
Result = parsed,
70+
HttpResponse = this.HttpResponse,
71+
Body = this.Body,
72+
};
73+
}
74+
catch (Exception e)
75+
{
76+
throw new FirebaseAuthException(
77+
ErrorCode.Unknown,
78+
"Error while parsing Auth service response.",
79+
AuthErrorCode.UnexpectedResponse,
80+
e,
81+
this.HttpResponse);
82+
}
83+
}
84+
}
85+
86+
internal sealed class ParsedResponseInfo<T> : ResponseInfo
87+
{
88+
internal T Result { get; set; }
89+
}
90+
}
91+
}

FirebaseAdmin/FirebaseAdmin/Auth/ListUsersRequest.cs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,12 @@ internal sealed class ListUsersRequest : IClientServiceRequest<ExportedUserRecor
3636

3737
private readonly string baseUrl;
3838
private readonly ConfigurableHttpClient httpClient;
39-
private readonly AuthErrorHandler errorHandler;
4039

4140
private ListUsersRequest(
4241
string baseUrl, ConfigurableHttpClient httpClient, ListUsersOptions options)
4342
{
4443
this.baseUrl = baseUrl;
4544
this.httpClient = httpClient;
46-
this.errorHandler = new AuthErrorHandler();
4745
this.RequestParameters = new Dictionary<string, IParameter>();
4846
this.SetPageSize(options.PageSize);
4947
this.SetPageToken(options.PageToken);
@@ -175,18 +173,15 @@ private async Task<DownloadAccountResponse> SendAndDeserializeAsync(
175173
{
176174
var response = await this.SendAsync(request, cancellationToken)
177175
.ConfigureAwait(false);
178-
return response.SafeDeserialize<DownloadAccountResponse>(
179-
FirebaseUserManager.HandleParseError).Result;
176+
var parsed = response.SafeDeserialize<DownloadAccountResponse>();
177+
return parsed.Result;
180178
}
181179

182-
private async Task<Extensions.ResponseInfo> SendAsync(
180+
private async Task<HttpExtensions.ResponseInfo> SendAsync(
183181
HttpRequestMessage request, CancellationToken cancellationToken)
184182
{
185-
var response = await this.httpClient.SendAndReadAsync(
186-
request, cancellationToken, FirebaseUserManager.HandleHttpError)
183+
return await this.httpClient.SendAndReadAsync(request, cancellationToken)
187184
.ConfigureAwait(false);
188-
this.errorHandler.ThrowIfError(response.HttpResponse, response.Body);
189-
return response;
190185
}
191186

192187
/// <summary>

FirebaseAdmin/FirebaseAdmin/Extensions.cs

Lines changed: 0 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,6 @@ internal static class Extensions
4242
SocketError.NetworkUnreachable,
4343
};
4444

45-
internal delegate FirebaseException HttpErrorHandlerFunc(HttpRequestException e);
46-
47-
internal delegate FirebaseException ParseErrorHandlerFunc(
48-
Exception e, HttpResponseMessage response);
49-
5045
/// <summary>
5146
/// Extracts and returns the underlying <see cref="ServiceAccountCredential"/> from a
5247
/// <see cref="GoogleCredential"/>. Returns null if the <c>GoogleCredential</c> is not
@@ -192,64 +187,5 @@ public static FirebaseException ToFirebaseException(this HttpRequestException ex
192187

193188
return new FirebaseException(code, $"{message}: {exception.Message}", exception);
194189
}
195-
196-
internal static async Task<ResponseInfo> SendAndReadAsync(
197-
this ConfigurableHttpClient httpClient,
198-
HttpRequestMessage request,
199-
CancellationToken cancellationToken,
200-
HttpErrorHandlerFunc func = null)
201-
{
202-
try
203-
{
204-
var response = await httpClient.SendAsync(request, cancellationToken)
205-
.ConfigureAwait(false);
206-
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
207-
208-
return new ResponseInfo()
209-
{
210-
HttpResponse = response,
211-
Body = json,
212-
};
213-
}
214-
catch (HttpRequestException e)
215-
{
216-
if (func == null)
217-
{
218-
throw e.ToFirebaseException();
219-
}
220-
221-
throw func(e);
222-
}
223-
}
224-
225-
internal class ResponseInfo
226-
{
227-
internal HttpResponseMessage HttpResponse { get; set; }
228-
229-
internal string Body { get; set; }
230-
231-
internal ParsedResponseInfo<TResult> SafeDeserialize<TResult>(ParseErrorHandlerFunc func)
232-
{
233-
try
234-
{
235-
var parsed = NewtonsoftJsonSerializer.Instance.Deserialize<TResult>(this.Body);
236-
return new ParsedResponseInfo<TResult>()
237-
{
238-
Result = parsed,
239-
HttpResponse = this.HttpResponse,
240-
Body = this.Body,
241-
};
242-
}
243-
catch (Exception e)
244-
{
245-
throw func(e, this.HttpResponse);
246-
}
247-
}
248-
}
249-
250-
internal class ParsedResponseInfo<T> : ResponseInfo
251-
{
252-
internal T Result { get; set; }
253-
}
254190
}
255191
}

0 commit comments

Comments
 (0)