Exemplo n.º 1
0
        public async Task <ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = userViewModel.Email, Email = userViewModel.Email
                };
                var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);

                //Add User to the selected Roles
                if (adminresult.Succeeded)
                {
                    if (selectedRoles != null)
                    {
                        var result = await _userManager.AddToRolesAsync(user.Id, selectedRoles);

                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await _roleManager.GetAllCustomRolesAsync(), "Name", "Name");
                            return(View());
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(await _roleManager.GetAllCustomRolesAsync(), "Name", "Name");
                    return(View());
                }
                return(RedirectToAction("Index"));
            }
            ViewBag.RoleId = new SelectList(await _roleManager.GetAllCustomRolesAsync(), "Name", "Name");
            return(View());
        }
Exemplo n.º 2
0
        public virtual async Task <ActionResult> Add(UserDataEntry model)
        {
            if (Session["Captcha"] == null || Session["Captcha"].ToString() != model.Captcha)
            {
                ModelState.AddModelError("Captcha", "مجموع اشتباه است");
            }

            if (!ModelState.IsValid)
            {
                return(MessageBox.Show(ModelState.GetErrors(), MessageType.Warning));
            }

            var user = AutoMapperConfig.Configuration.Mapper.Map <ApplicationUser>(model);

            var adminresult = await _userManager.CreateAsync(user, model.Password);

            if (adminresult.Succeeded)
            {
                var result = await _userManager.AddToRolesAsync(user.Id, "Admin");

                if (!result.Succeeded)
                {
                    return(MessageBox.Show(result.Errors.First(), MessageType.Warning));
                }
            }
            else
            {
                return(MessageBox.Show(adminresult.Errors.First(), MessageType.Warning));
            }

            return(MessageBox.Show("اطلاعات با موفقیت ثبت شد", MessageType.Success));
        }
        public async Task <IActionResult> Edit(UsersViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var User = await userManager.FindByIdAsync(viewModel.Id);

                if (User == null)
                {
                    return(NotFound());
                }
                else
                {
                    IdentityResult Result;
                    var            RecentRoles = await userManager.GetRolesAsync(User);

                    var DeleteRoles = RecentRoles.Except(viewModel.Roles);
                    var AddRoles    = viewModel.Roles.Except(RecentRoles);

                    Result = await userManager.RemoveFromRolesAsync(User, DeleteRoles);

                    if (Result.Succeeded)
                    {
                        Result = await userManager.AddToRolesAsync(User, AddRoles);

                        if (Result.Succeeded)
                        {
                            User.FirstName   = viewModel.FirstName;
                            User.LastName    = viewModel.LastName;
                            User.Email       = viewModel.Email;
                            User.PhoneNumber = viewModel.PhoneNumber;
                            User.UserName    = viewModel.UserName;
                            User.BirthDate   = convertDate.ShamsiToMiladi(viewModel.PersianBirthDate);

                            Result = await userManager.UpdateAsync(User);

                            if (Result.Succeeded)
                            {
                                ViewBag.AlertSuccess = "ذخیره تغییرات با موفقیت انجام شد.";
                            }
                        }
                    }

                    if (Result != null)
                    {
                        foreach (var item in Result.Errors)
                        {
                            ModelState.AddModelError("", item.Description);
                        }
                    }
                }
            }

            ViewBag.AllRoles = roleManager.GetAllRoles();
            return(View(viewModel));
        }
Exemplo n.º 4
0
        public async Task <Guid> Handle(CreateNewUser message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var user = new ApplicationUser
            {
                UserName       = message.Email,
                Email          = message.Email,
                OrganizationId = message.OrganizationId
            };

            var userId = Guid.NewGuid();
            var result = await _userManager.CreateAsync(user, userId.ToString());

            if (!result.Succeeded)
            {
                throw new BusinessRuleException(result.Errors);
            }

            var roles = new List <string> {
                Roles.Therapist
            };

            if (message.IsAdministrator)
            {
                roles.Add(Roles.OrganizationAdministrator);
            }

            await _userManager.AddToRolesAsync(user.Id, roles.ToArray());

            await _session.SaveChangesAsync();

            var domainEvent = _mapper.Map <UserCreated>(message);

            _bus.PublishDomainEvent(domainEvent);

            return(userId);
        }
Exemplo n.º 5
0
        public virtual async Task <ActionResult> Register(RegisterViewModel userViewModel, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(userViewModel));
            }


            var user = new ApplicationUser
            {
                UserName       = userViewModel.UserName,
                Email          = userViewModel.Email,
                EmailConfirmed = true
            };

            var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);

            if (adminresult.Succeeded)
            {
                var result = await _userManager.AddToRolesAsync(user.Id, "User");

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View());
                }
            }
            else
            {
                ModelState.AddModelError("", adminresult.Errors.First());

                return(View());
            }

            await _signInManager.PasswordSignInAsync(userViewModel.UserName, userViewModel.Password, false, shouldLockout : false);


            return(redirectToLocal(returnUrl));
        }
