Exemplo n.º 1
0
    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));
        }
Exemplo n.º 3
0
        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());
        }
Exemplo n.º 4
0
        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());
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
        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,
                                     } }));
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        /// <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);
            }
        }
Exemplo n.º 12
0
        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);
        }
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        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());
        }
Exemplo n.º 15
0
 public long Resolve(object source, object destination, long destMember, ResolutionContext context)
 {
     return(_userIdProvider.GetUserId());
 }
Exemplo n.º 16
0
        private IEnumerable <Claim> BuildClaims(HttpContext context)
        {
            var userId = _userIdProvider.GetUserId(new ServiceHubConnectionContext(context));

            return(ClaimsUtility.BuildJwtClaims(context.User, userId, GetClaimsProvider(context)).ToList());
        }
Exemplo n.º 17
0
        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);
        }
Exemplo n.º 18
0
        public override Task OnConnected()
        {
            _frontendQueriesFactory.Setup(_userIdProvider.GetUserId(Context.Request), Context.ConnectionId, a => {});

            return(base.OnConnected());
        }
Exemplo n.º 19
0
 public static T GetUserId <T>(this IUserIdProvider userIdProvider)
 {
     return(userIdProvider.GetUserId().ToOrDefault <T>());
 }
Exemplo n.º 20
0
        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);
        }
Exemplo n.º 21
0
 public static T?GetUserId <T>(this IUserIdProvider userIdProvider, T?defaultValue = default)
 {
     return(userIdProvider.GetUserId().ToOrDefault(defaultValue));
 }
Exemplo n.º 22
0
 public TodoDbContext(DbContextOptions <TodoDbContext> options, IUserIdProvider userIdProvider)
     : base(options)
 {
     UserId = userIdProvider.GetUserId();
 }