예제 #1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #2
0
        //[ValidateDNTCaptcha(CaptchaGeneratorLanguage = DNTCaptcha.Core.Providers.Language.Persian)]
        public async Task <IActionResult> Index(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User();

                Mapper.Map(model, user);

                if (model.UserType == UserTypeSSOT.Person)
                {
                    user.UserName = model.NationalCode;
                }
                else
                {
                    user.UserName = model.Email;
                }

                user.EmailConfirmed = true;

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

                if (result.Succeeded)
                {
                    _logger.LogInformation($"کاربر {user.UserName} از طریق سایت ثبت نام کرده است.");

                    var ChangePhoneNumberToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);

                    _smsService.sendMessage(model.PhoneNumber, "به سامانه کارآموزی خوش آمدید.");
                    //var smsResult = await _smsSender.SendSmsAsync(model.PhoneNumber, $"برای تکمیل ثبت نام خود کد : {ChangePhoneNumberToken} را وارد نمایید.");

                    if (model.UserType == UserTypeSSOT.Person)
                    {
                        await _userManager.AddToRoleAsync(user, ConstantRoles.UserBase);
                    }

                    if (model.CreateByAdmin.HasValue && model.CreateByAdmin == true)
                    {
                        return(Redirect("~/Identity/UsersManager/Index"));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, false, null);

                        return(Redirect("/"));
                    }
                }
                List <string> errors = new List <string>();

                foreach (var error in result.Errors)
                {
                    //ModelState.AddModelError(string.Empty, error.Description);
                    errors.Add(error.Description);
                }

                TempData.AddResult(ServiceResult.Error(string.Join("<br/>", errors)));
            }

            ViewBag.UserType = model.UserType;
            return(View(model));
        }
        public async Task <ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = userViewModel.UserName, 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(Json(new { success = true }));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(await _roleManager.GetAllCustomRolesAsync(), "Name", "Name");
                    return(Json(new { success = true }));
                }
                return(PartialView(viewName: "Create", model: userViewModel));
            }
            ViewBag.RoleId = new SelectList(await _roleManager.GetAllCustomRolesAsync(), "Name", "Name");
            return(PartialView(viewName: "Create", model: userViewModel));
        }
예제 #4
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.UserName
                };

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

                if (result.Succeeded)
                {
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account",
                    //    new { userId = user.Id, code }, protocol: Request.Url.Scheme);
                    //await _userManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                    //ViewBag.Link = callbackUrl;
                    return(View("RegisterConfirmation"));
                }
                addErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public virtual async Task <ApiResult <User> > Create(UserDto userDto, CancellationToken cancellationToken)
        {
            _logger.LogError("متد Create فراخوانی شد");
            HttpContext.RiseError(new Exception("متد Create فراخوانی شد"));

            //var exists = await userRepository.TableNoTracking.AnyAsync(p => p.UserName == userDto.UserName);
            //if (exists)
            //    return BadRequest("نام کاربری تکراری است");

            var user = new User
            {
                Birthday  = DateTime.Now,
                FirstName = userDto.FullName,
                LastName  = userDto.FullName,
                Gender    = userDto.Gender,
                UserName  = userDto.UserName,
                Email     = userDto.Email
            };
            var result = await _userManager.CreateAsync(user, userDto.Password);

            if (!result.Succeeded)
            {
                return(BadRequest());
            }

            //await userRepository.AddAsync(user, userDto.Password, cancellationToken);
            return(user);
        }
예제 #6
0
        public async Task <ActionResult> Create(CreateUserVM createUserVM)
        {
            if (!ModelState.IsValid)
            {
                return(View(createUserVM));
            }

            AppUser user   = Mapper.Map <CreateUserVM, AppUser>(createUserVM);
            var     result = await _userManager.CreateAsync(user, createUserVM.Password);

            if (!result.Succeeded)
            {
                TempData["status"]  = "alert-danger";
                TempData["message"] = string.Format("Não foi possível criar o usuário - erro no acesso ao banco de dados.");
                return(View(createUserVM));
            }

            _logger.Log(String.Format("USERS - Novo usuário criado - Email: {0}", user.Email));

            TempData["status"]  = "alert-success";
            TempData["message"] = string.Format("Usuário criado com sucesso. E-mail: <strong>{0}</strong>", user.Email);

            string redirectionTarget = Request.Form["save-and-back"] != null ? "Index" : "Create";

            return(RedirectToAction(redirectionTarget));
        }
        public async Task <IActionResult> CreateUser([FromBody] RegisterViewModel model)
        {
            User user = new User
            {
                UserName  = model.UserName,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName
            };
            IdentityResult result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                _logger.LogInformation(3, $"{user.UserName} created a new account with password.");

                if (_settings.EnableEmailConfirmation)
                {
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    await _emailSender.SendEmailAsync(
                        email : user.Email,
                        subject : "Please confirm your email",
                        message : code);

                    return(Ok());
                }
            }
            return(BadRequest(error: result.DumpErrors(useHtmlNewLine: false)));
        }
예제 #8
0
        public async Task <ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    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.AddUserToRolesAsync(user.Id, selectedRoles);

                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await _roleManager.GetRolesAsync(), "Name", "Name");
                            return(View());
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(_roleManager.GetRoles(), "Name", "Name");
                    return(View());
                }
                return(RedirectToAction("Index"));
            }
            ViewBag.RoleId = new SelectList(_roleManager.GetRoles(), "Name", "Name");
            return(View());
        }
예제 #9
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));
        }
        /// <inheritdoc/>
        public async Task <SuccessOrFailureWithErrors> CreateUserAsync(ApplicationUser user, string password)
        {
            var result = await userManager.CreateAsync(user, password);

            return(result.Succeeded ?
                   SuccessOrFailureWithErrors.Success :
                   new SuccessOrFailureWithErrors(result.Errors.Select(e => e.Description).ToList()));
        }
예제 #11
0
        public async Task <IHttpActionResult> PostAdminRegister(RegisterFullViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ApplicationUser user = Mapper.Map <RegisterFullViewModel, ApplicationUser>(model);

            if (!await _userManager.IsValid(user))
            {
                var resul = new IdentityResult(_userManager.Errors.Select(x => x.Value).AsEnumerable());
                return(GetErrorResult(resul));
            }

            try
            {
                var result = await _userManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }

            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            catch (Exception ex)
            {
                throw;
            }


            return(Ok());
        }
예제 #12
0
        public async Task <IdentityResult> Register()
        {
            var res = await _applicationUserManager.CreateAsync(new User {
                UserName  = _user.Phone,
                FirstName = _user.FirstName,
                LastName  = _user.LastName,
                Email     = _user.Email,
                IsActive  = true
            }, _user.Password);

            return(res);
        }
예제 #13
0
        public async Task <IHttpActionResult> Registration([FromBody] RegistrationModel model)
        {
            var roles = new List <string>();

            roles.Add(model.Role);
            var identityUser = new Account {
                UserName = model.UserName, Roles = roles
            };

            var result = await _userManager.CreateAsync(identityUser, model.Password);

            return(Ok());
        }
예제 #14
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model,
                                                                   string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _authenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
예제 #15
0
파일: FrmUsers.cs 프로젝트: windygu/ERP
        private async Task <IdentityResult> CreateNewUser()
        {
            var newUser = new ApplicationUser()
            {
                UserName    = txtUserName.Text.Trim(),
                Email       = txtMail.Text.Trim(),
                PhoneNumber = txtPhone.Text.Trim(),
                IsActive    = true,
            };


            return(await _userManager.CreateAsync(newUser, txtPass.Text.Trim()));
        }
        private async Task <ApplicationUser> CreateUser(FacebookUserCredentialsResponse facebookResponse)
        {
            ApplicationUser user = new ApplicationUser {
                UserName = facebookResponse.email, Email = facebookResponse.email
            };
            IdentityResult result = await applicationUserManager.CreateAsync(user);

            if (result.Succeeded)
            {
                IdentityResult loginInfoResult = await applicationUserManager.AddLoginAsync(user, new UserLoginInfo("Facebook", facebookResponse.id, facebookResponse.name));

                if (!loginInfoResult.Succeeded)
                {
                    throw new Exception("Creating new user failed");
                }
            }
            else
            {
                throw new Exception("Creating new user failed");
            }

            return(user);
        }
예제 #17
0
        public async Task <IActionResult> Index(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    UserName  = model.Username,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation(3, $"{user.UserName} created a new account with password.");

                    if (_siteOptions.Value.EnableEmailConfirmation)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        //ControllerExtensions.ShortControllerName<RegisterController>(), //todo: use everywhere .................

                        await _emailSender.SendEmailAsync(
                            email : user.Email,
                            subject : "لطفا اکانت خود را تائید کنید",
                            viewNameOrPath : "~/Areas/Identity/Views/EmailTemplates/_RegisterEmailConfirmation.cshtml",
                            model : new RegisterEmailConfirmationViewModel
                        {
                            User = user,
                            EmailConfirmationToken = code,
                            EmailSignature         = _siteOptions.Value.Smtp.FromName,
                            MessageDateTime        = DateTime.UtcNow.ToLongPersianDateTimeString()
                        });

                        return(RedirectToAction(nameof(ConfirmYourEmail)));
                    }
                    return(RedirectToAction(nameof(ConfirmedRegisteration)));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return(View(model));
        }
예제 #18
0
        public async Task <IdentityResult> RegisterAsync(RegisterBaseViewModel ViewModel)
        {
            DateTime BirthDateMiladi = _convertDate.ConvertShamsiToMiladi(ViewModel.BirthDate);
            var      user            = new ApplicationUser {
                UserName = ViewModel.UserName, Email = ViewModel.Email, PhoneNumber = ViewModel.PhoneNumber, RegisterDate = DateTime.Now, IsActive = true, BirthDate = BirthDateMiladi, EmailConfirmed = ViewModel.EmailConfirmed, PhoneNumberConfirmed = ViewModel.PhoneNumberConfirmed
            };
            IdentityResult result = await _userManager.CreateAsync(user, ViewModel.Password);

            if (result.Succeeded)
            {
                return(await AddRoleToUser("کاربر", user));
            }
            else
            {
                return(result);
            }
        }
예제 #19
0
        public async Task <object> RegisterAsync(User user)
        {
            var userRegister = _mapper.Map <AIM.User>(user);

            userRegister.Id = Guid.NewGuid().ToString();

            var result = await _userManager.CreateAsync(userRegister, user.Password);

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(userRegister, false);

                return(GenerateJwtToken(userRegister));
            }

            return(result.Errors);
        }
예제 #20
0
        public async Task <IActionResult> Register(RegisterViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                DateTime BirthDateMiladi = convertDate.ShamsiToMiladi(viewModel.BirthDate);

                var user = new ApplicationUser {
                    UserName = viewModel.UserName, Email = viewModel.Email, PhoneNumber = viewModel.PhoneNumber, RegisterDate = DateTime.Now, IsActive = true, BirthDate = BirthDateMiladi
                };
                IdentityResult result = await userManager.CreateAsync(user, viewModel.Password);

                if (result.Succeeded)
                {
                    var role = await roleManager.FindByNameAsync("کاربر");

                    if (role == null)
                    {
                        await roleManager.CreateAsync(new ApplicationRole("کاربر"));
                    }

                    result = await userManager.AddToRoleAsync(user, "کاربر");

                    await userManager.AddClaimAsync(user, new Claim(ClaimTypes.DateOfBirth, BirthDateMiladi.ToString("MM/dd")));

                    if (result.Succeeded)
                    {
                        var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", values: new { userId = user.Id, code = code }, protocol: Request.Scheme);

                        await emailSender.SendEmailAsync(viewModel.Email, "تایید ایمیل حساب کاربری - سایت میزفا", $"<div dir='rtl' style='font-family:tahoma;font-size:14px'>لطفا با کلیک روی لینک رویه رو ایمیل خود را تایید کنید.  <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>کلیک کنید</a></div>");

                        return(RedirectToAction("Index", "Home", new { id = "ConfirmEmail" }));
                    }
                }

                foreach (var item in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, item.Description);
                }
            }

            return(View());
        }
        public virtual async Task <ActionResult> Register(RegisterVM model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Index", "Home"));
                }
            }
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #22
0
        public async Task <IActionResult> Index(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    UserName  = model.Username,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };

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

                if (result.Succeeded)
                {
                    _logger.LogInformation(3, $"{user.UserName} created a new account with password.");

                    if (_appSettings.Value.EnableEmailConfirmation)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        await _emailSender.SendEmailAsync(
                            email : user.Email,
                            subject : "لطفا اکانت خود را تائید کنید",
                            message : "پیام تست"
                            // viewNameOrPath: "~/Areas/Identity/Views/EmailTemplates/_RegisterEmailConfirmation.cshtml",
                            // model: new RegisterEmailConfirmationViewModel
                            // {
                            //     User = user,
                            //     EmailConfirmationToken = code,
                            //     EmailSignature = _siteOptions.Value.Smtp.FromName,
                            //     MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString()
                            // }
                            );

                        //return RedirectToAction(nameof(ConfirmYourEmail));
                    }
                }
            }

            return(View(model));
        }
        public async Task <ApiResult <string> > Register([FromBody] UsersViewModel viewModel)
        {
            ModelState.Remove("roleId");
            ModelState.Remove("PersianBirthDate");
            ModelState.Remove("PhoneNumber");
            if (ModelState.IsValid)
            {
                AppUser user = new AppUser
                {
                    EmailConfirmed = true,
                    UserName       = viewModel.UserName,
                    FirstName      = viewModel.FirstName,
                    LastName       = viewModel.LastName,
                    PasswordHash   = viewModel.Password,
                    Email          = viewModel.Email,
                    Gender         = viewModel.Gender ?? viewModel.Gender,
                    Notifications  = new List <Notification>
                    {
                        new Notification
                        {
                            EnterEmail    = true,
                            ExitEmail     = true,
                            EnterTelegram = true,
                            ExitTelegram  = true,
                            EnterSms      = false,
                            ExitSms       = false,
                        }
                    }
                };
                IdentityResult identityResult = await _userManager.CreateAsync(user, viewModel.Password);

                if (identityResult.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "کاربر عادی");

                    return(Ok(NotificationMessages.RegisterSuccess));
                }

                return(BadRequest(identityResult.DumpErrors()));
            }

            return(BadRequest(ModelState.GetErrorsModelState()));
        }
예제 #24
0
        // User: Admin/User/Add/id
        public virtual ActionResult Add(User model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            HttpPostedFileBase file = Request.Files["user-avatar"];

            model.AvatarPath  = file.FileName;
            model.Email       = model.Email;
            model.UserName    = model.Email;
            model.CreatedDate = DateTime.Now;
            model.BirthDay    = DateTime.Now;
            model.IP          = Request.UserHostAddress;
            model.IsBaned     = false;

            var path = Path.Combine(Server.MapPath("~/Content/upload/avatar/"), file.FileName);

            file.SaveAs(path);
            var userCreate = _userService.CreateAsync(model, model.Password);

            if (userCreate.Result.Errors.Count() == 0)
            {
                string[] roleIds = Request["CategoryIds[]"].Split(',');
                foreach (var item in roleIds)
                {
                    _userService.AddToRoleAsync(userCreate.Id, _roleService.FindByIdAsync(Convert.ToInt32(item)).Result.Name);
                }
            }

            foreach (var item in userCreate.Result.Errors)
            {
                ModelState.AddModelError(Guid.NewGuid().ToString(), item.ToString());
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            _uow.SaveAllChanges();
            return(RedirectToAction("Index"));
        }
        public async Task <IHttpActionResult> Registration([FromBody] Registration model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var internalEmail = model.Nickname + "@steadywork.pro";
            var defaultAvataR = "https://mailbordpic.blob.core.windows.net/mailbordpic/default.png";
            var identityUser  = new IdentityUser
            {
                UserName = model.Nickname + "@steadywork.pro",
                Email    = model.Email,
                Name     = model.Name,
                Company  = model.Company,
                Image    = defaultAvataR
            };

            var result = await _userManager.CreateAsync(identityUser, model.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(ModelState));
            }

            string galleonHashPassword = BCryptHelper.HashPassword(model.Password, BCryptHelper.GenerateSalt(10));
            bool   matches             = BCryptHelper.CheckPassword(model.Password, galleonHashPassword);

            GalleonRegistrationModel galleonUser = new GalleonRegistrationModel
            {
                Name      = identityUser.Name,
                Email     = identityUser.UserName,
                IsAdmin   = false,
                Password  = galleonHashPassword,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            await _galleonUserStore.CreateAsync(galleonUser);

            return(Ok());
        }
예제 #26
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);
        }
예제 #27
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));
        }
예제 #28
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));
        }
예제 #29
0
        public virtual async Task <ActionResult> Register(RegisterViewModel_ userViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName        = userViewModel.Email,
                    Email           = userViewModel.Email,
                    EmailConfirmed  = true,
                    RegisterDate    = DateTime.Now.Date,
                    DateDisableUser = DateTime.Parse("2001/1/1")
                };

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

                var result = await _userManager.AddToRoleAsync(user.Id, "public");

                if (publicresult.Succeeded && result.Succeeded)
                {
                    return(PartialView(viewName: MVC.admin.Shared.Views._alert, model: new AlertViewModel {
                        Alert = AlertOperation.SurveyOperation(StatusOperation.SuccessCreateUser), Status = AlertMode.success
                    }));
                }
                else
                {
                    return(PartialView(viewName: MVC.admin.Shared.Views._alert, model: new AlertViewModel {
                        Alert = AlertOperation.SurveyOperation(StatusOperation.FailCreateUser), Status = AlertMode.warning
                    }));
                }
            }
            else
            {
                return(PartialView(viewName: MVC.admin.Shared.Views._alert, model: new AlertViewModel {
                    Alert = AlertOperation.SurveyOperation(StatusOperation.InValidCreateUser), Status = AlertMode.warning
                }));
            }
        }
        public async Task <IActionResult> Register(RegisterViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = viewModel.UserName, Email = viewModel.Email, RegisterDateTime = DateTime.Now, IsActive = true, FirstName = "", LastName = ""
                };
                IdentityResult result = await _userManager.CreateAsync(user, viewModel.Password);

                if (result.Succeeded)
                {
                    var role = await _roleManager.FindByNameAsync("کاربر");

                    if (role == null)
                    {
                        await _roleManager.CreateAsync(new Role("کاربر"));
                    }

                    result = await _userManager.AddToRoleAsync(user, "کاربر");

                    if (result.Succeeded)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", values: new { userId = user.Id, code = code }, protocol: Request.Scheme);
                        await _emailSender.SendEmailAsync(viewModel.Email, "تایید حساب کاربری - سایت میزفا", $"<div dir='rtl' style='font-family:tahoma;font-size:14px'>لطفا با کلیک روی لینک رویه رو حساب کاربری خود را فعال کنید.  <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>کلیک کنید</a></div>");

                        TempData["notification"] = $" ایمیل فعال سازی حساب کاربری به {viewModel.Email} ارسال شد. ";
                    }
                }

                ModelState.AddErrorsFromResult(result);
            }

            return(PartialView("_Register"));
        }