Exemple #1
0
        protected new IActionResult Response(object result = null)
        {
            if (IsValidOperation())
            {
                return(Ok(new
                {
                    success = true,
                    data = result
                }));
            }

            return(BadRequest(new
            {
                success = false,
                errors = _notifications.GetNotifications().Select(n => n.Value)
            }));
        }
Exemple #2
0
        protected new IActionResult Response(object result = null)
        {
            if (!ModelState.IsValid)
            {
                NotificarErroModelInvalida();
            }

            if (OperacaoValida())
            {
                return(Ok(result));
            }

            return(BadRequest(new
            {
                errors = _notifications.GetNotifications().Select(p => p.Value)
            }));
        }
        /// <summary>
        /// Objeto de resposta às requisições
        /// </summary>
        /// <param name="result">Qualquer objeto de retorno</param>
        /// <returns></returns>
        protected new IActionResult Response(object result = null)
        {
            if (OperacaoValida())
            {
                return(Ok(new
                {
                    success = true,
                    data = result
                }));
            }

            return(BadRequest(new
            {
                success = false,
                erros = _notifications.GetNotifications().Select(n => n.Value) // retorna somente o valor da notificação
            }));
        }
Exemple #4
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (_domainNotification.HasNotifications)
            {
                context.HttpContext.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                context.HttpContext.Response.ContentType = "application/json";

                var notifications = JsonConvert.SerializeObject(
                    _domainNotification.GetNotifications().Select(GetMessageNotifications).ToArray());

                await context.HttpContext.Response.WriteAsync(notifications);

                return;
            }

            next();
        }
Exemple #5
0
        public async Task <IActionResult> Reservation([FromBody] ReservationInput reservation)
        {
            try
            {
                var result = await _reservationService.InsertAsync(reservation.UserId, reservation.ProductionId, DateTime.Now, reservation.InitialDate, reservation.FinalDate);

                if (result > 0)
                {
                    return(Ok());
                }
                return(OkOrNoContent(_notificationHandler.GetNotifications()));
            }
            catch (Exception ex)
            {
                return(BadRequest());;
            }
        }
Exemple #6
0
        protected new IActionResult Response(object result = null, int totalRows = 0)
        {
            if (OperacaoValida())
            {
                return(Ok(new
                {
                    success = true,
                    data = result,
                    totalRows = totalRows
                }));
            }

            return(BadRequest(new
            {
                success = false,
                errors = _notifications.GetNotifications().Select(n => new ValidationError(n.Key, n.Value))
            }));
        }
Exemple #7
0
        public async Task <IActionResult> OnGetAsync(int playerId = 0)
        {
            if (playerId == 0)
            {
                return(Content("请重新进入游戏"));
            }

            var command = new JoinGameCommand(_account.UserId, playerId);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return(Content(errorMessage));
            }

            return(RedirectToPage("/Game/Index"));
        }
Exemple #8
0
        protected new IActionResult Response(object result = null)
        {
            if (IsValidOperation())
            {
                if (result == null)
                {
                    return(NoContent());
                }

                return(Ok(result));
            }

            _logger.Log(LogLevel.Warning, JsonConvert.SerializeObject(Notifications, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));

            return(BadRequest(_notifications.GetNotifications().Select(n => n.Value)));
        }
Exemple #9
0
        public void DeveAdicionarUmaNotification()
        {
            var notificationBuilder = new DomainNotificationBuilder()
                                      .Comkey("Id")
                                      .ComValue("Id inválido")
                                      .Instanciar();

            _domainNotification.Handle(notificationBuilder, default);

            _domainNotification.GetNotifications().Should().NotBeNull();
            _domainNotification.GetNotifications().Should().HaveCount(1);
            _domainNotification.GetNotifications().Should().BeEquivalentTo(notificationBuilder);
            _domainNotification.HasNotifications().Should().BeTrue();
        }
        protected new async Task <IActionResult> Response(object result = null)
        {
            if (OperationIsValid())
            {
                var retok = Task.Run(() => Ok(new
                {
                    success = true,
                    data    = result
                }));

                return(await retok);
            }

            var ret = Task.Run(() => BadRequest(new
            {
                success = false,
                errors  = _notifications.GetNotifications().Select(n => n.Value)
            }));

            return(await ret);
        }
Exemple #11
0
        protected new IActionResult Response(object result = null, HttpStatusCode statusCode = HttpStatusCode.OK)
        {
            if (IsValidOperation())
            {
                _logger.Information($"RESULTADO :: {JsonConvert.SerializeObject(result)}");
                return(StatusCode((int)statusCode, new
                {
                    result,
                    StatusCode = (int)statusCode
                }));
            }

            var responseMensage = new ResponseMensage
            {
                Mensagens  = _notifications.GetNotifications(),
                StatusCode = (int)statusCode
            };

            _logger.Information($"VALIDAÇÕES :: {JsonConvert.SerializeObject(responseMensage)}");
            return(StatusCode((int)statusCode, responseMensage));
        }
        // A palavra chave new determina que estamos usando o nosso próprio response
        protected new IActionResult Response(object result = null)
        {
            if (OperacaoValida())
            {
                var vOk = Ok(new
                {
                    success = true,
                    data    = result
                });

                // Ok result produz um status code 200
                return(vOk);
            }

            // BadRequest result produz um status code 400, algo não deu certo
            return(BadRequest(new
            {
                success = false,
                errors = _notifications.GetNotifications().Select(n => n.Value)
            }));
        }
Exemple #13
0
        protected new IActionResult Response(object result = null)
        {
            if (ValidOperation())
            {
                return(Ok(new
                {
                    success = true,
                    data = "OK"
                           //data = result -> 'Operation is not supported on this platform
                           //https://github.com/JamesNK/Newtonsoft.Json/issues/1404
                }));
            }

            var errorsNotifications = _notifications.GetNotifications().Select(n => _localizer[n.Value]);

            LogNotificationErrors(errorsNotifications);
            return(BadRequest(new
            {
                success = false,
                errors = errorsNotifications
            }));
        }
Exemple #14
0
        public async Task <IActionResult> OnPostAsync([FromBody] PlayerCreateDto dto)
        {
            var userId = _accountContext.UserId;

            var command = new CreateCommand(dto.Name, dto.Gender, userId, dto.Str, dto.Con, dto.Dex, dto.Int);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return(await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                })));
            }

            return(await Task.FromResult(new JsonResult(new
            {
                status = true
            })));
        }
        protected IActionResult CreateResponse(HttpStatusCode code, object result)
        {
            switch (code)
            {
            case HttpStatusCode.OK:
                if (_notifications.HasNotifications())
                {
                    return(Ok(new { success = false, data = _notifications.GetNotifications() }));
                }
                if (result == null)
                {
                    return(Ok(new { success = false, data = "Nenhum resultado gerado no request." }));
                }
                return(Ok(new { success = true, data = result }));

            case HttpStatusCode.BadRequest:
                return(BadRequest(result));

            default:
                return(BadRequest(result));
            }
        }
Exemple #16
0
        public async Task <IActionResult> OnPostAsync([FromBody] UserRegDto dto)
        {
            var userId = _accountContext.UserId;

            var command = new RegCommand(dto.Email, dto.Password, dto.Code);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return(await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                })));
            }

            return(await Task.FromResult(new JsonResult(new
            {
                status = true
            })));
        }
Exemple #17
0
        public async Task <IActionResult> OnPostAsync()
        {
            var userId = _accountContext.UserId;

            var command = new LogoutCommand(userId);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return(await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                })));
            }

            return(await Task.FromResult(new JsonResult(new
            {
                status = true
            })));
        }
Exemple #18
0
        public async Task <IActionResult> Login([FromBody] UserLoginModel ViewModel)
        {
            await _UserService.Login(ViewModel);

            var list   = _Notifications.GetNotifications();
            var sucess = Convert.ToBoolean((from item in list
                                            where item.Key == "Sucess"
                                            select item.Value.ToString())
                                           .FirstOrDefault());
            var data = (from item in list
                        where item.Key == "data"
                        select item.Value).FirstOrDefault();

            if (string.IsNullOrEmpty(data))
            {
                data = _Notifications.GetErrorMessage();
            }
            return(Ok(new
            {
                sucess,
                data
            }));
        }
Exemple #19
0
        public ActionResult Create(StudentViewModel studentView)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(studentView));
                }

                _studentAppService.Register(studentView);
                ////对错误进行记录,还需要抛给前台

                var notificacoes = _domainNotificationHandler.GetNotifications();
                notificacoes.ForEach(c => ViewData.ModelState.AddModelError(string.Empty, c.Value));

                return(View());
            }
            catch (Exception ex)
            {
                throw;
            }
            //return View(studentView);
        }
