borepin/FabAccessAPI/Connection.cs

64 lines
1.9 KiB
C#
Raw Normal View History

2021-09-11 13:53:40 +02:00
using Capnp.Rpc;
2022-03-12 22:52:28 +01:00
using FabAccessAPI.Exceptions;
2021-09-11 13:53:40 +02:00
using FabAccessAPI.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2020-10-26 14:35:31 +01:00
2021-09-11 13:53:40 +02:00
namespace FabAccessAPI
{
public class Connection
{
2022-01-03 21:13:03 +00:00
#region Private Fields
private readonly IBootstrap? _BootstrapCap = null;
private Auth? _Auth = null;
2021-09-11 13:53:40 +02:00
#endregion
2020-11-12 10:12:56 +01:00
2022-01-03 21:13:03 +00:00
#region Constructors
2021-09-11 13:53:40 +02:00
/// <summary>
///
/// </summary>
/// <param name="rpcClient">Should be an already configured and connected TcpRpcClient</param>
public Connection(TcpRpcClient rpcClient)
{
2022-01-03 21:13:03 +00:00
RpcClient = rpcClient;
_BootstrapCap = RpcClient.GetMain<IBootstrap>();
2021-09-11 13:53:40 +02:00
}
2022-01-03 21:13:03 +00:00
#endregion
2020-11-12 10:12:56 +01:00
2022-01-03 21:13:03 +00:00
#region Fields
public TcpRpcClient? RpcClient { get; } = null;
2022-03-12 22:52:28 +01:00
public Session? Session { get; private set; } = null;
2022-01-03 21:13:03 +00:00
#endregion
#region Methods
2021-09-11 13:53:40 +02:00
/// <summary>
/// Authenticate this connection.
/// Calling this more then once is UB
/// </summary>
/// <param name="mech">The desired authentication mechanism</param>
/// <param name="kvs">Key-Value data specific to the mechanism</param>
/// <returns></returns>
2022-03-12 22:52:28 +01:00
public async Task Auth(string mech, Dictionary<string, object> kvs, CancellationToken cancellationToken_ = default)
2021-09-11 13:53:40 +02:00
{
2022-03-12 22:52:28 +01:00
IReadOnlyList<string>? mechs = await _BootstrapCap.Mechanisms();
2021-09-11 13:53:40 +02:00
if (!mechs.Contains(mech))
{
throw new UnsupportedMechanismException();
}
2022-03-12 22:52:28 +01:00
if (_Auth == null)
{
IAuthentication? authCap = await _BootstrapCap.CreateSession(mech, cancellationToken_).ConfigureAwait(false);
_Auth = new Auth(authCap);
}
2021-09-11 13:53:40 +02:00
2022-03-12 22:52:28 +01:00
Session = await _Auth.Authenticate(mech, kvs);
2021-09-11 13:53:40 +02:00
}
2022-01-03 21:13:03 +00:00
#endregion
2021-09-11 13:53:40 +02:00
}
}