Skip to content

Commit 7d7c5ef

Browse files
committed
Some major code cleanup
1 parent 815895f commit 7d7c5ef

39 files changed

+393
-912
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Copyright © 2009-2020 John Sheehan, Andrew Young, Alexey Zimarev and RestSharp community
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+
namespace RestSharp.Authenticators
16+
{
17+
public abstract class AuthenticatorBase : IAuthenticator
18+
{
19+
protected AuthenticatorBase(string token) => Token = token;
20+
21+
protected string Token { get; }
22+
23+
protected abstract Parameter GetAuthenticationParameter(string accessToken);
24+
25+
public void Authenticate(IRestClient client, IRestRequest request) => request.AddOrUpdateParameter(GetAuthenticationParameter(Token));
26+
}
27+
}

src/RestSharp/Authenticators/HttpBasicAuthenticator.cs

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -29,34 +29,19 @@ namespace RestSharp.Authenticators
2929
/// Encoding can be specified depending on what your server expect (see https://stackoverflow.com/a/7243567).
3030
/// UTF-8 is used by default but some servers might expect ISO-8859-1 encoding.
3131
/// </remarks>
32-
public class HttpBasicAuthenticator : IAuthenticator
32+
public class HttpBasicAuthenticator : AuthenticatorBase
3333
{
34-
readonly string _authHeader;
35-
3634
public HttpBasicAuthenticator(string username, string password)
37-
: this(username, password, Encoding.UTF8)
38-
{
39-
}
35+
: this(username, password, Encoding.UTF8) { }
4036

4137
public HttpBasicAuthenticator(string username, string password, Encoding encoding)
42-
{
43-
var token = Convert.ToBase64String(encoding.GetBytes($"{username}:{password}"));
44-
45-
_authHeader = $"Basic {token}";
46-
}
47-
48-
public void Authenticate(IRestClient client, IRestRequest request)
49-
{
50-
// NetworkCredentials always makes two trips, even if with PreAuthenticate,
51-
// it is also unsafe for many partial trust scenarios
52-
// request.Credentials = Credentials;
53-
// thanks TweetSharp!
38+
: base(GetHeader(username, password, encoding)) { }
5439

55-
// request.Credentials = new NetworkCredential(_username, _password);
40+
static string GetHeader(string username, string password, Encoding encoding)
41+
=> Convert.ToBase64String(encoding.GetBytes($"{username}:{password}"));
5642

57-
// only add the Authorization parameter if it hasn't been added by a previous Execute
58-
if (!request.Parameters.Any(p => "Authorization".Equals(p.Name, StringComparison.OrdinalIgnoreCase)))
59-
request.AddParameter("Authorization", _authHeader, ParameterType.HttpHeader);
60-
}
43+
// return ;
44+
protected override Parameter GetAuthenticationParameter(string accessToken)
45+
=> new Parameter("Authorization", $"Basic {accessToken}", ParameterType.HttpHeader);
6146
}
6247
}

src/RestSharp/Authenticators/JwtAuthenticator.cs

Lines changed: 2 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717

1818
#endregion
1919

20-
using System;
21-
using System.Linq;
2220
using RestSharp.Validation;
2321

2422
namespace RestSharp.Authenticators
@@ -30,18 +28,9 @@ namespace RestSharp.Authenticators
3028
public class JwtAuthenticator : IAuthenticator
3129
{
3230
string _authHeader;
33-
bool _forceTokenUpdate;
3431

3532
// ReSharper disable once IntroduceOptionalParameters.Global
36-
public JwtAuthenticator(string accessToken) : this(accessToken, false)
37-
{
38-
}
39-
40-
public JwtAuthenticator(string accessToken, bool forceTokenUpdate)
41-
{
42-
SetBearerToken(accessToken);
43-
_forceTokenUpdate = forceTokenUpdate;
44-
}
33+
public JwtAuthenticator(string accessToken) => SetBearerToken(accessToken);
4534

4635
/// <summary>
4736
/// Set the new bearer token so the request gets the new header value
@@ -52,21 +41,9 @@ public void SetBearerToken(string accessToken)
5241
Ensure.NotEmpty(accessToken, nameof(accessToken));
5342

5443
_authHeader = $"Bearer {accessToken}";
55-
_forceTokenUpdate = true;
5644
}
5745

