示例#1
0
        public async Task <IActionResult> Register(RegisterViewModel model, Uri returnUrl = null)
        {
            ViewData["Title"] = "Register";
            // ViewData["Menu"] = "navAccount";
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName  = model?.UserName,
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Email     = model.Email
                };
                var result = await UserManagerAgent.CreateAsync(user, model.Password).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    if (!await RoleManagerAgent.RoleExistsAsync(_appSettings.SecRole.Level1).ConfigureAwait(false))
                    {
                        ApplicationRole role = new ApplicationRole
                        {
                            Name        = _appSettings.SecRole.Level1,
                            Description = "Perform basic operations."
                        };
                        IdentityResult roleResult = await RoleManagerAgent.CreateAsync(role).ConfigureAwait(false);

                        if (!roleResult.Succeeded)
                        {
                            ModelState.AddModelError(string.Empty, "Error while creating role!");
                            return(View(model));
                        }
                    }
                    UserManagerAgent.AddToRoleAsync(user, _appSettings.SecRole.Level1).Wait();

                    // send confirmation email
                    string confirmationToken = await UserManagerAgent.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);

                    string confirmationLink = Url.Action("ConfirmEmail", "Account",
                                                         new { userid = user.Id, token = confirmationToken }, protocol: HttpContext.Request.Scheme);

                    string[] emailAddresses = { _appSettings.SMTP.AdminEmail, user.Email };
                    var      emailName      = string.IsNullOrWhiteSpace(user.FirstName) ? user.UserName : $"{user.FirstName} {user.LastName}".Trim();
                    await _emailAgent.SendEmailAsync(_appSettings.SMTP.FromEmail, _appSettings.SMTP.FromEmail, emailAddresses,
                                                     "Welcome to Winemakers Software - Please verify your email.", CreateVerifyEmail(confirmationLink, emailName), true, null).ConfigureAwait(false);

                    // redirect to limbo page
                    return(RedirectToAction("RegisterLimbo", "Account"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }