Exemple #1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, AccountImage = model.AccountImage?.ToByteArray()
                };

                var result = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    var currentUser = await _userManager.FindByEmailAsync(user.Email).ConfigureAwait(false);

                    await _userManager.AddToRoleAsync(currentUser.Id, "User").ConfigureAwait(false);

                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : true).ConfigureAwait(false);

                    Logger.Log.Info($"Был зарегистрирован новый пользователь {user.Email}");
                    return(View("DisplayEmail"));
                }


                ModelState.AddModelErrors(result.Errors.Select(x => new ValidationResult(x)));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemple #2
0
 public IActionResult Put(long id, [FromBody] Calibration model)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             return(InvalidModelStateResult());
         }
         if (!validateEntity(model))
         {
             return(InvalidModelStateResult());
         }
         var modelStateDic = repository.ValidateEntity(model);
         if (modelStateDic.Count > 0)
         {
             ModelState.AddModelErrors(modelStateDic);
             return(InvalidModelStateResult());
         }
         if (repository.Get().Count(a => a.CalibrationId.Equals(model.CalibrationId)) == 0)
         {
             return(NotFound(Constants.ErrorMessages.NotFoundEntity));
         }
         return(Accepted(repository.Update(model)));
     }
     catch (Exception ex)
     {
         logger.LogError(ex.GetExceptionMessages());
         return(StatusCode(StatusCodes.Status500InternalServerError, Constants.ErrorMessages.UpdateError));
     }
 }
        public virtual object SaveEdit(string pagePath, Page pageInput, User currentUser)
        {
            string pageToEditPath = pagePath.Substring(0, pagePath.Length - ("/" + PageMode.Edit).Length);

            if (pageToEditPath.Length == pagePath.Length)
            {
                return(null);
            }

            Page page = pageService.GetPage(pageToEditPath);

            if (page == null)
            {
                return(null);
            }

            ValidationStateDictionary validationState;

            pageService.EditPage(page, pageInput.Parent, pageInput, out validationState);

            if (!validationState.IsValid)
            {
                ModelState.AddModelErrors(validationState);

                return(Edit(pageToEditPath));
            }

            page = pageService.GetPage(pageInput.Slug, pageInput.Parent.ID);

            return(Redirect(Url.AppPath(page.Path)));
        }
Exemple #4
0
        public ActionResult CreateGoal(GroupGoalFormModel goal)
        {
            GroupGoal groupgoal = Mapper.Map <GroupGoalFormModel, GroupGoal>(goal);
            var       groupUser = groupUserService.GetGroupUser(User.Identity.GetUserId(), goal.GroupId);

            groupgoal.GroupUserId = groupUser.GroupUserId;
            //groupgoal.GroupUser = groupUser;
            //if (groupgoal.AssignedTo == null)
            //{
            //    groupgoal.AssignedGroupUserId = null;
            //}
            var errors = groupGoalService.CanAddGoal(groupgoal, groupUpdateService).ToList();

            ModelState.AddModelErrors(errors);
            if (ModelState.IsValid)
            {
                //groupgoal.GroupUser.UserId = ((SocialGoalUser)(User.Identity)).UserId;
                groupGoalService.CreateGroupGoal(groupgoal);
                return(RedirectToAction("Index", new { id = goal.GroupId }));
            }
            //goal.Group = groupService.GetGroup(goal.GroupUser.GroupId);
            var metrics = metricService.GetMetrics();
            var focuss  = focusService.GetFocussOfGroup(goal.GroupId);

            goal.Metrics = metrics.ToSelectListItems(-1);
            goal.Foci    = focuss.ToSelectListItems(-1);
            return(View(goal));
        }
        // Bind(Include = "...") is used to avoid overposting attacks
        public async Task <ActionResult> EditInscripcion(EditOwnInscripcionViewModel viewModel)
        {
            try {
                Usuario user = await _usuarioEndpoint.GetCurrentUsuario(token : _userSession.BearerToken);

                viewModel.SetAlumno(user.Id);

                var entity = _mapper.Map <Inscripcion>(viewModel.Inscripcion);

                if (entity.State == null)
                {
                    entity.State = Inscripcion.InscripcionStates.Active;
                }

                await _inscripcionEndpoint.Put(entity, _userSession.BearerToken);
            } catch (UnauthorizedRequestException) {
                return(RedirectToAction("AccessDeniedPartial", "Error"));
            } catch (BadRequestException ex) {
                viewModel.SetEstadosAsSelectList();

                ModelState.AddModelErrors(ex.Errors);

                return(PartialView("_EditOwnInscripcion", viewModel));
            } catch (Exception ex) {
                return(RedirectToAction("SpecificErrorPartial", "Error", new { error = ex.Message }));
            }

            return(Content("OK"));
        }
Exemple #6
0
        public ActionResult Save(CategoryFormModel form)
        {
            if (ModelState.IsValid)
            {
                //TODO: Create Automapper form => command
                var command = new CreateOrUpdateCategoryCommand()
                {
                    CategoryId  = form.CategoryId,
                    Name        = form.Name,
                    Description = form.Description
                };

                IEnumerable <ValidationResult> errors = commandBus.Validate(command);
                ModelState.AddModelErrors(errors);
                if (ModelState.IsValid)
                {
                    var result = commandBus.Submit(command);
                    if (result.Success)
                    {
                        return(RedirectToAction("Index"));
                    }
                }
            }

            if (form.CategoryId == 0)
            {
                return(View("Create", form));
            }
            else
            {
                return(View("Edit", form));
            }
        }
Exemple #7
0
 public ActionResult Save(PostProfileFormModel form)
 {
     if (ModelState.IsValid)
     {
         var command = Mapper.Map <PostProfileFormModel, CreateOrUpdatePostProfileCommand>(form);
         IEnumerable <ValidationResult> errors = commandBus.Validate(command);
         ModelState.AddModelErrors(errors);
         if (ModelState.IsValid)
         {
             var result = commandBus.Submit(command);
             if (result.Success)
             {
                 return(RedirectToAction("Index"));
             }
         }
     }
     //if fail
     if (form.ProfileId == 0)
     {
         return(View("Create", form));
     }
     else
     {
         return(View("Edit", form));
     }
 }
Exemple #8
0
        public async Task <IActionResult> XhrEdit(ControllerModels.Messages.EditInput input)
        {
            var message = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id);

            if (message is null || message.Deleted)
            {
                throw new HttpNotFoundError();
            }

            if (message.PostedById != UserContext.ApplicationUser.Id && !UserContext.IsAdmin)
            {
                throw new HttpForbiddenError();
            }

            if (ModelState.IsValid)
            {
                var result = await MessageRepository.EditMessage(input);

                ModelState.AddModelErrors(result.Errors);

                if (ModelState.IsValid)
                {
                    await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message {
                        TopicId   = result.TopicId,
                        MessageId = result.MessageId
                    });

                    return(Ok());
                }
            }

            var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });

            return(new JsonResult(errors));
        }
Exemple #9
0
        public async Task <IActionResult> AddThought(int id, int smiley)
        {
            var message = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == id);

            if (message is null || message.Deleted)
            {
                throw new HttpNotFoundError();
            }

            if (ModelState.IsValid)
            {
                var result = await MessageRepository.AddThought(id, smiley);

                ModelState.AddModelErrors(result.Errors);

                if (ModelState.IsValid)
                {
                    await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message {
                        TopicId   = result.TopicId,
                        MessageId = result.MessageId
                    });

                    var redirectPath = Url.DisplayMessage(result.TopicId, result.MessageId);
                    return(Redirect(redirectPath));
                }
            }

            return(ForumViewResult.RedirectToReferrer(this));
        }
Exemple #10
0
        // Bind(Include = "...") is used to avoid overposting attacks
        public async Task <ActionResult> Edit(MvcDepartamentoModel departamento)
        {
            try
            {
                var entity = _mapper.Map <Departamento>(departamento);

                await _departamentoEndpoint.Put(entity, _userSession.BearerToken);
            }
            catch (UnauthorizedRequestException)
            {
                return(RedirectToAction("AccessDeniedPartial", "Error"));
            }
            catch (BadRequestException ex)
            {
                ModelState.AddModelErrors(ex.Errors);

                return(PartialView("_Edit", departamento));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("SpecificErrorPartial", "Error", new { error = ex.Message }));
            }

            return(Content("OK"));
        }
Exemple #11
0
        public async Task <IActionResult> XhrReply(ControllerModels.Messages.CreateReplyInput input)
        {
            if (input.Id > 0)
            {
                var message = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id);

                if (message is null || message.Deleted)
                {
                    throw new HttpNotFoundError();
                }
            }

            if (ModelState.IsValid)
            {
                var result = await MessageRepository.CreateReply(input);

                ModelState.AddModelErrors(result.Errors);

                if (ModelState.IsValid)
                {
                    await ForumHub.Clients.All.SendAsync("new-reply", new HubModels.Message {
                        TopicId   = result.TopicId,
                        MessageId = result.MessageId
                    });

                    return(Ok());
                }
            }

            var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });

            return(new JsonResult(errors));
        }
Exemple #12
0
        public virtual ActionResult Edit(TIdType id, TEditModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                // Send the errors to the debug console.
                ModelState.OutputErrors();

                PopulateEditModel(viewModel);
                return(EditFailed(viewModel));
            }

            var entity = GetEntity(id);

            if (entity == null)
            {
                return(HttpNotFound());
            }

            var errors = ProcessEdit(entity, viewModel);

            if (errors.Any())
            {
                ModelState.AddModelErrors(errors);
                PopulateEditModel(viewModel);

                return(EditFailed(viewModel));
            }

            return(EditSucceeded(viewModel, entity));
        }
        public async Task <ActionResult> Edit(EditMateriaViewModel viewModel)
        {
            try
            {
                var entity = _mapper.Map <Materia>(viewModel.Materia);

                await _materiaEndpoint.Put(entity, _userSession.BearerToken);
            }
            catch (UnauthorizedRequestException)
            {
                return(RedirectToAction("AccessDeniedPartial", "Error"));
            }
            catch (BadRequestException ex)
            {
                IEnumerable <Departamento> entities = await _departamentoEndpoint.GetAll(_userSession.BearerToken);

                var departamentos = _mapper.Map <IEnumerable <MvcDepartamentoModel> >(entities);
                viewModel.SetDepartamentosAsSelectList(departamentos);

                ModelState.AddModelErrors(ex.Errors);

                return(PartialView("_Edit", viewModel));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("SpecificErrorPartial", "Error", new { error = ex.Message }));
            }

            return(Content("OK"));
        }
Exemple #14
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Register([FromBody] RegisterUserInfoDTO model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var user = new IdentityUser {
                UserName = model.UserName, Email = model.Email
            };
            var result = await _userManager.CreateAsync(user, model.NewPassword);

            ActionResult actionResult;

            if (!result.Succeeded)
            {
                var errorDescriptions = result.Errors.Select(x => x.Description);
                Logger.LogError($"Tried to register user '{model.Email}', but failed. Errors:\n {string.Join("; ", errorDescriptions)}");

                ModelState.AddModelErrors(result.GetFormatedErrors());
                actionResult = BadRequest(ModelState);
            }
            else
            {
                Logger.LogInformation($"User '{model.Email}' created a new account with password.");
                actionResult = Ok(user);
            }

            return(actionResult);
        }
        public async Task <ActionResult> CreateHorario(CreateOwnHorarioConsultaViewModel viewModel)
        {
            try
            {
                Usuario user = await _usuarioEndpoint.GetCurrentUsuario(token : _userSession.BearerToken);

                viewModel.SetProfesor(user.Id);

                var horarioConsulta = _mapper.Map <HorarioConsulta>(source: viewModel.HorarioConsulta);

                await _horarioConsultaEndpoint.Post(horarioConsulta, _userSession.BearerToken);
            }
            catch (UnauthorizedRequestException)
            {
                return(RedirectToAction("AccessDenied", "Error"));
            }
            catch (BadRequestException ex)
            {
                IEnumerable <Materia> entities = await _materiaEndpoint.GetAll(_userSession.BearerToken);;

                var materias = _mapper.Map <IEnumerable <MvcMateriaModel> >(source: entities);
                viewModel.SetMateriasAsSelectList(materias);
                viewModel.SetDiasSemanaAsSelectList();

                ModelState.AddModelErrors(ex.Errors);

                return(PartialView("_CreateOwnHorario", viewModel));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("SpecificError", "Error", new { error = ex.Message }));
            }

            return(Content("OK"));
        }
Exemple #16
0
        public async Task <IActionResult> CompleteWithEmailAsync([FromQuery] SignUpCompleteWithEmailViewModel model)
        {
            User user = await UserManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("Email", ApiError.NotFound);
            }
            else if (user.EmailConfirmed)
            {
                ModelState.AddModelError("Email", ApiError.AlreadyCompleted);
            }
            else
            {
                IdentityResult result = await UserManager.ConfirmEmailAsync(user, model.Token);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, false);

                    return(Redirect("/email-confirmed"));
                }
                else
                {
                    ModelState.AddModelErrors(result);
                }
            }

            return(BadRequest(ModelState));
        }
Exemple #17
0
        public IActionResult SendToken(HomeSendToken m)
        {
            if (ModelState.IsValid)
            {
                if (m.Token.Equals("none", StringComparison.OrdinalIgnoreCase))
                {
                    throw new AppException("None is one bad-ass code which we do not accept.");
                }

                if (m.Token.Equals("everything", StringComparison.OrdinalIgnoreCase))
                {
                    ModelState.AddModelError(string.Empty, "Too greedy token!");
                }

                if (m.Token.Equals("secret", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        throw new AppException("It is secret, you know. No clue.");
                    }
                    catch (AppException ex)
                    {
                        ModelState.AddModelErrors(ex);
                    }
                }

                if (m.Token.Equals("error", StringComparison.OrdinalIgnoreCase))
                {
                    throw new Exception("Error!");
                }
            }

            return(View("Contact", m));
        }
Exemple #18
0
        // Bind(Include = "...") is used to avoid overposting attacks
        public async Task <ActionResult> Edit(EditHorarioConsultaFechadoViewModel viewModel)
        {
            try
            {
                var entity = _mapper.Map <HorarioConsultaFechado>(viewModel.HorarioConsultaFechado);

                await _horarioConsultaFechadoEndpoint.Put(entity, _userSession.BearerToken);
            }
            catch (UnauthorizedRequestException)
            {
                return(RedirectToAction("AccessDeniedPartial", "Error"));
            }
            catch (BadRequestException ex)
            {
                var horariosConsultaTask = _horarioConsultaEndpoint.GetAll(_userSession.BearerToken);

                await Task.WhenAll(horariosConsultaTask);

                var horariosConsulta = _mapper.Map <IEnumerable <MvcHorarioConsultaModel> >(source: horariosConsultaTask.Result);

                viewModel.SetHorariosConsultaAsSelectList(horariosConsulta);
                viewModel.SetEstadosAsSelectList();

                ModelState.AddModelErrors(ex.Errors);

                return(PartialView("_Edit", viewModel));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("SpecificErrorPartial", "Error", new { error = ex.Message }));
            }

            return(Content("OK"));
        }
Exemple #19
0
        public ActionResult Edit(int id, FormCollection forms)
        {
            if (id == 0)
            {
                CmsMenu newMenu = new CmsMenu()
                {
                    Title       = forms.GetValue("Title").AttemptedValue,
                    Description = forms.GetValue("Description").AttemptedValue,
                    Type        = forms.GetValue("Type").AttemptedValue
                };
                if (newMenu.IsValid)
                {
                    return(this.CreateNewMenu(newMenu));
                }

                ModelState.AddModelErrors(newMenu.GetRuleViolations());
                return(View(newMenu));
            }

            CmsMenu menu = this.menuService.LoadMenu(id);

            UpdateModel(menu, forms.ToValueProvider());
            this.menuService.SaveMenu(menu);
            TempData["SuccessResult"] = "Menu was successfully saved";
            return(this.View(menu));
        }
Exemple #20
0
        public async Task <IActionResult> Put(int id, [FromBody] ProductViewModel productViewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var product = _mapper.Map <Product>(productViewModel);

                    var validationResult = await _productHandler.CanUpdate(id, product);

                    if (validationResult == null)
                    {
                        product.Id = id;
                        var result = await _productService.Update(product);

                        if (result.ValidationResults.Count == 0)
                        {
                            return(Ok("Product modified successfully!"));
                        }

                        ModelState.AddModelErrors(result.ValidationResults);
                    }

                    ModelState.AddModelError(validationResult);
                }
            }
            catch (Exception ex)
            {
                var exceptionMessage = await Helpers.GetErrors(ex);

                ModelState.AddModelError(new ValidationResult(exceptionMessage));
            }

            return(BadRequest(ModelState.GetErrors()));
        }
Exemple #21
0
        public async Task <IActionResult> Post([FromBody] PurchaseOrder model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(this.InvalidModelStateResult <PurchaseOrdersController>(logger));
                }
                var modelStateDic = repository.ValidateEntity(model);
                if (modelStateDic.Count > 0)
                {
                    ModelState.AddModelErrors(modelStateDic);
                    return(this.InvalidModelStateResult <PurchaseOrdersController>(logger));
                }

                var result = await repository.CreateAsync(model);

                return(Accepted(result));
            }
            catch (Exception ex)
            {
                logger.LogError(ex.GetExceptionMessages());
                return(StatusCode(StatusCodes.Status500InternalServerError, Constants.ErrorMessages.CreateError));
            }
        }
        public IHttpActionResult Login(LoginRequestModel requestModel)
        {
            if (ModelState.IsValid)
            {
                AccountCommand accountCommand = Mapper.Map <AccountCommand>(requestModel);
                IEnumerable <ValidationResult> validations = commandDispatcher.Validate(accountCommand);

                ModelState.AddModelErrors(validations);

                if (ModelState.IsValid)
                {
                    AccountByUsernameQuery query = new AccountByUsernameQuery(requestModel.Username);
                    Account account = queryDispatcher.Dispatch <AccountByUsernameQuery, Account>(query);

                    AuthCommand    loginCommand   = new AuthCommand(account.Id, requestModel.RememberMe);
                    Authentication authentication = commandDispatcher.Dispatch <AuthCommand, Authentication>(loginCommand);

                    AccountResponseModel responseModel = Mapper
                                                         .Map <AccountResponseModel>(authentication)
                                                         .Map(account);

                    return(Ok(responseModel));
                }
            }

            return(BadRequest(ModelState));
        }
        public async Task <ActionResult> Subscribe(
            [Bind(Include = "HorarioConsultaFechadoId, Observation, Topic")] MvcInscripcionModel inscripcion)
        {
            try {
                Usuario user = await _usuarioEndpoint.GetCurrentUsuario(token : _userSession.BearerToken);

                inscripcion.State    = MvcInscripcionModel.InscripcionStates.Active;
                inscripcion.AlumnoId = user.Id;

                var entity = _mapper.Map <Inscripcion>(source: inscripcion);

                await _inscripcionEndpoint.Post(entity, _userSession.BearerToken);
            } catch (UnauthorizedRequestException) {
                return(RedirectToAction("AccessDeniedPartial", "Error"));
            } catch (BadRequestException ex) {
                HorarioConsultaFechado entity = await _horarioConsultaFechadoEndpoint.Get(inscripcion.HorarioConsultaFechadoId, _userSession.BearerToken);

                var horarioFechado = _mapper.Map <MvcHorarioConsultaFechadoModel>(source: entity);

                inscripcion.HorarioConsultaFechado = horarioFechado;

                ModelState.AddModelErrors(ex.Errors);

                return(PartialView("_Subscribe", inscripcion));
            } catch (Exception ex) {
                return(RedirectToAction("SpecificErrorPartial", "Error", new { error = ex.Message }));
            }

            return(Content("OK"));
        }
Exemple #24
0
        public async Task <IActionResult> Reset(ResetPasswordCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(View(command));
            }

            var response = await this.Mediator.Send(command);

            if (response.IsFailure)
            {
                ModelState.AddModelErrors(response.Errors);
                command.NewPassword        = string.Empty;
                command.ConfirmNewPassword = string.Empty;

                return(View(command));
            }

            return(RedirectToAction("Result", new ResultViewModel
            {
                IsSuccess = true,
                Title = "Reset Password",
                Description = "You can reset your password",
                Messages = new List <string>()
                {
                    "You're password has been successfully changed!"
                }
            }));
        }
Exemple #25
0
        public IActionResult Post([FromBody] Calibration model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(InvalidModelStateResult());
                }
                if (!validateEntity(model))
                {
                    return(InvalidModelStateResult());
                }
                var modelStateDic = repository.ValidateEntity(model);
                if (modelStateDic.Count > 0)
                {
                    ModelState.AddModelErrors(modelStateDic);
                    return(InvalidModelStateResult());
                }

                return(Accepted(repository.Create(model)));
            }
            catch (Exception ex)
            {
                logger.LogError(ex.GetExceptionMessages());
                return(StatusCode(StatusCodes.Status500InternalServerError, Constants.ErrorMessages.CreateError));
            }
        }