Exemplo n.º 6
0
        public virtual async Task <ActionResult> Create(WebMarket.ViewModel.Admin.User.UserDataEntry model, params string[] selectedRoles)
        {
            if (selectedRoles != null)
            {
                if (ModelState.IsValid)
                {
                    model.BirthDate = DateTime.Now;
                    var user = AutoMapperConfig.Configuration.Mapper.Map <ApplicationUser>(model);

                    var adminresult = await _userService.CreateAsync(user, model.Password);

                    //Add User to the selected Roles
                    if (adminresult.Succeeded)
                    {
                        await _userService.AddToRolesAsync(user.Id, selectedRoles);

                        return(MessageBox.Show("اطلاعات با موفقیت ثبت شد", MessageType.Success));
                    }
                }
                return(MessageBox.Show(ModelState.GetErrors(), MessageType.Warning));
            }
            return(MessageBox.Show("ابتدا نقش کاربر را مشخص کنید", MessageType.Warning));
        }
Exemplo n.º 7
0
        public virtual async Task <ActionResult> Register(RegisterViewModel userViewModel,
                                                          params string[] SelectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName        = userViewModel.Email,
                    Email           = userViewModel.Email,
                    RegisterDate    = DateTime.Now,
                    EmailConfirmed  = true,
                    DateDisableUser = DateTime.Parse("1/1/1")
                };

                var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);

                //Add User to the selected Roles
                if (adminresult.Succeeded)
                {
                    if (SelectedRoles != null)
                    {
                        var result = await _userManager.AddToRolesAsync(user.Id, SelectedRoles);

                        if (!result.Succeeded)
                        {
                            return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel {
                                Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning
                            }));
                        }
                        else
                        {
                            return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel {
                                Alert = AlertOperation.SurveyOperation(StatusOperation.SuccessCreateUser), Status = AlertMode.success
                            }));
                        }
                    }
                    else
                    {
                        var result = await _userManager.AddToRoleAsync(user.Id, "public");

                        if (!result.Succeeded)
                        {
                            return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel {
                                Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning
                            }));
                        }
                        else
                        {
                            return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel {
                                Alert = AlertOperation.SurveyOperation(StatusOperation.SuccessCreateUser), Status = AlertMode.success
                            }));
                        }
                    }
                }
                else
                {
                    // ViewBag.RoleId = new SelectList(_roleManager.Roles, "Name", "Name");
                    return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel {
                        Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning
                    }));
                }
            }
            else
            {
                //ViewBag.RoleId = new SelectList(_roleManager.Roles, "Name", "Name");
                return(PartialView(MVC.admin.Shared.Views._alert, new AlertViewModel {
                    Alert = AlertOperation.SurveyOperation(StatusOperation.Invalid), Status = AlertMode.warning
                }));
            }
        }
        public virtual async Task <ActionResult> Add(RegisterViewModel userViewModel, HttpPostedFileBase userImage)
        {
            if (userViewModel.Id.HasValue)
            {
                ModelState.Remove("Password");
                ModelState.Remove("ConfirmPassword");
            }

            if (!ModelState.IsValid)
            {
                return(View(userViewModel));
            }

            if (!userViewModel.Id.HasValue)
            {
                var user = new ApplicationUser
                {
                    UserName       = userViewModel.UserName,
                    Email          = userViewModel.Email,
                    EmailConfirmed = true
                };

                var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);

                if (adminresult.Succeeded)
                {
                    var result = await _userManager.AddToRolesAsync(user.Id, "Admin");

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        return(View());
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());

                    return(View());
                }

                TempData["message"] = "کاربر جدید با موفقیت در سیستم ثبت شد";
            }
            else
            {
                var user = await _userManager.FindByIdAsync(userViewModel.Id.Value);

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

                user.UserName = userViewModel.UserName;
                user.Email    = userViewModel.Email;

                await _unitOfWork.SaveAllChangesAsync();

                TempData["message"] = "کاربر مورد نظر با موفقیت ویرایش شد";
            }

            if (userImage != null)
            {
                var img = new WebImage(userImage.InputStream);
                img.Resize(161, 161, true, false).Crop(1, 1);

                img.Save(Server.MapPath("~/UploadedFiles/Avatars/" + userViewModel.UserName + ".png"));
            }


            return(RedirectToAction(MVC.User.Admin.ActionNames.Index));
        }