Exemple #20
0
        protected async Task <bool> DoCommand(Func <Task> func)
        {
            //踢出自己
            var connectionId = await _mudOnlineProvider.GetConnectionId(_account.PlayerId);

            if (string.IsNullOrEmpty(connectionId))
            {
                await KickOut(Context.ConnectionId);
                await ShowSystemMessage(Context.ConnectionId, "你已经断线,请刷新或重新登录");

                Context.Abort();
                return(await Task.FromResult(false));
            }

            if (connectionId != Context.ConnectionId)
            {
                await KickOut(Context.ConnectionId);
                await ShowSystemMessage(Context.ConnectionId, "你已经断线,请刷新或重新登录");

                Context.Abort();
                return(await Task.FromResult(false));
            }

            await func?.Invoke();


            if (!IsValidOperation())
            {
                foreach (var notification in _notifications.GetNotifications())
                {
                    await ShowSystemMessage(Context.ConnectionId, notification.Content);
                }
                return(await Task.FromResult(false));
            }
            return(await Task.FromResult(true));
        }
        public async Task Validar_Metodo_Insert_Sem_Dados_Obrigatorios(string name, int idEditor, int age)
        {
            //Arrange
            var input = new HeroInput();

            input.Name     = name;
            input.IdEditor = idEditor;
            input.Age      = age;

            //Act
            var result = await this.heroAppService
                         .InsertAsync(input)
                         .ConfigureAwait(false);

            //Assert
            result
            .Should()
            .Be(default(Hero));

            domainNotificationHandler
            .GetNotifications()
            .Should()
            .HaveCount(1);

            domainNotificationHandler
            .GetNotifications()
            .FirstOrDefault()
            .DomainNotificationType
            .Should()
            .Be(DomainNotificationType.BadRequest);

            domainNotificationHandler
            .GetNotifications()
            .FirstOrDefault()
            .Value
            .Should()
            .Be("Os dados são obrigatórios");
        }
        public async Task Validar_Metodo_Insert_Sem_Dados_Obrigatorios()
        {
            // Arrange
            var input = new HeroInput();

            // Act
            var result = await this
                         .heroAppService
                         .Insert(input)
                         .ConfigureAwait(false);

            // Assert
            result
            .Should()
            .Be(default(Hero));

            domainNotificationHandler
            .GetNotifications()
            .Should()
            .HaveCount(1);


            domainNotificationHandler
            .GetNotifications()
            .FirstOrDefault()
            .DomainNotificationType
            .Should()
            .Be(DomainNotificationType.BadRequest);

            domainNotificationHandler
            .GetNotifications()
            .FirstOrDefault()
            .Value
            .Should()
            .Be("Os dados não foram preenchidos corretamente!");
        }
Exemple #23
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 protected List <DomainNotification> GetValidations()
 {
     return(_notifications.GetNotifications());
 }
Exemple #24
0
        public async Task <IActionResult> ExternalLoginCallback()
        {
            // read external identity from the temporary cookie
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);

            if (result?.Succeeded != true)
            {
                throw new Exception("External authentication error");
            }

            // lookup our user and external provider info
            var(user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);

            if (user == null)
            {
                // this might be where you might initiate a custom workflow for user registration
                // in this sample we don't show how that would be done, as our sample implementation
                // simply auto-provisions new external user
                user = await AutoProvisionUserAsync(provider, providerUserId, claims);

                if (user == null)
                {
                    return(RedirectToAction("LoginError", "Home", new { Error = string.Join(" ", _notifications.GetNotifications().Select(a => $"{a.Key}: {a.Value}")) }));
                }
            }

            // this allows us to collect any additonal claims or properties
            // for the specific prtotocols used and store them in the local auth cookie.
            // this is typically used to store data needed for signout from those protocols.
            var additionalLocalClaims = new List <Claim>();
            var localSignInProps      = new AuthenticationProperties();

            ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
            ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
            ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);

            // issue authentication cookie for user

            var s = await _userManager.FindByNameAsync(user.UserName);

            var principal = await _signInManager.CreateUserPrincipalAsync(s);

            additionalLocalClaims.AddRange(principal.Claims);
            var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? s.Id.ToString();

            await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, s.Id.ToString(), name));

            await HttpContext.SignInAsync(s.Id.ToString(), name, provider, localSignInProps, additionalLocalClaims.ToArray());

            // delete temporary cookie used during external authentication
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            // validate return URL and redirect back to authorization endpoint or a local page
            var returnUrl = result.Properties.Items["returnUrl"];

            // check if external login is in the context of an OIDC request
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context != null)
            {
                if (await _clientStore.IsPkceClientAsync(context.ClientId))
                {
                    // if the client is PKCE then we assume it's native, so this change in how to
                    // return the response is for better UX for the end user.
                    return(View("Redirect", new RedirectViewModel {
                        RedirectUrl = returnUrl
                    }));
                }
            }

            return(Redirect(returnUrl));
        }
 protected IEnumerable <string> GetErroMessage()
 {
     return(_notifications.GetNotifications().Select(c => c.Value).ToList());
 }
