Exemplo n.º 1
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Profile"));
            }

            IdentityRole role = Roles.FirstOrDefault(r => r.Name == model.Role);

            if (ModelState.IsValid && role != null)
            {
                model.Username = model.Email.ToLower().Split("@")[0];
                UserModel user   = _mapper.Map <UserModel>(model);
                var       result = await ManageUser.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await ManageUser.AddToRoleAsync(user, role.Name);

                    var token = await ManageUser.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { token = token, email = user.Email });

                    var         url         = "https://" + Request.Host + callbackUrl;
                    MailRequest mailrequest = new MailRequest {
                        ToEmail = model.Email,
                        Subject = "Email Verification Token",
                        Body    = "<div style='text-align:center'> <h1 style='margin:20px;'> Thanks for signing up, " + model.FirstName + " </h1> <a href='" + url + "' > Verify Email </a> </div>"
                    };

                    var confirm = await SendToken(mailrequest);

                    if (!confirm)
                    {
                        // Failed to send verification token
                        await ConfirmEmail(token, model.Email);
                    }

                    return(RedirectToAction("Login", "Account"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.TryAddModelError(error.Code, error.Description);
                }
            }

            return(View(model));
        }