Пример #1
0
 public override Task <IpAddressResponse> GetClientIpAddress(Empty request, ServerCallContext context)
 {
     return(Task.FromResult(new IpAddressResponse
     {
         IpAddress = context?.GetHttpContext()?.Connection?.RemoteIpAddress?.ToString() ?? ""
     }));
 }
        public override async Task <UpdateReply> Update(UpdateRequest request, ServerCallContext context)
        {
            try {
                Comment c = await commentsService.UpdateAsync(new Comment { Id = request.Id, Subject = request.Subject, Body = request.Body });

                return(new UpdateReply()
                {
                    Id = c.Id, PhotoId = c.PhotoId, Subject = c.Subject, UserName = c.UserName, Body = c.Body, SubmittedOn = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(c.SubmittedOn.ToUniversalTime())
                });
            } catch (UnauthorizedEditAttemptException <Comment> ) {
                //found on https://docs.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/error-handling
                var user     = context.GetHttpContext().User;
                var metadata = new Metadata {
                    { "User", user.Identity.Name }
                };
                throw new RpcException(new Status(StatusCode.PermissionDenied, "Permission denied"), metadata);
            }
        }
        private async Task <TResponse> ResolvedInterceptorInvoker(TRequest resolvedRequest,
                                                                  ServerCallContext resolvedContext)
        {
            GrpcActivatorHandle <TService> serviceHandle = default;

            try
            {
                serviceHandle = ServiceActivator.Create(resolvedContext.GetHttpContext().RequestServices);
                return(await _invoker(serviceHandle.Instance, resolvedRequest, resolvedContext));
            }
            finally
            {
                if (serviceHandle.Instance != null)
                {
                    await ServiceActivator.ReleaseAsync(serviceHandle);
                }
            }
        }
Пример #4
0
        public override async Task <Empty> Accept(AcceptRequest request, ServerCallContext context)
        {
            var user = context.GetHttpContext().User;

            if (!await _authorizationProvider.CheckAccessAsync(user, AcceptOperation, context.CancellationToken).ConfigureAwait(false))
            {
                throw RpcExceptions.AccessDenied();
            }
            _bus.Publish(new ElectionMessage.Accept(
                             Uuid.FromDto(request.ServerId).ToGuid(),
                             new DnsEndPoint(request.ServerHttp.Address,
                                             (int)request.ServerHttp.Port),
                             Uuid.FromDto(request.LeaderId).ToGuid(),
                             new DnsEndPoint(request.LeaderHttp.Address,
                                             (int)request.LeaderHttp.Port),
                             request.View));
            return(EmptyResult);
        }
Пример #5
0
        public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation)
        {
            TResponse response = null;

            try
            {
                response = await continuation(request, context);
            }
            finally
            {
                var httpContext = context.GetHttpContext();

                httpContext.Items.Add(BasicConfig.HttpReportsGrpcRequest, request);
                httpContext.Items.Add(BasicConfig.HttpReportsGrpcResponse, response);
            }

            return(response);
        }
Пример #6
0
        public override async Task <RemoveAuthenticatorReply> RemoveAuthenticator(RemoveAuthenticatorRequest request, ServerCallContext context)
        {
            Guid    id   = new Guid(request.Id);
            AppUser user = await _userManager.GetUserAsync(context.GetHttpContext().User);

            UserTotpDevice device = await _authDbContext.UserTotpDevices
                                    .Where(d => d.User == user)
                                    .Where(d => d.Id == id)
                                    .SingleAsync();

            _authDbContext.Remove(device);
            await _authDbContext.SaveChangesAsync();

            return(new RemoveAuthenticatorReply
            {
                Success = true,
            });
        }
        public override async Task <StateResp> State(StateReq request, ServerCallContext context)
        {
            var user = context.GetHttpContext().User;

            if (!await _authorizationProvider.CheckAccessAsync(user, StateOperation, context.CancellationToken)
                .ConfigureAwait(false))
            {
                throw AccessDenied();
            }
            var resultSource = new TaskCompletionSource <Value>();

            var options = request.Options;

            var name      = options.Name;
            var partition = options.Partition ?? string.Empty;

            var envelope = new CallbackEnvelope(OnMessage);

            _queue.Publish(new ProjectionManagementMessage.Command.GetState(envelope, name, partition));

            return(new StateResp {
                State = await resultSource.Task.ConfigureAwait(false)
            });

            void OnMessage(Message message)
            {
                if (!(message is ProjectionManagementMessage.ProjectionState result))
                {
                    resultSource.TrySetException(UnknownMessage <ProjectionManagementMessage.ProjectionState>(message));
                    return;
                }

                if (string.IsNullOrEmpty(result.State))
                {
                    resultSource.TrySetResult(new Value {
                        StructValue = new Struct()
                    });
                    return;
                }
                var document = JsonDocument.Parse(result.State);

                resultSource.TrySetResult(GetProtoValue(document.RootElement));
            }
        }