5846
public void Authenticate(IRestClient client, IRestRequest request)
59-
{
60-
if (_forceTokenUpdate)
61-
{
62-
request.AddOrUpdateParameter("Authorization", _authHeader, ParameterType.HttpHeader);
63-
return;
64-
}
65-
66-
// only add the Authorization parameter if it hasn't been added by a previous Execute
67-
if (!request.Parameters.Any(p => p.Type.Equals(ParameterType.HttpHeader) &&
68-
p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
69-
request.AddParameter("Authorization", _authHeader, ParameterType.HttpHeader);
70-
}
47+
=> request.AddOrUpdateParameter("Authorization", _authHeader, ParameterType.HttpHeader);
7148
}
7249
}

src/RestSharp/Authenticators/NtlmAuthenticator.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,12 @@ namespace RestSharp.Authenticators
2626
/// </summary>
2727
public class NtlmAuthenticator : IAuthenticator
2828
{
29-
readonly ICredentials credentials;
29+
readonly ICredentials _credentials;
3030

3131
/// <summary>
3232
/// Authenticate with the credentials of the currently logged in user
3333
/// </summary>
34-
public NtlmAuthenticator()
35-
: this(CredentialCache.DefaultCredentials) { }
34+
public NtlmAuthenticator() : this(CredentialCache.DefaultCredentials) { }
3635

3736
/// <summary>
3837
/// Authenticate by impersonation
@@ -46,8 +45,8 @@ public NtlmAuthenticator(string username, string password)
4645
/// Authenticate by impersonation, using an existing <c>ICredentials</c> instance
4746
/// </summary>
4847
/// <param name="credentials"></param>
49-
public NtlmAuthenticator(ICredentials credentials) => this.credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
48+
public NtlmAuthenticator(ICredentials credentials) => this._credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
5049

51-
public void Authenticate(IRestClient client, IRestRequest request) => request.Credentials = credentials;
50+
public void Authenticate(IRestClient client, IRestRequest request) => request.Credentials = _credentials;
5251
}
5352
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace RestSharp.Authenticators.OAuth
2+
{
3+
public enum OAuthSignatureMethod { HmacSha1, HmacSha256, PlainText, RsaSha1 }
4+
5+
public enum OAuthSignatureTreatment { Escaped, Unescaped }
6+
7+
public enum OAuthParameterHandling { HttpAuthorizationHeader, UrlOrPostParameters }
8+
9+
public enum OAuthType { RequestToken, AccessToken, ProtectedResource, ClientAuthentication }
10+
}
Lines changed: 0 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,13 @@
11
using System;
22
using System.Collections.Generic;
3-
using System.Collections.Specialized;
4-
using System.Linq;
5-
using System.Text;
63

74
namespace RestSharp.Authenticators.OAuth.Extensions
85
{
96
internal static class CollectionExtensions
107
{
11-
public static IEnumerable<T> AsEnumerable<T>(this T item) => new[] {item};
12-
13-
public static IEnumerable<T> And<T>(this T item, T other) => new[] {item, other};
14-
15-
public static IEnumerable<T> And<T>(this IEnumerable<T> items, T item)
16-
{
17-
foreach (var i in items) yield return i;
18-
19-
yield return item;
20-
}
21-
22-
public static TK TryWithKey<T, TK>(this IDictionary<T, TK> dictionary, T key)
23-
=> dictionary.ContainsKey(key)
24-
? dictionary[key]
25-
: default;
26-
27-
public static IEnumerable<T> ToEnumerable<T>(this object[] items) where T : class => items.Select(item => item as T);
28-
298
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
309
{
3110
foreach (var item in items) action(item);
3211
}
33-
34-
public static void AddRange(this IDictionary<string, string> collection, NameValueCollection range)
35-
{
36-
foreach (var key in range.AllKeys) collection.Add(key, range[key]);
37-
}
38-
39-
public static string ToQueryString(this NameValueCollection collection)
40-
{
41-
var sb = new StringBuilder();
42-
43-
if (collection.Count > 0) sb.Append('?');
44-
45-
var count = 0;
46-
47-
foreach (var key in collection.AllKeys)
48-
{
49-
sb.AppendFormat("{0}={1}", key, collection[key].UrlEncode());
50-
count++;
51-
52-
if (count >= collection.Count) continue;
53-
54-
sb.Append('&');
55-
}
56-
57-
return sb.ToString();
58-
}
59-
60-
public static string Concatenate(this WebParameterCollection collection, string separator, string spacer)
61-
{
62-
var sb = new StringBuilder();
63-
var total = collection.Count;
64-
var count = 0;
65-
66-
foreach (var item in collection)
67-
{
68-
sb.Append(item.Name);
69-
sb.Append(separator);
70-
sb.Append(item.Value);
71-
72-
count++;
73-
74-
if (count < total) sb.Append(spacer);
75-
}
76-
77-
return sb.ToString();
78-
}
7912
}
8013
}