Exemple #26
0
        public async Task <IActionResult> Put(int id, [FromBody] CategoryViewModel categoryViewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var category = _mapper.Map <Category>(categoryViewModel);

                    var validationResult = await _categoryHandler.CanUpdate(id, category);

                    if (validationResult == null)
                    {
                        category.Id = id;
                        var result = await _categoryService.Update(category);

                        if (result.ValidationResults.Count == 0)
                        {
                            return(Ok("Category modified successfully!"));
                        }

                        ModelState.AddModelErrors(result.ValidationResults);
                    }

                    ModelState.AddModelError(validationResult);
                }
            }
            catch (Exception ex)
            {
                var exceptionMessage = await Helpers.GetErrors(ex);

                ModelState.AddModelError(new ValidationResult(exceptionMessage));
            }

            return(BadRequest(ModelState.GetErrors()));
        }
Exemple #27
0
 public ActionResult ChangePassword(ChangePasswordFormModel form)
 {
     if (ModelState.IsValid)
     {
         EFMVCUser efmvcUser = HttpContext.User.GetEFMVCUser();
         var       command   = new ChangePasswordCommand
         {
             UserId      = efmvcUser.UserId,
             OldPassword = form.OldPassword,
             NewPassword = form.NewPassword
         };
         IEnumerable <ValidationResult> errors = commandBus.Validate(command);
         ModelState.AddModelErrors(errors);
         if (ModelState.IsValid)
         {
             var result = commandBus.Submit(command);
             if (result.Success)
             {
                 return(RedirectToAction("ChangePasswordSuccess"));
             }
             else
             {
                 ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
             }
         }
     }
     // If we got this far, something failed, redisplay form
     return(View(form));
 }
Exemple #28
0
        public IHttpActionResult Register(RegisterRequestModel requestModel)
        {
            if (ModelState.IsValid)
            {
                UsernameCommand uniqueUsernameCommand      = new UsernameCommand(requestModel.Username);
                IEnumerable <ValidationResult> validations = commandDispatcher.Validate(uniqueUsernameCommand);

                ModelState.AddModelErrors(validations);

                if (ModelState.IsValid)
                {
                    AccountCommand accountCommand = new AccountCommand(requestModel.Username, requestModel.Password);
                    Account        account        = commandDispatcher.Dispatch <AccountCommand, Account>(accountCommand);

                    AuthCommand    authCommand    = new AuthCommand(account.Id, false);
                    Authentication authentication = commandDispatcher.Dispatch <AuthCommand, Authentication>(authCommand);

                    AccountResponseModel responseModel = Mapper
                                                         .Map <AccountResponseModel>(authentication)
                                                         .Map(account);

                    return(Ok(responseModel));
                }
            }

            return(BadRequest(ModelState));
        }
Exemple #29
0
        public ActionResult Edit(GoalFormModel editGoal)
        {
            Goal goalToEdit = Mapper.Map <GoalFormModel, Goal>(editGoal);
            var  errors     = goalService.CanAddGoal(goalToEdit, updateService);

            ModelState.AddModelErrors(errors);
            if (ModelState.IsValid)
            {
                goalService.EditGoal(goalToEdit);
                return(RedirectToAction("Index", new { id = editGoal.GoalId }));
            }
            else
            {
                var metrics    = metricService.GetMetrics();
                var goalstatus = goalStatusService.GetGoalStatus();
                var goal       = goalService.GetGoal(editGoal.GoalId);
                if (goal.Metric != null)
                {
                    editGoal.Metrics = metrics.ToSelectListItems(goal.Metric.MetricId);
                }
                else
                {
                    editGoal.Metrics = metrics.ToSelectListItems(-1);
                }

                return(View(editGoal));
            }
        }
Exemple #30
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.FindByNameAsync(model.Email).ConfigureAwait(false);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }

            var result = await _userManager.ResetPasswordAsync(user.Id, model.Code, model.Password).ConfigureAwait(false);

            if (result.Succeeded)
            {
                Logger.Log.Info($"Пользователь {user.Email} сбросил пароль");
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }

            ModelState.AddModelErrors(result.Errors.Select(x => new ValidationResult(x)));
            return(View());
        }