Пример #8
0
        public async Task CreateDuplexStreaming(
            IAsyncStreamReader <TRequest> requestStream,
            IServerStreamWriter <TResponse> responseStream,
            ServerCallContext context)
        {
            var httpContext = context.GetHttpContext();

            Logger.LogInformation($"Connection id: {httpContext.Connection.Id}");

            if (!await requestStream.MoveNext())
            {
                return;
            }

            var clientId = _messageProcessor.GetClientId(requestStream.Current);

            Logger.LogInformation($"{clientId} connected");
            var subscriber = new SubscribersModel <TResponse>
            {
                Subscriber = responseStream,
                Id         = $"{clientId}"
            };

            _serverGrpcSubscribers.AddSubscriber(subscriber);

            do
            {
                if (requestStream.Current == null)
                {
                    continue;
                }

                var resultMessage = _messageProcessor.Process(requestStream.Current);
                if (resultMessage == null)
                {
                    continue;
                }

                await _serverGrpcSubscribers.BroadcastMessageAsync(resultMessage);
            } while (await requestStream.MoveNext());

            _serverGrpcSubscribers.RemoveSubscriber(subscriber);
            Logger.LogInformation($"{clientId} disconnected");
        }
Пример #9
0
        public override async Task <Empty> RestartSubsystem(Empty request, ServerCallContext context)
        {
            var restartSubsystemSource = new TaskCompletionSource <Empty>();

            var user = context.GetHttpContext().User;

            if (!await _authorizationProvider.CheckAccessAsync(user,
                                                               RestartOperation, context.CancellationToken).ConfigureAwait(false))
            {
                throw RpcExceptions.AccessDenied();
            }

            _publisher.Publish(new SubscriptionMessage.PersistentSubscriptionsRestart(
                                   new CallbackEnvelope(HandleRestartSubsystemCompleted)));
            return(await restartSubsystemSource.Task.ConfigureAwait(false));

            void HandleRestartSubsystemCompleted(Message message)
            {
                if (message is ClientMessage.NotHandled notHandled &&
                    RpcExceptions.TryHandleNotHandled(notHandled, out var ex))
                {
                    restartSubsystemSource.TrySetException(ex);
                    return;
                }

                switch (message)
                {
                case SubscriptionMessage.PersistentSubscriptionsRestarting _:
                    restartSubsystemSource.TrySetResult(new Empty());
                    return;

                case SubscriptionMessage.InvalidPersistentSubscriptionsRestart fail:
                    restartSubsystemSource.TrySetException(
                        RpcExceptions.PersistentSubscriptionFailed("", "",
                                                                   $"Persistent Subscriptions cannot be restarted as it is in the wrong state."));
                    return;

                default:
                    restartSubsystemSource.TrySetException(
                        RpcExceptions.UnknownMessage <SubscriptionMessage.PersistentSubscriptionsRestarting>(message));
                    return;
                }
            }
        }
Пример #10
0
        private async Task <Reply> UpdateFields(Tags.Tag request, ServerCallContext context,
                                                Func <Tag, Task <Error> > updateField)
        {
            var reply = new Reply();
            var user  = await _userService.GetUser(context.GetHttpContext());

            if (user == null)
            {
                reply.Error = Error.NeedLogin;
                return(reply);
            }

            if (!user.HasWritePermission())
            {
                reply.Error = Error.NoPermission;
                return(reply);
            }

            if (Guid.TryParse(request.Id, out var id))
            {
                var item = await _service.All().Where(i => i.Id == id).FirstOrDefaultAsync();

                if (item != null)
                {
                    reply.Error = await updateField(item);

                    if (reply.Error == Error.None)
                    {
                        await _service.Update(item);
                    }
                }
                else
                {
                    reply.Error = Error.NoSuchEntity;
                }
            }
            else
            {
                reply.Error = Error.InvalidArguments;
            }

            return(reply);
        }
