Skip to content
This repository was archived by the owner on Aug 26, 2022. It is now read-only.

Commit a964206

Browse files
committed
Begin adding classes for auth
1 parent e9e11a5 commit a964206

10 files changed

+138
-31
lines changed

CypherNet.UnitTests/CypherSessionTransactionTests.cs

+4-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Net;
33
using System.Threading.Tasks;
44
using System.Transactions;
5+
using CypherNet.Configuration;
56
using CypherNet.Dynamic;
67
using CypherNet.Graph;
78
using CypherNet.Http;
@@ -29,7 +30,7 @@ public void CreateNode__CreatesNode()
2930
{
3031
var mock = InitializeMockWebClient(AutoCommitAddress);
3132

32-
var session = new CypherSession(BaseUri, mock.Object);
33+
var session = new CypherSession(new ConnectionProperties(BaseUri), mock.Object);
3334
var node = session.CreateNode(new {name = Name}, "person");
3435
Assert.AreEqual(node.AsDynamic().name, Name);
3536
Assert.AreEqual((node).Labels.First(), "person");
@@ -47,7 +48,7 @@ public void CreateNode_WithinCommitedTransaction_CallsCommit()
4748
//Commit
4849
mock.Setup(m => m.PostAsync(CommitAddress, EmptyRequest)).Returns(() => BuildResponse(EmptyResponse));
4950

50-
var session = new CypherSession(BaseUri, mock.Object);
51+
var session = new CypherSession(new ConnectionProperties(BaseUri), mock.Object);
5152
using (var ts = new TransactionScope())
5253
{
5354
session.CreateNode(new {name = Name}, "person");
@@ -66,7 +67,7 @@ public void CreateNode_WithinRollbackTransaction_CallsRollback()
6667
//Rollback
6768
mock.Setup(m => m.DeleteAsync(KeepAliveAddress)).Returns(() => BuildResponse(EmptyResponse));
6869

69-
var session = new CypherSession(BaseUri, mock.Object);
70+
var session = new CypherSession(new ConnectionProperties(BaseUri), mock.Object);
7071

7172
using (new TransactionScope())
7273
{

CypherNet.sln.DotSettings

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
22
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LIMIT/@EntryValue">200</s:Int64>
3-
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
3+
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EAddAccessorOwnerDeclarationBracesMigration/@EntryIndexedValue">True</s:Boolean>
4+
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
5+
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

CypherNet/Configuration/Fluently.cs

+26-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
using System;
2+
using System.Collections.Generic;
3+
using System.Data.Common;
24
using CypherNet.Logging;
35

46
namespace CypherNet.Configuration
@@ -21,22 +23,42 @@ public static ISessionConfiguration Configure(string endpointUri)
2123

2224
internal class SessionConfiguration : ISessionConfiguration
2325
{
24-
private readonly string _endpointUri;
26+
private readonly ConnectionProperties _connectionProperties;
2527

26-
public SessionConfiguration(string endpointUri)
28+
public SessionConfiguration(string connectionString)
2729
{
28-
_endpointUri = endpointUri;
30+
_connectionProperties = Neo4JConnectionStringParser.Parse(connectionString);
2931
Logging.Logger.Current = new TraceLogger();
3032
}
3133

3234
public ICypherSessionFactory CreateSessionFactory()
3335
{
34-
return new DefaultCypherSessionFactory(_endpointUri);
36+
return new DefaultCypherSessionFactory(_connectionProperties);
3537
}
3638
}
3739

3840
public interface ISessionConfiguration
3941
{
4042
ICypherSessionFactory CreateSessionFactory();
4143
}
44+
45+
public class ConnectionProperties
46+
{
47+
public ConnectionProperties(string url): this(url, null, null)
48+
{
49+
}
50+
51+
public ConnectionProperties(string url, string username, string password)
52+
{
53+
Url = url;
54+
Username = username;
55+
Password = password;
56+
}
57+
58+
public string Url { get; private set; }
59+
60+
public string Username { get; private set; }
61+
62+
public string Password { get; private set; }
63+
}
4264
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System.Linq;
2+
using System.Text.RegularExpressions;
3+
4+
namespace CypherNet.Configuration
5+
{
6+
internal class Neo4JConnectionStringParser
7+
{
8+
private readonly static Regex URL_REGEX = new Regex(@"https ?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)");
9+
10+
internal static ConnectionProperties Parse(string connectionString)
11+
{
12+
if (URL_REGEX.IsMatch(connectionString))
13+
{
14+
return new ConnectionProperties(connectionString, null, null);
15+
}
16+
var values = connectionString.Split(';')
17+
.Select(s => s.Trim())
18+
.Select(s => s.Split('='))
19+
.ToDictionary(arr => arr[0].ToLower(), arr => arr[1]);
20+
21+
var server = values["server"];
22+
string user, password;
23+
24+
values.TryGetValue("user id", out user);
25+
values.TryGetValue("password", out password);
26+
return new ConnectionProperties(server, user, password);
27+
}
28+
}
29+
}

CypherNet/CypherNet.csproj

+2
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
</ItemGroup>
5252
<ItemGroup>
5353
<Compile Include="Configuration\Fluently.cs" />
54+
<Compile Include="Configuration\Neo4JConnectionStringParser.cs" />
5455
<Compile Include="Dynamic\CachedDictionaryPropertiesProvider.cs" />
5556
<Compile Include="Dynamic\DynamicEntity.cs" />
5657
<Compile Include="Dynamic\IDynamicMetaData.cs" />
@@ -59,6 +60,7 @@
5960
<Compile Include="Graph\IGraphEntity.cs" />
6061
<Compile Include="Graph\Node.cs" />
6162
<Compile Include="Graph\Relationship.cs" />
63+
<Compile Include="Http\BasicAuthCredentials.cs" />
6264
<Compile Include="Http\IWebClient.cs" />
6365
<Compile Include="Http\WebClient.cs" />
6466
<Compile Include="ICypherSession.cs" />
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
namespace CypherNet.Http
2+
{
3+
using System;
4+
using System.Text;
5+
6+
public class BasicAuthCredentials
7+
{
8+
public BasicAuthCredentials(string username, string password)
9+
{
10+
EncodedCredentials = EncodeCredentials(username, password);
11+
}
12+
13+
public string EncodedCredentials { get; }
14+
15+
private static string EncodeCredentials(string username, string password)
16+
{
17+
var auth = string.Format("{0}:{1}", username, password);
18+
var enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
19+
var cred = string.Format("{0} {1}", "Basic", enc);
20+
return cred;
21+
}
22+
}
23+
}

CypherNet/Http/WebClient.cs

+18-9
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,17 @@ namespace CypherNet.Http
77
{
88
public class WebClient : IWebClient
99
{
10+
private readonly BasicAuthCredentials _credentials;
11+
12+
public WebClient()
13+
{
14+
}
15+
16+
public WebClient(BasicAuthCredentials credentials)
17+
{
18+
_credentials = credentials;
19+
}
20+
1021
#region IWebClient Members
1122

1223
public async Task<IHttpResponseMessage> GetAsync(string url)
@@ -31,15 +42,9 @@ public async Task<IHttpResponseMessage> DeleteAsync(string url)
3142

3243
#endregion
3344

34-
private async Task<IHttpResponseMessage> Execute(string url, HttpMethod method)
45+
private Task<IHttpResponseMessage> Execute(string url, HttpMethod method)
3546
{
36-
var msg = new HttpRequestMessage(method, url);
37-
38-
using (var client = new HttpClient())
39-
{
40-
var result = await client.SendAsync(msg).ConfigureAwait(false);
41-
return new HttpResponseMessageWrapper(result);
42-
}
47+
return Execute(url, null, method);
4348
}
4449

4550
private async Task<IHttpResponseMessage> Execute(string url, String content, HttpMethod method)
@@ -54,10 +59,14 @@ private async Task<IHttpResponseMessage> Execute(string url, String content, Htt
5459

5560
using (var client = new HttpClient())
5661
{
62+
if (_credentials != null)
63+
{
64+
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials.EncodedCredentials);
65+
}
66+
5767
var result = await client.SendAsync(msg).ConfigureAwait(false);
5868
return new HttpResponseMessageWrapper(result);
5969
}
6070
}
6171
}
62-
6372
}

CypherNet/ICypherSessionFactory.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
namespace CypherNet
1+
using CypherNet.Configuration;
2+
3+
namespace CypherNet
24
{
35
public interface ICypherSessionFactory
46
{
57
ICypherSession Create();
6-
ICypherSession Create(string sourceUri);
8+
ICypherSession Create(ConnectionProperties connectionProperties);
79
}
810
}

CypherNet/Transaction/CypherSession.cs

+20-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace CypherNet.Transaction
1+
using CypherNet.Configuration;
2+
3+
namespace CypherNet.Transaction
24
{
35
#region
46

@@ -40,14 +42,14 @@ public class CypherSession : ICypherSession
4042
private readonly IEntityCache _entityCache;
4143
private readonly IWebClient _webClient;
4244

43-
internal CypherSession(string uri)
44-
: this(uri, new WebClient())
45+
internal CypherSession(ConnectionProperties connectionProperties)
46+
: this(connectionProperties, new WebClient(connectionProperties.BuildBasicAuthCredentials()))
4547
{
4648
}
4749

48-
internal CypherSession(string uri, IWebClient webClient)
50+
internal CypherSession(ConnectionProperties connectionProperties, IWebClient webClient)
4951
{
50-
_uri = uri;
52+
_uri = connectionProperties.Url;
5153
_webClient = webClient;
5254
_entityCache = new DictionaryEntityCache();
5355
_webSerializer = new DefaultJsonSerializer(_entityCache);
@@ -266,4 +268,17 @@ public SingleNodeResult(Node newNode)
266268
public Node NewNode { get; private set; }
267269
}
268270
}
271+
272+
internal static class ConnectionPropertiesExtension
273+
{
274+
public static BasicAuthCredentials BuildBasicAuthCredentials(this ConnectionProperties connectionProperties)
275+
{
276+
if (!(new[] {connectionProperties.Username, connectionProperties.Password}.All(string.IsNullOrEmpty)))
277+
{
278+
return new BasicAuthCredentials(connectionProperties.Username, connectionProperties.Password);
279+
}
280+
281+
return null;
282+
}
283+
}
269284
}

CypherNet/Transaction/DefaultCypherSessionFactory.cs

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,32 @@
1-
using CypherNet.Serialization;
1+

22

33
namespace CypherNet.Transaction
44
{
55
#region
66

77
using Http;
8+
using CypherNet.Configuration;
9+
using CypherNet.Serialization;
810

911
#endregion
1012

1113
internal class DefaultCypherSessionFactory : ICypherSessionFactory
1214
{
13-
private readonly string _sourceUri;
15+
private readonly ConnectionProperties _connectionProperties;
1416

15-
public DefaultCypherSessionFactory(string sourceUri)
17+
public DefaultCypherSessionFactory(ConnectionProperties connectionProperties)
1618
{
17-
_sourceUri = sourceUri;
19+
_connectionProperties = connectionProperties;
1820
}
1921

2022
public ICypherSession Create()
2123
{
22-
return Create(_sourceUri);
24+
return Create(_connectionProperties);
2325
}
2426

25-
public ICypherSession Create(string sourceUri)
27+
public ICypherSession Create(ConnectionProperties connectionProperties)
2628
{
27-
var session = new CypherSession(sourceUri);
29+
var session = new CypherSession(connectionProperties);
2830
session.Connect();
2931
return session;
3032
}

0 commit comments

Comments
 (0)