Exemplo n.º 9
0
        public virtual async Task <ActionResult> Register(RegisterViewModel model)
        {
            #region Validation
            var allRoles = await _roleManager.GetAllRolesAsync();

            var isDefaultForRegister = allRoles.FirstOrDefault(q => q.IsDefaultForRegister);

            if (_userManager.CheckEmailExist(model.Email, null))
            {
                this.AddErrors("Email", "این ایمیل قبلا در سیستم ثبت شده است");
            }

            if (_userManager.CheckUserNameExist(model.UserName, null))
            {
                this.AddErrors("UserName", "این نام کاربری قبلا در سیستم ثبت شده است");
            }

            if (_userManager.CheckNameForShowExist(model.NameForShow, null))
            {
                this.AddErrors("NameForShow", "این نام نمایشی قبلا در سیستم ثبت شده است");
            }

            if (!model.Password.IsSafePasword())
            {
                this.AddErrors("Password", "این کلمه عبور به راحتی قابل تشخیص است");
            }

            if (!model.Password.IsSafePasword())
            {
                this.AddErrors("Password", "این کلمه عبور به راحتی قابل تشخیص است");
            }

            if (isDefaultForRegister == null)
            {
                this.AddErrors("Role", "نقشی برای کاربران ثبت نام شده تعیین نشده است");
            }


            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            #endregion

            model.RegistrationIp = Network.GetClientIp();
            model.RegisterDate   = DateTime.Now;
            var userId = await _userManager.CreateAsync(model);

            await _userManager.AddToRolesAsync(userId, isDefaultForRegister.Name);

            //TODO
            // Send Confirmation Email
            await _emailService.SendEmailAsync(new IdentityMessage
            {
                Body =
                    "<table style=\"background-color: #f6f6f6; width: 100%; font-family: calibri; font-size: 16px; direction: rtl; line-height: 18pt; text-align: right;\"> " +
                    "<tbody> <tr> <td style=\"display: block !important; max-width: 600px !important; margin: 0 auto !important; clear: both !important;\" width=\"600\"> " +
                    "<div style=\"max-width: 600px; margin: 0 auto; display: block; padding: 20px;\"> " +
                    "<table style=\"background: #fff; border: 1px solid #e9e9e9; border-radius: 3px;\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"> " +
                    "<tbody> <tr> <td style=\"padding: 20px;\"> <table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"> " +
                    "<tbody> <tr> <td style=\"padding: 0 0 20px; text-align: center\"> <img src=\"http://aminmohamadi.ir/content/images/logo.png\" alt=\"\" /> </td> </tr> <tr> " +
                    "<td style=\"padding: 0 0 20px;\"> " + model.NameForShow +
                    " عزیز </td> </tr> <tr> <td style=\"padding: 0 0 20px;\">" +
                    " با عرض سلام و احترام <br />" +
                    " از این پس میتوانید با استفاده از نام کاربری و رمز عبور زیر جهت ورود به حساب کاربری خود وارد شوید </td> </tr> <tr> " +
                    "<td style=\"padding: 0 0 20px;\"> نام کاربری: " + model.UserName + " <br /> کلمه عبور: " + model.Password +
                    " </td> </tr> <tr> " +
                    "<td style=\"padding: 0 0 20px;\"> برای تغییر کلمه عبور باید کافیست به قسمت حساب کاربری سایت مراجعه کنید. </td> </tr> <tr> " +
                    "<td style=\"padding: 20px; text-align: center\"> <a href=\"http://aminmohamadi.ir\" style=\"text-decoration: none; color: #FFF; font-size: 14px; background-color:" +
                    " #348eda;border: solid #348eda; border-width: 10px 20px; line-height: 2; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; text-transform: capitalize;\">" +
                    "صفحه اصلی سایت</a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> </td> <td></td> </tr> </tbody></table>",

                Destination = model.Email,
                Subject     = "ایجاد حساب کاربری جدید - AminMohamadi.ir"
            });



            ViewBag.Message = "حساب کاربری شما با موفقیت ایجاد شد. ایمیلی حاوی نام کاربری و رمز عبور شما برای شما فرستاده شد. " +
                              "برای مشاهده اطلاعات کاربری به ایمیل خود مراجعه کنید.";

            return(View("RegisterSuccessfully"));
        }
Exemplo n.º 10
0
        public async Task <ApplicationUser> CreateUser(ApplicationUser user, string url, IEnumerable <string> roles)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (!String.IsNullOrWhiteSpace(user.Id))
            {
                new ArgumentException($"Cannot specify {nameof(user.Id)} when creating a user", nameof(user));
            }

            try
            {
                var existingUser = await UsrManager.FindByNameAsync(user.UserName);

                if (existingUser != null)
                {
                    var errorMessage = $"The username '{user.UserName}' is already taken";
                    throw new AccessControlChangeException(errorMessage, new List <string>()
                    {
                        errorMessage
                    });
                }

                user.Id = Guid.NewGuid().ToString();
                user.LockoutEndDateUtc = null;

                var createUserResult = await UsrManager.CreateAsync(user);

                if (!createUserResult.Succeeded)
                {
                    throw new AccessControlChangeException("Unable to create user", createUserResult.Errors);
                }

                if (roles != null && roles.Count() > 0)
                {
                    var roleResult = await UsrManager.AddToRolesAsync(user.Id, roles.ToArray());

                    if (!roleResult.Succeeded)
                    {
                        throw new AccessControlChangeException("Unable to assign roles", roleResult.Errors);
                    }
                }

                await SendResetPassword(user.Id, url);

                return(user);
            }
            catch (AccessControlChangeException e)
            {
                // This will dump the errors across lines in the log.
                var es = String.Join("\n", e.Errors);
                LogHelper.Exception(Logger, $"{nameof(CreateUser)} errors from identity:\n{es}", e);
                throw;
            }
            catch (Exception e)
            {
                LogHelper.Exception(Logger, $"{nameof(CreateUser)} failed", e);
                throw;
            }
        }