public void EnvironmentUserIdProviderTest() { IUserIdProvider userIdProvider = EnvironmentUserIdProvider.Instance.Value; var userId = userIdProvider.GetUserId(); Assert.Equal(Environment.UserName, userId); Assert.True(userIdProvider.TryGetUserId <string>(out var _)); Assert.False(userIdProvider.TryGetUserId <int>(out var _)); Assert.Equal(0, userIdProvider.GetUserId <int>()); }
public async Task <WalletViewModel> GetWalletAsync(long walletId) { var userId = _userIdProvider.GetUserId(); var repositoryModel = await _repository.GetWalletByIdAsync(walletId); if (repositoryModel.UserId != userId) { throw new NotAuthorizedException(); } return(_mapper.Map <WalletViewModel>(repositoryModel)); }
public async Task <IEnumerable <Wallet> > GetAllWalletsAsync() { var userId = _userIdProvider.GetUserId(); var wallets = await _repository.GetAllWalletsByUserIdAsync(userId); return(_mapper.Map <IEnumerable <Wallet> >(wallets.OrderBy(w => w.Name)).ToArray()); }
private IEnumerable <Claim> BuildClaims(HttpContext context, string hubName) { // Make sticky mode required if detect using blazor var mode = _blazorDetector.IsBlazor(hubName) ? ServerStickyMode.Required : _mode; var userId = _userIdProvider.GetUserId(new ServiceHubConnectionContext(context)); return(ClaimsUtility.BuildJwtClaims(context.User, userId, GetClaimsProvider(context), _serverName, mode, _enableDetailedErrors, _endpointsCount, _maxPollInterval, IsDiagnosticClient(context)).ToList()); }
public override async Task OnConnectedAsync(HubConnectionContext connection) { if (!isInitialized) { await ConnectToClusterAsync(); } var connectionId = connection.ConnectionId; await _clusterClient.GetHubLifetimeManagerGrain(_id, _hubTypeId).OnConnectedAsync(connectionId); var userId = _userIdProvider.GetUserId(connection); if (!string.IsNullOrEmpty(userId)) { await _userPartitioner.GetPartitionGrain(_clusterClient, userId, _hubTypeId).AddToUserAsync(connectionId, userId); } connectionsById.TryAdd(connectionId, connection); }
public void RegisterReceiver(IUserIdProvider idProvider) { _connection = new HubConnection(Settings.Default.ServiceUrl); _connection.Headers.Add("myauthtoken", idProvider.GetUserId(null)); _hub = _connection.CreateHubProxy(ServerSettings.HubClassName); _connection.Start().Wait(); GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider); }
public static IConnectionContext Create(IWebSocketConnection webSocket, IConnectionLifetimeManager lifetimeManager, ISimpleProtocol simpleProtocol, IUserIdProvider userIdProvider) { var connectionId = webSocket.ConnectionInfo.Id.ToString(); var context = new ConnectionContext(connectionId, webSocket); context.Features.Set(simpleProtocol); context.Features.Set(lifetimeManager); context.UserIdentifier = userIdProvider.GetUserId(webSocket.ConnectionInfo); return(context); }
public IActionResult Get([FromServices] IUserIdProvider userIdProvider) { // var userId = User.GetUserId<int>(); var userId2 = userIdProvider.GetUserId(); return(Ok(new object[] { userId2, new { User.Identity.IsAuthenticated, UserId = User.GetUserId(), User.Identity.Name, User.Identity.AuthenticationType, } })); }
internal async Task <bool> NegotiateAsync(TimeSpan timeout, IHubProtocolResolver protocolResolver, IUserIdProvider userIdProvider) { try { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(timeout); while (await _connectionContext.Transport.Reader.WaitToReadAsync(cts.Token)) { while (_connectionContext.Transport.Reader.TryRead(out var buffer)) { if (NegotiationProtocol.TryParseMessage(buffer, out var negotiationMessage)) { var protocol = protocolResolver.GetProtocol(negotiationMessage.Protocol, this); var transportCapabilities = Features.Get <IConnectionTransportFeature>()?.TransportCapabilities ?? throw new InvalidOperationException("Unable to read transport capabilities."); var dataEncoder = (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) == 0) ? (IDataEncoder)Base64Encoder : PassThroughEncoder; var transferModeFeature = Features.Get <ITransferModeFeature>() ?? throw new InvalidOperationException("Unable to read transfer mode."); transferModeFeature.TransferMode = (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) != 0) ? TransferMode.Binary : TransferMode.Text; ProtocolReaderWriter = new HubProtocolReaderWriter(protocol, dataEncoder); _logger.UsingHubProtocol(protocol.Name); UserIdentifier = userIdProvider.GetUserId(this); return(true); } } } } } catch (OperationCanceledException) { _logger.NegotiateCanceled(); } return(false); }
/// <summary>Creates a new instance of the UoW.</summary> /// <param name="connectionUri">The URI string used to connect the MongoDB.</param> /// <param name="userIdProvider">The provider for user ID used to filter user specific objects.</param> public MongoDbUow(string connectionUri, IUserIdProvider userIdProvider) { if (string.IsNullOrWhiteSpace(connectionUri)) { throw new ArgumentNullException(nameof(connectionUri)); } var mongoUrl = new MongoUrl(connectionUri); if (string.IsNullOrWhiteSpace(mongoUrl.DatabaseName)) { throw new ArgumentNullException("Missing database name in connection string"); } _database = new MongoClient(mongoUrl).GetDatabase(mongoUrl.DatabaseName); UserId = userIdProvider?.GetUserId(); }
public long Resolve(ChangePasswordRequest source, object destination, long destMember, ResolutionContext context) { if (string.IsNullOrEmpty(source.Token)) { return(_userIdProvider.GetUserId()); } else { var forgotPasswordToken = _authRepository.GetForgotPasswordTokenByToken(source.Token); if (forgotPasswordToken.ExpiresOn < TimeProvider.Current.Now) { throw new ExpiredTokenException(); } return(forgotPasswordToken.UserId); } }
public static bool TryGetUserId <T>(this IUserIdProvider userIdProvider, out T value, T defaultValue = default) { try { var userId = userIdProvider.GetUserId(); if (!string.IsNullOrEmpty(userId)) { value = userId.To <T>(); return(true); } } catch (Exception) { // ignored } value = defaultValue; return(false); }
public async Task <TransactionViewModel> GetTransactionAsync(long?transactionId = null) { var userId = _userIdProvider.GetUserId(); var wallets = await _walletsRepository.GetAllWalletsByUserIdAsync(userId); var viewModel = new TransactionViewModel(); if (transactionId.HasValue) { var transaction = await _transactionsRepository .GetTransactionByIdAsync(transactionId.Value); viewModel = _mapper.Map <TransactionViewModel>(transaction); viewModel.Wallets = new SelectList(wallets, "Id", "Name", viewModel.SelectedWalletId); } else { viewModel.Wallets = new SelectList(wallets, "Id", "Name"); } return(viewModel); }
private IEnumerable <Claim> BuildClaims(HttpContext context) { var userId = _userIdProvider.GetUserId(new ServiceHubConnectionContext(context)); return(ClaimsUtility.BuildJwtClaims(context.User, userId, GetClaimsProvider(context), _serverName, _mode, _enableDetailedErrors, _endpointsCount).ToList()); }
public long Resolve(object source, object destination, long destMember, ResolutionContext context) { return(_userIdProvider.GetUserId()); }
private IEnumerable <Claim> BuildClaims(HttpContext context) { var userId = _userIdProvider.GetUserId(new ServiceHubConnectionContext(context)); return(ClaimsUtility.BuildJwtClaims(context.User, userId, GetClaimsProvider(context)).ToList()); }
internal async Task <bool> NegotiateAsync(TimeSpan timeout, IList <string> supportedProtocols, IHubProtocolResolver protocolResolver, IUserIdProvider userIdProvider) { try { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(timeout); while (true) { var result = await _connectionContext.Transport.Input.ReadAsync(cts.Token); var buffer = result.Buffer; var consumed = buffer.End; var examined = buffer.End; try { if (!buffer.IsEmpty) { if (NegotiationProtocol.TryParseMessage(buffer, out var negotiationMessage, out consumed, out examined)) { Protocol = protocolResolver.GetProtocol(negotiationMessage.Protocol, supportedProtocols, this); // If there's a transfer format feature, we need to check if we're compatible and set the active format. // If there isn't a feature, it means that the transport supports binary data and doesn't need us to tell them // what format we're writing. var transferFormatFeature = Features.Get <ITransferFormatFeature>(); if (transferFormatFeature != null) { if ((transferFormatFeature.SupportedFormats & Protocol.TransferFormat) == 0) { throw new InvalidOperationException($"Cannot use the '{Protocol.Name}' protocol on the current transport. The transport does not support the '{Protocol.TransferFormat}' transfer mode."); } transferFormatFeature.ActiveFormat = Protocol.TransferFormat; } _cachedPingMessage = Protocol.WriteToArray(PingMessage.Instance); Log.UsingHubProtocol(_logger, Protocol.Name); UserIdentifier = userIdProvider.GetUserId(this); if (Features.Get <IConnectionInherentKeepAliveFeature>() == null) { // Only register KeepAlive after protocol negotiated otherwise KeepAliveTick could try to write without having a ProtocolReaderWriter Features.Get <IConnectionHeartbeatFeature>()?.OnHeartbeat(state => ((HubConnectionContext)state).KeepAliveTick(), this); } return(true); } } else if (result.IsCompleted) { break; } } finally { _connectionContext.Transport.Input.AdvanceTo(consumed, examined); } } } } catch (OperationCanceledException) { Log.NegotiateCanceled(_logger); } return(false); }
public override Task OnConnected() { _frontendQueriesFactory.Setup(_userIdProvider.GetUserId(Context.Request), Context.ConnectionId, a => {}); return(base.OnConnected()); }
public static T GetUserId <T>(this IUserIdProvider userIdProvider) { return(userIdProvider.GetUserId().ToOrDefault <T>()); }
internal async Task <bool> NegotiateAsync(TimeSpan timeout, IList <string> supportedProtocols, IHubProtocolResolver protocolResolver, IUserIdProvider userIdProvider) { try { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(timeout); while (true) { var result = await _connectionContext.Transport.Input.ReadAsync(cts.Token); var buffer = result.Buffer; var consumed = buffer.End; var examined = buffer.End; try { if (!buffer.IsEmpty) { if (NegotiationProtocol.TryParseMessage(buffer, out var negotiationMessage, out consumed, out examined)) { var protocol = protocolResolver.GetProtocol(negotiationMessage.Protocol, supportedProtocols, this); var transportCapabilities = Features.Get <IConnectionTransportFeature>()?.TransportCapabilities ?? throw new InvalidOperationException("Unable to read transport capabilities."); var dataEncoder = (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) == 0) ? (IDataEncoder)Base64Encoder : PassThroughEncoder; var transferModeFeature = Features.Get <ITransferModeFeature>() ?? throw new InvalidOperationException("Unable to read transfer mode."); transferModeFeature.TransferMode = (protocol.Type == ProtocolType.Binary && (transportCapabilities & TransferMode.Binary) != 0) ? TransferMode.Binary : TransferMode.Text; ProtocolReaderWriter = new HubProtocolReaderWriter(protocol, dataEncoder); _cachedPingMessage = ProtocolReaderWriter.WriteMessage(PingMessage.Instance); Log.UsingHubProtocol(_logger, protocol.Name); UserIdentifier = userIdProvider.GetUserId(this); if (Features.Get <IConnectionInherentKeepAliveFeature>() == null) { // Only register KeepAlive after protocol negotiated otherwise KeepAliveTick could try to write without having a ProtocolReaderWriter Features.Get <IConnectionHeartbeatFeature>()?.OnHeartbeat(state => ((HubConnectionContext)state).KeepAliveTick(), this); } return(true); } } else if (result.IsCompleted) { break; } } finally { _connectionContext.Transport.Input.AdvanceTo(consumed, examined); } } } } catch (OperationCanceledException) { Log.NegotiateCanceled(_logger); } return(false); }
public static T?GetUserId <T>(this IUserIdProvider userIdProvider, T?defaultValue = default) { return(userIdProvider.GetUserId().ToOrDefault(defaultValue)); }
public TodoDbContext(DbContextOptions <TodoDbContext> options, IUserIdProvider userIdProvider) : base(options) { UserId = userIdProvider.GetUserId(); }