Exemple #26
0
 public MessageHttpResponse(Object data, DomainNotificationHandler domainNotification)
 {
     this.data     = data;
     this.messages = domainNotification.HasNotifications() ? domainNotification.GetNotifications() : null;
     this.type     = domainNotification.HasNotifications() ? typeMessage.VALIDATION_ERROR : typeMessage.SUCCESS;
 }
Exemple #27
0
 public Task RaiseEvent <T>(T @event) where T : Event
 {
     _domainNotification.GetNotifications().Add(@event as DomainNotification);
     return(Task.CompletedTask);
 }
Exemple #28
0
 public Dictionary <string, List <string> > GetNotifications()
 {
     return(notifications.GetNotifications()
            .GroupBy(g => g.Key)
            .ToDictionary(d => d.Key, d => d.Select(x => x.Value).ToList()));
 }
Exemple #29
0
        public async Task <IActionResult> ExternalLoginCallback()
        {
            // read external identity from the temporary cookie
            var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

            if (result?.Succeeded != true)
            {
                throw new Exception("External authentication error");
            }

            // lookup our user and external provider info
            var(user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);

            if (user == null)
            {
                // this might be where you might initiate a custom workflow for user registration
                // in this sample we don't show how that would be done, as our sample implementation
                // simply auto-provisions new external user
                user = await AutoProvisionUserAsync(provider, providerUserId, claims);

                if (user == null)
                {
                    return(RedirectToAction("LoginError", "Home", new { Error = string.Join(" ", _notifications.GetNotifications().Select(a => $"{a.Key}: {a.Value}")) }));
                }
            }

            // this allows us to collect any additonal claims or properties
            // for the specific prtotocols used and store them in the local auth cookie.
            // this is typically used to store data needed for signout from those protocols.
            var additionalLocalClaims = new List <Claim>();
            var localSignInProps      = new AuthenticationProperties();

            ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
            ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
            ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);

            // issue authentication cookie for user
            // we must issue the cookie maually, and can't use the SignInManager because
            // it doesn't expose an API to issue additional claims from the login workflow
            // I don't have pride of this.
            var s = new UserIdentity()
            {
                Id                   = user.Id,
                Name                 = user.Name,
                SecurityStamp        = user.SecurityStamp,
                AccessFailedCount    = user.AccessFailedCount,
                Bio                  = user.Bio,
                Company              = user.Company,
                Email                = user.Email,
                EmailConfirmed       = user.EmailConfirmed,
                JobTitle             = user.JobTitle,
                LockoutEnabled       = user.LockoutEnabled,
                LockoutEnd           = user.LockoutEnd,
                PhoneNumber          = user.PhoneNumber,
                PhoneNumberConfirmed = user.PhoneNumberConfirmed,
                Picture              = user.Picture,
                TwoFactorEnabled     = user.TwoFactorEnabled,
                Url                  = user.Url,
                UserName             = user.UserName,
            };
            var principal = await _signInManager.CreateUserPrincipalAsync(s);

            additionalLocalClaims.AddRange(principal.Claims);
            var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id.ToString();
            await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id.ToString(), name));

            await HttpContext.SignInAsync(user.Id.ToString(), name, provider, localSignInProps, additionalLocalClaims.ToArray());

            // delete temporary cookie used during external authentication
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            // validate return URL and redirect back to authorization endpoint or a local page
            var returnUrl = result.Properties.Items["returnUrl"];

            if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemple #30
0
 private IEnumerable <string> GetValidationErrors()
 {
     return(_notifications.GetNotifications().Select(c => c.Value));
 }