Exemplo n.º 1
0
        public async Task <EventViewmodel> Find(Guid eventUuid, UserHelper requestingUser)
        {
            if (eventUuid == Guid.Empty)
            {
                throw new UnprocessableException();
            }

            EventDto dbEvent = await _eventDal.Find(eventUuid);

            if (dbEvent == null)
            {
                throw new KeyNotFoundException();
            }

            var         mappedEvent        = _mapper.Map <EventViewmodel>(dbEvent);
            List <Guid> userUuidCollection = GetUserUuidsFromEvent(mappedEvent);

            var usersFromUserService = _rpcClient.Call <List <UserRabbitMq> >(userUuidCollection, RabbitMqQueues.FindUserQueue);

            AddUsernamesToEventDate(requestingUser, mappedEvent, usersFromUserService);
            AddUsernamesToEventSteps(requestingUser, mappedEvent, usersFromUserService);

            mappedEvent.CanBeRemoved = dbEvent.AuthorUuid != Guid.Empty &&
                                       dbEvent.AuthorUuid == requestingUser.Uuid;
            return(mappedEvent);
        }
Exemplo n.º 2
0
        static bool Execute()
        {
            var response = _rpcClient.Call <string>("rpc_queue", string.Empty, string.Empty);

            Interlocked.Increment(ref tps);

            return(true);
        }