Пример #11
0
    public override async Task SayHellos(HelloRequest request, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context)
    {
        var httpContext = context.GetHttpContext();

        _logger.LogInformation($"Connection id: {httpContext.Connection.Id}");

        var i = 0;

        while (!context.CancellationToken.IsCancellationRequested)
        {
            var message = $"How are you {request.Name}? {++i}";
            _logger.LogInformation($"Sending greeting {message}.");

            await responseStream.WriteAsync(new HelloReply { Message = message });

            // Gotta look busy
            await Task.Delay(1000);
        }
    }
Пример #12
0
        public override async Task <UpdateResp> Update(UpdateReq request, ServerCallContext context)
        {
            var updatedSource = new TaskCompletionSource <bool>();
            var options       = request.Options;

            var user = context.GetHttpContext().User;

            if (!await _authorizationProvider.CheckAccessAsync(user, UpdateOperation, context.CancellationToken)
                .ConfigureAwait(false))
            {
                throw AccessDenied();
            }
            const string handlerType = "JS";
            var          name        = options.Name;
            var          query       = options.Query;
            bool?        emitEnabled = (options.EmitOptionCase, options.EmitEnabled) switch {
                (EmitOptionOneofCase.EmitEnabled, true) => true,
                (EmitOptionOneofCase.EmitEnabled, false) => false,
                (EmitOptionOneofCase.NoEmitOptions, _) => default,
Пример #13
0
        public override async Task <KeyValueReply> AddOrUpdate(KeyValue request, ServerCallContext context)
        {
            var reply = new KeyValueReply();
            var user  = await _userService.GetUser(context.GetHttpContext());

            if (user == null)
            {
                reply.Error = Error.NeedLogin;
                return(reply);
            }

            if (!user.HasWritePermission())
            {
                reply.Error = Error.NoPermission;
                return(reply);
            }

            if (string.IsNullOrWhiteSpace(request.Id))
            {
                reply.Error = Error.InvalidArguments;
                return(reply);
            }

            var item = await _service.All().Where(k => k.Id == request.Id).FirstOrDefaultAsync();

            Domain.Models.KeyValue newItem;
            if (item != null)
            {
                item.Value = request.Value;
                newItem    = await _service.Update(item);
            }
            else
            {
                newItem = await _service.Add(new Domain.Models.KeyValue {
                    Id = request.Id, Value = request.Value
                });
            }

            reply.KeyValue = new KeyValue {
                Id = newItem.Id, Value = newItem.Value
            };
            return(reply);
        }
Пример #14
0
        private async Task <Reply> UpdateFields(string id, ServerCallContext context,
                                                Func <User, Task <Error> > updateField)
        {
            var reply = new Reply();
            var user  = await _userService.GetUser(context.GetHttpContext());

            if (user == null)
            {
                reply.Error = Error.NeedLogin;
                return(reply);
            }

            if (!user.HasWritePermission())
            {
                reply.Error = Error.NoPermission;
                return(reply);
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                reply.Error = Error.InvalidArguments;
            }
            else
            {
                var item = await _service.All().Where(i => i.Id == id).FirstOrDefaultAsync();

                if (item != null)
                {
                    reply.Error = await updateField(item);

                    if (reply.Error == Error.None)
                    {
                        await _service.Update(item);
                    }
                }
                else
                {
                    reply.Error = Error.NoSuchEntity;
                }
            }

            return(reply);
        }
Пример #15
0
    public override async Task SayHellos(HelloRequest request, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context)
    {
        var httpContext = context.GetHttpContext();

        _logger.LogInformation($"Connection id: {httpContext.Connection.Id}");

        for (int i = 0; i < 3; i++)
        {
            var message = $"How are you {request.Name}? {i}";
            _logger.LogInformation($"Sending greeting {message}");
            await responseStream.WriteAsync(new HelloReply { Message = message });

            // Gotta look busy
            await Task.Delay(1000);
        }

        _logger.LogInformation("Sending goodbye");
        await responseStream.WriteAsync(new HelloReply { Message = $"Goodbye {request.Name}!" });
    }
Пример #16
0
        public override async Task <TradesResponse> GetTrades(TradesRequest request, ServerCallContext context)
        {
            var result = await _validationService.ValidateTradesRequestAsync(request.AssetPairId, request.Offset, request.Take);

            if (result != null)
            {
                return(new TradesResponse
                {
                    Error = new Error
                    {
                        Code = (int)result.Code,
                        Message = result.Message
                    }
                });
            }

            DateTime?from = null;
            DateTime?to   = null;

            if (DateTime.TryParse(request.From, out var fromDate))
            {
                from = fromDate;
            }

            if (DateTime.TryParse(request.To, out var toDate))
            {
                to = toDate;
            }

            var orderAction = request.OptionalSideCase == TradesRequest.OptionalSideOneofCase.None
                ? (OrderAction?)null
                : request.Side == Side.Buy ? OrderAction.Buy : OrderAction.Sell;
            var trades = await _historyClient.GetTradersAsync(context.GetHttpContext().User.GetWalletId(),
                                                              request.AssetPairId, request.Offset, request.Take, orderAction, from, to);

            var res  = new TradesResponse();
            var data = _mapper.Map <List <Trade> >(trades);

            res.Payload.AddRange(data);

            return(res);
        }
Пример #17
0
        public override async Task <TombstoneResp> Tombstone(TombstoneReq request, ServerCallContext context)
        {
            var options    = request.Options;
            var streamName = options.StreamName;

            var expectedVersion = options.ExpectedStreamRevisionCase switch {
                TombstoneReq.Types.Options.ExpectedStreamRevisionOneofCase.Revision =>
                new StreamRevision(options.Revision).ToInt64(),
                TombstoneReq.Types.Options.ExpectedStreamRevisionOneofCase.Any =>
                AnyStreamRevision.Any.ToInt64(),
                TombstoneReq.Types.Options.ExpectedStreamRevisionOneofCase.NoStream =>
                AnyStreamRevision.NoStream.ToInt64(),
                TombstoneReq.Types.Options.ExpectedStreamRevisionOneofCase.StreamExists =>
                AnyStreamRevision.StreamExists.ToInt64(),
                _ => throw new InvalidOperationException()
            };

            var requiresLeader = GetRequiresLeader(context.RequestHeaders);

            var user = context.GetHttpContext().User;
            var op   = DeleteOperation.WithParameter(Plugins.Authorization.Operations.Streams.Parameters.StreamId(streamName));

            if (!await _provider.CheckAccessAsync(user, op, context.CancellationToken).ConfigureAwait(false))
            {
                throw AccessDenied();
            }

            var position = await DeleteInternal(streamName, expectedVersion, user, true, requiresLeader,
                                                context.CancellationToken).ConfigureAwait(false);

            return(position.HasValue
                                ? new TombstoneResp {
                Position = new TombstoneResp.Types.Position {
                    CommitPosition = position.Value.CommitPosition,
                    PreparePosition = position.Value.PreparePosition
                }
            }
                                : new TombstoneResp {
                NoPosition = new Empty()
            });
        }
Пример #18
0
        public override async Task <Empty> PrepareOk(PrepareOkRequest request, ServerCallContext context)
        {
            var user = context.GetHttpContext().User;

            if (!await _authorizationProvider.CheckAccessAsync(user, PrepareOkOperation, context.CancellationToken).ConfigureAwait(false))
            {
                throw AccessDenied();
            }
            _bus.Publish(new ElectionMessage.PrepareOk(
                             request.View,
                             Uuid.FromDto(request.ServerId).ToGuid(),
                             new IPEndPoint(IPAddress.Parse(request.ServerInternalHttp.Address), (int)request.ServerInternalHttp.Port),
                             request.EpochNumber,
                             request.EpochPosition,
                             Uuid.FromDto(request.EpochId).ToGuid(),
                             request.LastCommitPosition,
                             request.WriterCheckpoint,
                             request.ChaserCheckpoint,
                             request.NodePriority));
            return(EmptyResult);
        }
        public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(
            TRequest request,
            ServerCallContext context,
            UnaryServerMethod <TRequest, TResponse> continuation)
        {
            if (_locator.TryGetValidator <TRequest>(out var validator))
            {
                var results = await validator.ValidateAsync(request);

                if (!results.IsValid)
                {
                    var message = await _handler.HandleAsync(results.Errors);

                    context.Status = new Status(StatusCode.InvalidArgument, message);
                    context.GetHttpContext().Response.Headers[GrpcProtocolConstants.StatusTrailerName] = GrpcProtocolConstants.StatusTrailerInvalidArgument;
                    return(ObjectCreator <TResponse> .Empty);
                }
            }

            return(await continuation(request, context));
        }
Пример #20
0
        private async Task <IQueryable <File> > FilterPrivate(IQueryable <File> items, ServerCallContext context)
        {
            //todo: permission via filetype: File->Adm, Resource->Login
            var readPrivate = (await _userService.GetUser(context.GetHttpContext())).HasReadPrivatePermission();

            if (!readPrivate)
            {
                var defStr = await _keyValueService.GetValue(ServerKeys.DefaultPrivate.Key);

                var defPrivate = defStr == "true";
                if (defPrivate)
                {
                    items = items.Where(i => i.Private == (ulong)PrivateType.Public);
                }
                else
                {
                    items = items.Where(i => i.Private != (ulong)PrivateType.Private);
                }
            }
            return(items);
        }
Пример #21
0
        public override async Task SendMessage(
            IAsyncStreamReader <ChatMessage> requestStream,
            IServerStreamWriter <ChatMessage> responseStream, ServerCallContext context)
        {
            string connectionId = context.GetHttpContext().Connection.Id;

            rooms[responseStream] = connectionId;

            await foreach (var request in requestStream.ReadAllAsync(context.CancellationToken))
            {
                foreach (var room in rooms)
                {
                    await room.Key.WriteAsync(new ChatMessage { Content = request.Content });
                }
            }

            //while (await requestStream.MoveNext(context.CancellationToken))
            //{

            //}
        }
        private async Task ResolvedInterceptorInvoker(IAsyncStreamReader <TRequest> requestStream, IServerStreamWriter <TResponse> responseStream, ServerCallContext resolvedContext)
        {
            GrpcActivatorHandle <TService> serviceHandle = default;

            try
            {
                serviceHandle = ServiceActivator.Create(resolvedContext.GetHttpContext().RequestServices);
                await _invoker(
                    serviceHandle.Instance,
                    requestStream,
                    responseStream,
                    resolvedContext);
            }
            finally
            {
                if (serviceHandle.Instance != null)
                {
                    await ServiceActivator.ReleaseAsync(serviceHandle);
                }
            }
        }
Пример #23
0
        public override async Task <Empty> ResetCache(Empty _, ServerCallContext context)
        {
            try
            {
                var user = context.GetHttpContext().User;
                _logger.LogInformation($"User {user.ToBlameString()} is resetting the cache.");
                await _configManager.ResetCacheAsync(user);

                return(new Empty());
            }
            catch (SecurityException ex)
            {
                _logger.LogError(ex, "Failed to reset cache.");
                throw new RpcException(new Status(StatusCode.PermissionDenied, ex.Message));
            }
            catch (Exception ex) when(!(ex is RpcException))
            {
                _logger.LogError(ex, "Failed to reset cache.");
                throw new RpcException(new Status(StatusCode.Internal, ex.Message));
            }
        }
Пример #24
0
        public override async Task <UserReply> GetUser(Empty request, ServerCallContext context)
        {
            string userId = _userManager.GetUserId(context.GetHttpContext().User);

            AppUser user = await _dbContext.Users
                           .Include(u => u.Groups)
                           .SingleAsync(u => u.Id == new Guid(userId));

            UserReply reply = new UserReply
            {
                Username = user.UserName,
                Email    = user.Email,
            };

            foreach (UserGroup group in user.Groups)
            {
                reply.GroupNames.Add(group.Name);
            }

            return(reply);
        }
Пример #25
0
        public override async Task <Reply> DeleteAll(Empty request, ServerCallContext context)
        {
            var reply = new Reply();
            var user  = await _userService.GetUser(context.GetHttpContext());

            if (user == null)
            {
                reply.Error = Error.NeedLogin;
                return(reply);
            }

            if (!user.HasWritePermission())
            {
                reply.Error = Error.NoPermission;
                return(reply);
            }

            await _service.DeleteAll();

            return(reply);
        }
        public override async Task <ChangePasswordResp> ChangePassword(ChangePasswordReq request,
                                                                       ServerCallContext context)
        {
            var options = request.Options;

            var user = context.GetHttpContext().User;
            var changePasswordOperation = ChangePasswordOperation;

            if (user?.Identity?.Name != null)
            {
                changePasswordOperation =
                    changePasswordOperation.WithParameter(
                        Plugins.Authorization.Operations.Users.Parameters.User(user.Identity.Name));
            }
            if (!await _authorizationProvider.CheckAccessAsync(user, changePasswordOperation, context.CancellationToken).ConfigureAwait(false))
            {
                throw RpcExceptions.AccessDenied();
            }
            var changePasswordSource = new TaskCompletionSource <bool>();

            var envelope = new CallbackEnvelope(OnMessage);

            _publisher.Publish(new UserManagementMessage.ChangePassword(envelope, user, options.LoginName,
                                                                        options.CurrentPassword,
                                                                        options.NewPassword));

            await changePasswordSource.Task.ConfigureAwait(false);

            return(new ChangePasswordResp());

            void OnMessage(Message message)
            {
                if (HandleErrors(options.LoginName, message, changePasswordSource))
                {
                    return;
                }

                changePasswordSource.TrySetResult(true);
            }
        }
Пример #27
0
        public override async Task <Empty> RestartPersistentSubscriptions(Empty request, ServerCallContext context)
        {
            var restart  = new TaskCompletionSource <bool>();
            var envelope = new CallbackEnvelope(OnMessage);

            var user = context.GetHttpContext().User;

            if (!await _authorizationProvider.CheckAccessAsync(user, RestartPersistentSubscriptionsOperation,
                                                               context.CancellationToken)
                .ConfigureAwait(false))
            {
                throw RpcExceptions.AccessDenied();
            }

            _publisher.Publish(new SubscriptionMessage.PersistentSubscriptionsRestart(envelope));

            await restart.Task.ConfigureAwait(false);

            return(new Empty());

            void OnMessage(Message message)
            {
                switch (message)
                {
                case SubscriptionMessage.PersistentSubscriptionsRestarting _:
                    restart.TrySetResult(true);
                    break;

                case SubscriptionMessage.InvalidPersistentSubscriptionsRestart _:
                    restart.TrySetResult(true);
                    break;

                default:
                    restart.TrySetException(
                        RpcExceptions
                        .UnknownMessage <SubscriptionMessage.PersistentSubscriptionsRestarting>(message));
                    break;
                }
            }
        }
Пример #28
0
        public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation)
        {
            TResponse response = null;

            try
            {
                response = await continuation(request, context);
            }
            catch (Exception ex)
            {
                _logger.LogError("UnaryServerHandler Error:" + ex.ToString());
            }
            finally
            {
                var httpContext = context.GetHttpContext();

                httpContext.Items.Add(BasicConfig.HttpReportsGrpcRequest, request);
                httpContext.Items.Add(BasicConfig.HttpReportsGrpcResponse, response);
            }

            return(response);
        }
Пример #29
0
        public override async Task <RemoveReply> Remove(RemoveRequest request, ServerCallContext context)
        {
            Photo ph = await photosService.FindAsync(request.Id);

            var user = context.GetHttpContext().User;
            var authorizationResult = await authorizationService.AuthorizeAsync(user, ph, Policies.EditDeletePhoto);

            if (authorizationResult.Succeeded)
            {
                ph = await photosService.RemoveAsync(request.Id);

                return(ph.ToRemoveReply());
            }
            else
            {
                //found on https://docs.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/error-handling
                var metadata = new Metadata {
                    { "User", user.Identity.Name }
                };
                throw new RpcException(new Status(StatusCode.PermissionDenied, "Permission denied"), metadata);
            }
        }
Пример #30
0
        public override async Task <Shared.Apps.AppListReply> ListApps(Empty request, ServerCallContext context)
        {
            Guid userId = new Guid(_userManager.GetUserId(context.GetHttpContext().User));

            IEnumerable <AuthApp> authApps = await _authDbContext.AuthApp
                                             .AsNoTracking()
                                             .Where(a => a.UserGroups.Any(u => u.Members.Any(m => m.Id == userId)))
                                             .ToListAsync();

            AppListReply reply = new AppListReply();

            foreach (AuthApp app in authApps)
            {
                reply.Apps.Add(new AppListEntry
                {
                    Id   = app.Id.ToString(),
                    Name = app.Name,
                });
            }

            return(reply);
        }