src/RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs

Lines changed: 3 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,10 @@ internal static class OAuthExtensions
88
{
99
public static string ToRequestValue(this OAuthSignatureMethod signatureMethod)
1010
{
11-
var value = signatureMethod.ToString()
12-
.ToUpper();
13-
var shaIndex = value.IndexOf("SHA");
11+
var value = signatureMethod.ToString().ToUpper();
12+
var shaIndex = value.IndexOf("SHA", StringComparison.Ordinal);
1413

15-
return shaIndex > -1
16-
? value.Insert(shaIndex, "-")
17-
: value;
18-
}
19-
20-
public static OAuthSignatureMethod FromRequestValue(this string signatureMethod)
21-
{
22-
switch (signatureMethod)
23-
{
24-
case "HMAC-SHA1":
25-
return OAuthSignatureMethod.HmacSha1;
26-
27-
case "HMAC-SHA256":
28-
return OAuthSignatureMethod.HmacSha256;
29-
30-
case "RSA-SHA1":
31-
return OAuthSignatureMethod.RsaSha1;
32-
33-
default:
34-
return OAuthSignatureMethod.PlainText;
35-
}
14+
return shaIndex > -1 ? value.Insert(shaIndex, "-") : value;
3615
}
3716

3817
public static string HashWith(this string input, HashAlgorithm algorithm)
Lines changed: 2 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
using System;
2-
using System.Collections.Generic;
3-
using System.Globalization;
42
using System.Linq;
53
using System.Text;
64

@@ -10,51 +8,14 @@ internal static class StringExtensions
108
{
119
public static bool IsNullOrBlank(this string value) => string.IsNullOrWhiteSpace(value);
1210

13-
public static bool EqualsIgnoreCase(this string left, string right) => string.Equals(left, right, StringComparison.OrdinalIgnoreCase);
14-
15-
public static bool EqualsAny(this string input, params string[] args) => args.Aggregate(false, (current, arg) => current | input.Equals(arg));
16-
17-
public static string FormatWith(this string format, params object[] args) => string.Format(format, args);
18-
19-
public static string FormatWithInvariantCulture(this string format, params object[] args)
20-
=> string.Format(CultureInfo.InvariantCulture, format, args);
11+
public static bool EqualsIgnoreCase(this string left, string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase);
2112

2213
public static string Then(this string input, string value) => string.Concat(input, value);
2314

24-
public static string UrlEncode(this string value) => Uri.EscapeDataString(value);
25-
26-
public static string UrlDecode(this string value) => Uri.UnescapeDataString(value);
27-
2815
public static Uri AsUri(this string value) => new Uri(value);
2916

30-
public static string ToBase64String(this byte[] input) => Convert.ToBase64String(input);
31-
3217
public static byte[] GetBytes(this string input) => Encoding.UTF8.GetBytes(input);
3318

34-
public static string PercentEncode(this string s)
35-
{
36-
var bytes = s.GetBytes();
37-
var sb = new StringBuilder();
38-
39-
foreach (var b in bytes)
40-
sb.AppendFormat("%{0:X2}", b);
41-
42-
return sb.ToString();
43-
}
44-
45-
public static IDictionary<string, string> ParseQueryString(this string query)
46-
{
47-
// [DC]: This method does not URL decode, and cannot handle decoded input
48-
if (query.StartsWith("?"))
49-
query = query.Substring(1);
50-
51-
if (query.Equals(string.Empty))
52-
return new Dictionary<string, string>();
53-
54-
var parts = query.Split('&');
55-
56-
return parts.Select(part => part.Split('='))
57-
.ToDictionary(pair => pair[0], pair => pair[1]);
58-
}
19+
public static string PercentEncode(this string s) => string.Join("", s.GetBytes().Select(x => $"{x:X2}"));
5920
}
6021
}

src/RestSharp/Authenticators/OAuth/Extensions/TimeExtensions.cs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,6 @@ namespace RestSharp.Authenticators.OAuth.Extensions
44
{
55
internal static class TimeExtensions
66
{
7-
public static DateTime FromNow(this TimeSpan value) => new DateTime((DateTime.Now + value).Ticks);
8-
9-
public static DateTime FromUnixTime(this long seconds)
10-
{
11-
var time = new DateTime(1970, 1, 1);
12-
13-
time = time.AddSeconds(seconds);
14-
15-
return time.ToLocalTime();
16-
}
17-
187
public static long ToUnixTime(this DateTime dateTime)
198
{
209
var timeSpan = dateTime - new DateTime(1970, 1, 1);

0 commit comments

Comments
 (0)