Exemplo n.º 3
0
        public async Task <User> GetUser(Guid id)
        {
            string message  = $"GetUserWithId:{id}";
            var    response = await rpcClient.Call(message);

            var user = JsonConvert.DeserializeObject <User>(response);

            return(user);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Checks if the credentials are correct and returns an jwt and refresh token if password is correct
        /// </summary>
        /// <param name="login">The username and password</param>
        /// <returns>An jwt and refresh token if password is correct, if not correct null is returned</returns>
        public async Task <LoginResultViewmodel> Login(Login login)
        {
            UserDto dbUser = await _userDal.Find(login.Username);

            if (dbUser == null)
            {
                throw new UnauthorizedAccessException();
            }

            bool userIsDisabled = _rpcClient.Call <bool>(dbUser.Uuid, RabbitMqQueues.DisabledExistsUserQueue);

            if (userIsDisabled)
            {
                throw new DisabledUserException();
            }

            bool passwordCorrect = _securityLogic.VerifyPassword(login.Password, dbUser.Password);

            if (!passwordCorrect)
            {
                throw new UnauthorizedAccessException();
            }

            if (login.LoginCode > 99999 && login.LoginCode < 1000000 && login.SelectedAccountRole != AccountRole.Undefined)
            {
                return(await LoginWithSelectedAccount(login, dbUser));
            }

            if (dbUser.AccountRole > AccountRole.User)
            {
                return(await HandleMultipleAccountRolesLogin(dbUser));
            }

            AuthorizationTokensViewmodel tokens = await _jwtLogic.CreateJwt(dbUser);

            return(new LoginResultViewmodel
            {
                Jwt = tokens.Jwt,
                RefreshToken = tokens.RefreshToken
            });
        }
Exemplo n.º 5
0
        public void Call_ValidMessage_ReturnsString()
        {
            // Arrange
            IRpcClient client = Mock.Of <IRpcClient>(c => c.Call("ping") == "pong");

            //var mockClient = new Mock<IRpcClient>();
            //mockClient
            //  .Setup(c => c.Call("ping"))
            //  .Returns("pong");
            //var client = mockClient.Object;

            // Act
            var response = client.Call("ping");

            // Assert
            response.Should().Be("pong");
        }
        /// <summary>
        /// 调用
        /// </summary>
        /// <param name="method">方法</param>
        /// <param name="message">消息</param>
        /// <returns>返回数据</returns>
        public virtual object Call(MethodInfo method, object message)
        {
            var assemblyName = method.DeclaringType.Assembly.GetName().Name;
            var configInfo   = amqpConfigReader.Reader();

            if (configInfo == null)
            {
                throw new Exception("找不到AMQP配置信息");
            }

            var assemblyQueue = configInfo.ToRpcClientAssemblyQueue(assemblyName);

            if (assemblyQueue == null)
            {
                throw new Exception($"找不到程序集[{assemblyName}]的RPC客户端配置信息");
            }

            var byteSeri = GetByteSerialization(assemblyQueue.RpcClientAssembly.DataType);
            var byteData = byteSeri.Serialize(message);

            IRpcClient rpcClient = GetAvailableRpcClient(assemblyQueue);
            var        reData    = rpcClient.Call(byteData);

            // 如果返回值是空或者类型是void,则直接返回null
            if (reData.IsNullOrLength0() || method.ReturnType.IsTypeVoid())
            {
                return(null);
            }
            else
            {
                Type targetType = method.GetReturnValueType();
                if (targetType == null)
                {
                    return(null);
                }

                return(byteSeri.Deserialize(reData, targetType));
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Adds the datepicker to the database
        /// </summary>
        /// <param name="datepicker">The datepicker to add</param>
        /// <param name="requestingUser">The user that made the request</param>
        public async Task Add(DatepickerDto datepicker, UserHelper requestingUser)
        {
            datepicker.Uuid = Guid.NewGuid();
            if (!DatepickerValid(datepicker))
            {
                throw new UnprocessableException(nameof(datepicker));
            }

            datepicker.AuthorUuid = requestingUser.Uuid;
            datepicker.Dates.ForEach(d => d.DatePickerUuid = datepicker.Uuid);

            bool datepickerExists = await _datepickerDal.Exists(datepicker.Title);

            bool eventExists = _rpcClient.Call <bool>(datepicker.Title, RabbitMqQueues.ExistsEventQueue);

            if (eventExists || datepickerExists)
            {
                throw new DuplicateNameException();
            }

            await _datepickerDal.Add(datepicker);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Updates the user
        /// </summary>
        /// <param name="user">The new user data</param>
        /// <param name="requestingUserUuid">the uuid of the user that made the request</param>
        public async Task Update(User user, Guid requestingUserUuid)
        {
            if (!await UserModelValid(user))
            {
                throw new UnprocessableException();
            }

            UserDto dbUser = await _userDal.Find(requestingUserUuid);

            var userRabbitMq = _mapper.Map <UserRabbitMqSensitiveInformation>(user);

            userRabbitMq.Uuid        = dbUser.Uuid;
            userRabbitMq.AccountRole = dbUser.AccountRole;

            var passwordValid = _rpcClient.Call <bool>(userRabbitMq, RabbitMqQueues.ValidateUserPasswordQueue);

            if (!passwordValid)
            {
                throw new UnauthorizedAccessException();
            }

            await CheckForDuplicatedUserData(user, dbUser);

            dbUser.Username        = user.Username;
            dbUser.Email           = user.Email;
            dbUser.About           = user.About;
            dbUser.ReceiveEmail    = user.ReceiveEmail;
            dbUser.Hobbies         = _mapper.Map <List <UserHobbyDto> >(user.Hobbies);
            dbUser.FavoriteArtists = _mapper.Map <List <FavoriteArtistDto> >(user.FavoriteArtists);

            if (!string.IsNullOrEmpty(user.NewPassword) || dbUser.Username != user.Username)
            {
                userRabbitMq.Password = string.IsNullOrEmpty(user.NewPassword) ? user.Password : user.NewPassword;
                _publisher.Publish(userRabbitMq, RabbitMqRouting.UpdateUser, RabbitMqExchange.UserExchange);
            }

            await _userDal.Update(dbUser);
        }
Exemplo n.º 9
0
        public async Task <ActionResult <OrderModel> > PayForOrderAsync(int orderId, UserDetailsModel userDetails)
        {
            try
            {
                _logger.LogInformation("{Username} has started payment for the order with OrderId {OrderId}.",
                                       userDetails.Username, orderId);

                if (userDetails.CardAuthorizationInfo.ToLower() != "authorized" &&
                    userDetails.CardAuthorizationInfo.ToLower() != "unauthorized")
                {
                    throw new ArgumentException("CardAuthorizationInfo is not valid.");
                }


                var orderRequestDto = new OrderRequestDto {
                    OrderId = orderId
                };
                _rpcClient.Open();
                var order = _rpcClient.Call(orderRequestDto);
                _rpcClient.Close();


                if (order.OrderId == 0)
                {
                    throw new ArgumentException("No order with such id.");
                }

                if (userDetails.Username != order.Username)
                {
                    throw new ArgumentException("Usernames in order and user details should be equal.");
                }

                if (order.Status.ToLower() != "collecting")
                {
                    throw new InvalidOperationException("Order status should be \"Collecting\".");
                }

                switch (userDetails.CardAuthorizationInfo.ToLower())
                {
                case "authorized":
                    order.PaymentId = DateTime.Now.Ticks;
                    order.Status    = "Paid";
                    break;

                case "unauthorized":
                    order.PaymentId = DateTime.Now.Ticks;
                    order.Status    = "Failed";
                    break;
                }

                var payment = new Payment
                {
                    PaymentId = order.PaymentId.Value,
                    OrderId   = order.OrderId,
                    Username  = order.Username,
                    TotalCost = order.TotalCost,
                    IsPassed  = order.Status == "Paid" ? true : false
                };

                await _paymentRepository.AddPaymentAsync(payment);

                var payForOrderDto = _mapper.Map <PayForOrderDto>(order);

                _rabbitManager.Publish(payForOrderDto, "PaymentService_OrderExchange", ExchangeType.Direct, "PayForOrder");

                _logger.LogInformation("{Username} has finished payment for the order with OrderId {OrderId} with status {Status}.",
                                       order.Username, order.OrderId, order.Status);

                return(order);
            }
            catch (TimeoutException e)
            {
                _logger.LogInformation("{Username} has failed to perform payment for the order with OrderId {OrderId}.",
                                       userDetails.Username, orderId);

                return(StatusCode(408, e.Message));
            }
            catch (Exception e)
            {
                _logger.LogInformation("{Username} has failed to perform payment for the order with OrderId {OrderId}.",
                                       userDetails.Username, orderId);

                return(BadRequest(e.Message));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 调用
        /// </summary>
        /// <param name="method">方法</param>
        /// <param name="message">消息</param>
        /// <returns>返回数据</returns>
        public object Call(MethodInfo method, object message)
        {
            var assemblyName = method.DeclaringType.Assembly.GetName().Name;
            var configInfo   = rabbitConfigReader.Reader();

            if (configInfo == null)
            {
                throw new Exception("找不到RabbitConfig配置信息");
            }

            RpcClientAssemblyWrapInfo rpcClientAssemblyWrap;
            var messQueueInfo = GetMessageQueueByAssemblyName(configInfo, assemblyName, out rpcClientAssemblyWrap);

            if (rpcClientAssemblyWrap == null)
            {
                throw new Exception($"找不到程序集[{assemblyName}]的RPC客户端配置信息");
            }

            var byteSeri = GetByteSerialization(rpcClientAssemblyWrap.RpcClientAssembly.DataType);
            var byteData = byteSeri.Serialize(message);

            IRpcClient rpcClient = null;

            if (dicVirtualPathMapRpcClient.ContainsKey(rpcClientAssemblyWrap.RabbitVirtualPath.VirtualPath))
            {
                rpcClient = dicVirtualPathMapRpcClient[rpcClientAssemblyWrap.RabbitVirtualPath.VirtualPath];
            }
            else
            {
                lock (syncDicVirtualPathMapRpcClient)
                {
                    IMessageQueueConnection conn = null;
                    // 如果连接配置信息不全,则找默认的连接对象
                    if (string.IsNullOrWhiteSpace(rpcClientAssemblyWrap.RabbitVirtualPath.ConnectionString) && string.IsNullOrWhiteSpace(rpcClientAssemblyWrap.RabbitVirtualPath.ConnectionStringAppConfigName))
                    {
                        conn = SingleConnectionTool.CreateConnection();
                    }
                    else
                    {
                        conn = connectionFactoy.CreateAndOpen(new ConnectionWrapInfo()
                        {
                            ConnectionString = rpcClientAssemblyWrap.RabbitVirtualPath.ConnectionString,
                            ConnectionStringAppConfigName = rpcClientAssemblyWrap.RabbitVirtualPath.ConnectionStringAppConfigName
                        });
                    }
                    connections.Add(conn);

                    rpcClient = conn.CreateRpcClient(messQueueInfo);
                    try
                    {
                        dicVirtualPathMapRpcClient.Add(rpcClientAssemblyWrap.RabbitVirtualPath.VirtualPath, rpcClient);
                    }
                    catch (ArgumentException) { }
                }
            }

            var reData = rpcClient.Call(byteData);

            // 如果返回值是空或者类型是void,则直接返回null
            if (reData.IsNullOrLength0() || method.ReturnType.IsTypeVoid())
            {
                return(null);
            }
            else
            {
                Type targetType = null;

                // 判断返回类型是否Task
                if (method.ReturnType.IsTypeNotGenericityTask())
                {
                    return(null);
                }
                else if (method.ReturnType.IsTypeGenericityTask())
                {
                    targetType = method.ReturnType.GetProperty("Result").PropertyType;
                }
                else
                {
                    targetType = method.ReturnType;
                }

                return(byteSeri.Deserialize(reData, targetType));
            }
        }