Esempio n. 1
0
        public async Task <IActionResult> VerifEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(BadRequest("Something not right with the credentials"));
            }
            var user2Activate = await _userManager.FindByIdAsync(userId);

            if (user2Activate == null)
            {
                return(BadRequest("Expected validation can not be found"));
            }

            var result = await _userManager.ConfirmEmailAsync(user2Activate, code);

            if (result.Succeeded)
            {
                var conf = _confirmResp.ConfirmResponse(true, "Email Verified");
                return(Ok(conf));
            }
            var conffail = _confirmResp.ConfirmResponse(false, "Email Verification failed");

            return(NotFound(conffail));
        }
Esempio n. 2
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(BadRequest(new { message = "userId или code отсутствуют в теле запроса" }));
            }
            var user = await _userManager.FindByIdAsync(userId);

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

            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                return(this.Redirect(_appsettings.Client_URL + "/user/login"));
            }
            else
            {
                return(BadRequest());
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':");
            }

            return(Page());
        }
        public async Task <IActionResult> ConfirmEmail(string userId, string token)
        {
            if (userId == null || token == null)
            {
                TempData["message"] = "Geçersiz token.";
                return(View());
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user != null)
            {
                var result = await _userManager.ConfirmEmailAsync(user, token);

                if (result.Succeeded)
                {
                    TempData["message"] = "Hesabınız onaylandı";
                    return(View());
                }
            }

            TempData["message"] = "Hesabınız onaylanmadı.";
            return(View());
        }
        public async Task <IActionResult> ConfirmEmail(string userName, string code)
        {
            if (userName == null || code == null)
            {
                return(NotFound());
            }
            var user = await _userManager.FindByNameAsync(userName);

            if (user == null)
            {
                return(NotFound());
            }
            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                TempData["Response"] = "Email has been confirmed";
                return(RedirectToAction("Login", "Account"));
            }
            else
            {
                return(NotFound());
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> CreateUser(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new CustomUser
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    R        = 1.5,
                    P        = 1000,
                    C        = 678,
                    A        = 2000,
                    K0       = 0.65,
                    K1       = 1.25,
                    K2       = 1.85,
                    K3       = 2.45,
                    Func     = "-2*x + 4*x^2/3 - 7"
                };

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

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

                    await _userManager.ConfirmEmailAsync(user, token);

                    return(RedirectToAction("Index", "Home"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return(View(model));
        }
        public async Task <IActionResult> ConfirmEmail(long userId, string code)
        {
            if (userId == 0 || code == null)
            {
                //return RedirectToAction(nameof(HomeController.Index), "Home");\
                return(BadRequest("Failed to confirm email!"));
            }
            var user = await _userManager.FindByIdAsync(userId.ToString());

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{userId}'.");
            }
            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                return(Ok("ConfirmEmail"));
            }
            else
            {
                return(BadRequest("Failed to confirm email!"));
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (userId == null || code == null)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(HomeController.Index), "Home"));
            }
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{userId}'.");
            }
            var result = await _userManager.ConfirmEmailAsync(user, code);

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(result.Succeeded ? "ConfirmEmail" : "Error"));
        }
Esempio n. 9
0
        //confirm mail
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToAction("Login"));
            }
            //url coduna tıklandı gelen parametreye göre userID si alındı

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                throw new ApplicationException("Unable to find the user");
            }
            //user ıd olunca code ve emaile göre confirm edildi
            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                //başarılı mesajı verdirttik
                return(View("ConfirmEmail"));
            }
            return(RedirectToAction("Index", "Student"));
        }
Esempio n. 10
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            try
            {
                if (userId == null || code == null)
                {
                    return(RedirectToAction(nameof(HomeController.Index), "Home"));
                }
                var user = await _userManager.FindByIdAsync(userId);

                if (user == null)
                {
                    throw new ApplicationException($"Unable to load user with ID '{userId}'.");
                }
                var result = await _userManager.ConfirmEmailAsync(user, code);

                return(View(result.Succeeded ? "ConfirmEmail" : "Error"));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong: {ex}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Esempio n. 11
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':");
            }
            await _signInManager.SignInAsync(user, isPersistent : false);

            return(View());
        }
        public async Task <IActionResult> SetPassword(SetPasswordModel setPasswordModel)
        {
            if (setPasswordModel.UserId == null || setPasswordModel.EmailConfirmationCode == null || setPasswordModel.PasswordCode == null)
            {
                return(RedirectToPage("Home", "Index"));
            }

            var user = await _userManager.FindByIdAsync(setPasswordModel.UserId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{setPasswordModel.UserId}'."));
            }

            setPasswordModel.PasswordCode          = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(setPasswordModel.PasswordCode));
            setPasswordModel.EmailConfirmationCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(setPasswordModel.EmailConfirmationCode));
            var emailResult = await _userManager.ConfirmEmailAsync(user, setPasswordModel.EmailConfirmationCode);

            var resetPasswordResult = await _userManager.ResetPasswordAsync(user, setPasswordModel.PasswordCode, setPasswordModel.Password);

            await _userManager.SetUserNameAsync(user, setPasswordModel.Username);

            return(RedirectToAction("Login"));
        }
Esempio n. 13
0
        public async void CreateRestaurantUser(UserManager <IdentityUser> userManager)
        {
            const string restaurantEmail = "*****@*****.**";
            const string password        = "******";

            if (userManager.FindByNameAsync(restaurantEmail).Result == null)
            {
                var user = new IdentityUser
                {
                    UserName = restaurantEmail,
                    Email    = restaurantEmail
                };
                IdentityResult result = userManager.CreateAsync
                                            (user, password).Result;
                if (result.Succeeded)
                {
                    var claim = new Claim("Restaurant", "Yes");
                    userManager.AddClaimAsync(user, claim).Wait();
                    string token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    userManager.ConfirmEmailAsync(user, token).Wait();
                }
            }
        }
Esempio n. 14
0
        public async Task <ActionResult> ConfirmEmail(string userId = "", string token = "")
        {
            if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(token))
            {
                AddError("ID de usuário e código são obrigatórios");
                return(CustomResponse());
            }

            var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id.Equals(userId));

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

            IdentityResult result = await _userManager.ConfirmEmailAsync(user, token);

            if (result.Succeeded)
            {
                var userReturn = new User
                {
                    Id       = user.Id,
                    UserName = user.UserName,
                    Email    = user.Email
                };

                return(Ok(userReturn));
            }

            foreach (var error in result.Errors)
            {
                AddError(error.Description);
            }

            return(CustomResponse());
        }
Esempio n. 15
0
        public async Task <IActionResult> ConfirmEmail(string userId, string token)
        {
            if (userId != null && token != null)
            {
                var user = await userManager.FindByIdAsync(userId);

                if (user != null)
                {
                    var result = await userManager.ConfirmEmailAsync(user, token);

                    if (result.Succeeded)
                    {
                        return(View());
                    }

                    ViewBag.ErrorTitle   = $"Email cannot be confirmed";
                    ViewBag.ErrorMessage = "Please contact support on [email protected]";

                    return(View("~/Views/Error/Error.cshtml"));
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 16
0
        public async Task <UserManagerResponse> ConfirmEmailAsync(string userId, string token)
        {
            var user = await _userManger.FindByIdAsync(userId);

            if (user == null)
            {
                return new UserManagerResponse
                       {
                           IsSuccess = false,
                           Message   = "User not found"
                       }
            }
            ;

            var    decodedToken = WebEncoders.Base64UrlDecode(token);
            string normalToken  = Encoding.UTF8.GetString(decodedToken);

            var result = await _userManger.ConfirmEmailAsync(user, normalToken);

            if (result.Succeeded)
            {
                return new UserManagerResponse
                       {
                           Message   = "Email confirmed successfully!",
                           IsSuccess = true,
                       }
            }
            ;

            return(new UserManagerResponse
            {
                IsSuccess = false,
                Message = "Email did not confirm",
                Errors = result.Errors.Select(e => e.Description)
            });
        }
Esempio n. 17
0
        public async Task <AjaxResult> ConfirmEmail(ConfirmEmailDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(new AjaxResult("邮箱激活失败:参数不正确", AjaxResultType.Error));
            }

            User user = await _userManager.FindByIdAsync(dto.UserId.ToString());

            if (user == null)
            {
                return(new AjaxResult("注册邮箱激活失败:用户不存在", AjaxResultType.Error));
            }

            if (user.EmailConfirmed)
            {
                return(new AjaxResult("注册邮箱已激活,操作取消", AjaxResultType.Info));
            }

            string         code   = UrlBase64ReplaceChar(dto.Code);
            IdentityResult result = await _userManager.ConfirmEmailAsync(user, code);

            return(result.ToOperationResult().ToAjaxResult());
        }
Esempio n. 18
0
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index"));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            StatusMessage = result.Succeeded ? "Děkujeme za ověření e-mailové adresy." : "Chyba při ověření.";
            if (result.Succeeded)
            {
                return(RedirectToPage("Manage/Index"));
            }
            return(Page());
        }
Esempio n. 19
0
        public async Task <IActionResult> ConfirmEmail(string userId, string token)
        {
            if (userId == null || token == null)
            {
                RedirectToAction("index", "home");
            }

            var user = await userManager.FindByIdAsync(userId);

            if (user == null)
            {
                ViewBag.ErrorMessage = $"The user with id {userId} not found";
                return(View("Not Found"));
            }
            var result = await userManager.ConfirmEmailAsync(user, token);

            if (result.Succeeded)
            {
                return(View());
            }

            ViewBag.ErrorTitle = "Email cannot be confirmed";
            return(View("Error"));
        }
Esempio n. 20
0
        public async Task ConfirmEmail(string userId, string token)
        {
            if (userId == null || token == null)
            {
                throw new InvalidOperationException("Email confirmation failed");
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                throw new InvalidOperationException("User not found");
            }

            if (!user.EmailConfirmed)
            {
                var confirmationResult = await _userManager.ConfirmEmailAsync(user, token);

                if (!confirmationResult.Succeeded)
                {
                    throw new InvalidOperationException("Email confirmation failed.");
                }
            }
        }
        public async Task <IActionResult> ConfirmEmail(string userId, string token)
        {
            if (userId == null || token == null)
            {
                return(View());
            }
            var user = await _userManager.FindByIdAsync(userId);

            if (user != null)
            {
                var result = await _userManager.ConfirmEmailAsync(user, token);

                if (result.Succeeded)
                {
                    // cart objesini oluşturalım
                    await _cartService.InitializeCart(user.Id);

                    //CreateMessage("hesabınız onaylandı", "hesabınız onaylandı.", "success");
                    //return Json(new { success=true, redirectUrl="/account/login", message="Kullanıcı kaydınız tamamlandı. Giriş yapabilirsiniz." });
                    return(RedirectToAction(nameof(Login)));
                }
            }
            return(Json(new { message = "Böyle bir kullanıcı bulunamadı." }));
        }
Esempio n. 22
0
        public async Task <IActionResult> ConfirmEmail(int userId, string token, string returnUrl)
        {
            ApplicationUser user = await _userManager.FindByIdAsync(userId.ToString());

            if (user == null)
            {
                return(RedirectToAction(nameof(AccountController.Login)));
            }

            IdentityResult confirmEmailResult = await _userManager.ConfirmEmailAsync(user, token);

            if (!confirmEmailResult.Succeeded)
            {
                return(RedirectToAction(nameof(AccountController.Login)));
            }

            await CreateRequiredDataAsync(user.Id);
            await CreateSamplesAsync(user.Id);

            // Notify admin
            _ = _emailTemplateService.EnqueueNewEmailVerificationEmailAsync(user.Name, user.Email);

            return(RedirectToAction(nameof(AccountController.Login), new { returnUrl, alert = LoginAlert.RegistrationConfirmed }));
        }
        public async Task <IActionResult> OnPost(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("./");
            if (ModelState.IsValid && Email != null)
            {
                var user = await _userManager.FindByEmailAsync(Email);

                var token = await _userManager.GeneratePasswordResetTokenAsync(user);

                if (user == null)
                {
                    FailureMessage = "Unknown Email";
                    return(Page());
                }
                var result = await _userManager.ConfirmEmailAsync(user, Code);

                if (!result.Succeeded)
                {
                    FailureMessage = "Invalid code";
                    return(Page());
                }
                var userUpdate = await _userManager.ResetPasswordAsync(user, token, Password);

                await _signinManager.SignOutAsync();

                if (returnUrl != null)
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToPage("./Index"));
                }
            }
            return(Page());
        }
Esempio n. 24
0
        /// <summary>
        /// Confirm a user's email address.
        /// </summary>
        /// <param name="id">The user if of the user being confirmed.</param>
        /// <param name="token">The email confirmation token.</param>
        /// <returns>A <see cref="LocalRedirectResult"/> to the appropriate end route.</returns>
        public async Task <IActionResult> Confirm(string id, string token)
        {
            // get the user
            var newUser = await _userManager.FindByIdAsync(id);

            // if the user's email is already confirmed, no need to do it again
            if (!newUser.EmailConfirmed)
            {
                // confirm the email
                var result = await _userManager.ConfirmEmailAsync(newUser, token);

                // if the confirmation failed, show the failure message
                if (!result.Succeeded)
                {
                    return(LocalRedirect("~/home"));
                }
            }

            // get a new JWT token for this user
            var jwtToken = GenerateJwtToken(newUser);

            // redirect the user to the external login route
            return(LocalRedirect($"/external?returnUrl=/confirmed&token={ jwtToken }"));
        }
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            ViewBag.Setting = _toursDbContext.Settings.First();
            if (userId == null || code == null)
            {
                return(RedirectToAction("Login")); ///burda bashqa error seyfesi yaratmaq olar
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                throw new ApplicationException("Unable to find User");
            }

            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                return(View("ConfirmEmail"));
            }

            return(RedirectToAction("Transfer", "Service"));
        }
Esempio n. 26
0
        public async Task <Result <string> > ConfirmEmailAsync(string userId, string code)
        {
            //var user = await _userRepository.FindUserByIdAsync(userId).ConfigureAwait(false);
            var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false);

            if (user == null)
            {
                throw new NotFoundException();
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code).ConfigureAwait(false);

            if (!result.Succeeded)
            {
                throw new ApiException($"An error occurred while confirming {user.Email}.");
            }

            await _userRepository.UpdateActivatedAtAsync(userId, DateTime.UtcNow).ConfigureAwait(false);

            return(Result <string> .Success(user.Id,
                                            message :
                                            $"Account Confirmed for {user.Email}. You can now use the /api/identity/token endpoint to generate JWT."));
        }
Esempio n. 27
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(View("Error"));
            }
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(View("Error"));
            }
            //If the email is alraedy confirmed go to home page.
            if (user.EmailConfirmed)
            {
                return(View("Login"));
            }
            //Confirm the token
            var result = await _userManager.ConfirmEmailAsync(user, code);

            //If the token was correct, add the email to the UserEmailAddress model aswell.
            bool emailCreated = false;

            if (result.Succeeded)
            {
                UserEmailAddresses email = new UserEmailAddresses();
                email.ApplicationUser   = user;
                email.ApplicationUserId = user.Id;
                email.Confirmed         = true;
                email.emailAddress      = user.UserName;
                email.EmailType         = EmailTypes.Primary;
                //Create the email address in the database
                emailCreated = _emailProvider.createEmailForUser(email);
            }
            return(View((result.Succeeded && emailCreated) ? "ConfirmEmail" : "Error"));
        }
        //////////////////////////////////////////////////////////////////////////////
        // Common Methods
        //////////////////////////////////////////////////////////////////////////////

        private async Task <AspNetUser> AuthCreateUser(string email, string password, bool isExistingUser, bool verifyEmail, bool signUpForNews, string organizationId)
        {
            AspNetUser aspNetUser = base.identityDB.AspNetUsers.Where(u => u.Email == email).FirstOrDefault();

            //auth User, if existing
            if (isExistingUser)
            {
                if (aspNetUser != null)
                {
                    ApplicationUser user = new ApplicationUser()
                    {
                        UserName = email, Email = email
                    };
                    user = await base.UserManager.FindAsync(user.UserName, password);

                    if (user == null)
                    {
                        aspNetUser = null;
                        ModelState.AddModelError("Password", "User Email and/or Password is not valid");
                    }
                }
                else
                {
                    ModelState.AddModelError("IsExistingUser", "User does not exist");
                }
            }
            //else create User, send out verification email
            else
            {
                if (aspNetUser == null)
                {
                    ApplicationUser user = new ApplicationUser()
                    {
                        UserName = email, Email = email
                    };
                    IdentityResult result = await UserManager.CreateAsync(user, password);

                    if (result.Succeeded)
                    {
                        aspNetUser = identityDB.AspNetUsers.SingleOrDefault(u => u.Email == email);
                        user       = await UserManager.FindByEmailAsync(user.Email);


                        if (organizationId != null && aspNetUser.DefaultOrganizationId == null)
                        {
                            aspNetUser.DefaultOrganizationId = organizationId;
                            db.SaveChanges();
                        }

                        //send email verification notification to user
                        if (verifyEmail)
                        {
                            //generate callback url
                            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

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

                            //send notification
                            bool notifySuccess =
                                new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                    "USER_ACCOUNT_CONFIRM_EMAIL",
                                    user.Email,
                                    "User:"******"InvitationUrl", callbackUrl },
                                { "Email", user.Email }
                            });
                        }
                        //set email as already confirmed
                        else
                        {
                            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                            result = await UserManager.ConfirmEmailAsync(user.Id, token : code);
                        }

                        //subscribe user to news
                        if (signUpForNews)
                        {
                            //Subscribe the user for news
                            GNNotificationTopic NewsTopic   = db.GNNotificationTopics.Where(a => a.Code.Equals("GENOMENEXT_NEWS_AND_PRODUCTS") && a.Status == "ACTIVE").FirstOrDefault();
                            GNContact           UserContact = db.GNContacts.Where(a => a.Email.Equals(aspNetUser.Email)).FirstOrDefault();

                            if (UserContact != null)
                            {
                                UserContact.IsSubscribedForNewsletters = true;
                            }

                            db.SaveChanges();

                            if (NewsTopic != null && UserContact != null)
                            {
                                UserContact.GNNotificationTopicSubscribers.Add(new GNNotificationTopicSubscriber
                                {
                                    AddresseeType         = "TO",
                                    GNContactId           = UserContact.Id,
                                    GNNotificationTopicId = NewsTopic.Id,
                                    IsSubscribed          = "Y",
                                    CreateDateTime        = DateTime.Now,
                                    CreatedBy             = UserContact.Id
                                });
                            }
                        }
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
                else
                {
                    ModelState.AddModelError("Email", "User with this Email Address already exists");
                }
            }
            return(aspNetUser);
        }
        public async Task <RegisterResult> Register([FromBody] RegisterTeacherApiModel model)
        {
            var ctx = HttpContext.Current;

            try
            {
                if (ModelState.IsValid)
                {
                    string filePath = "";
                    foreach (string file in ctx.Request.Files)
                    {
                        var postedFile = ctx.Request.Files[file];
                        filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
                        postedFile.SaveAs(filePath);
                    }
                    var user = new ApplicationUser
                    {
                        UserName = model.UserName,
                        Email    = model.UserName + "@courses.com",
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        var token = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        await UserManager.ConfirmEmailAsync(user.Id, token);

                        var resRole = await UserManager.AddToRoleAsync(user.Id, "Teacher");

                        Db.Teachers.Add(new Teacher
                        {
                            FirstName = model.FirstName,
                            LastName  = model.LastName,
                            UserId    = user.Id,
                            CountryId = model.CountryId.HasValue ? model.CountryId.Value : Db.Countries.FirstOrDefault().Id,
                            ImageUrl  = string.IsNullOrEmpty(filePath) ? null : filePath
                        });
                        await Db.SaveChangesAsync();

                        return(new RegisterResult()
                        {
                            IsOk = true,
                            Message = new Message(MessageType.Success.ToString(), MessageType.Success),
                            Username = ""
                        });
                    }
                    else
                    {
                        List <string> errors = new List <string>();
                        foreach (var item in result.Errors)
                        {
                            errors.Add(item);
                        }
                        return(new RegisterResult()
                        {
                            IsOk = true,
                            Message = new Message(string.Join(",", errors.ToArray()), MessageType.Error),
                            Username = ""
                        });
                    }
                }
                else
                {
                    List <string> errors = new List <string>();
                    foreach (var item in ModelState.Values)
                    {
                        foreach (var error in item.Errors)
                        {
                            errors.Add(error.ErrorMessage);
                        }
                    }
                    return(new RegisterResult()
                    {
                        IsOk = true,
                        Message = new Message(string.Join(",", errors.ToArray()), MessageType.Error),
                        Username = null
                    });
                }
            }
            catch (Exception ex)
            {
                return(new RegisterResult()
                {
                    IsOk = false,
                    Message = new Message(ex.Message + " " + ex.InnerException?.Message, MessageType.Error),
                    Username = null
                });
            }
        }
Esempio n. 30
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            string role = Request.Form["rdUserRole"].ToString();

            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    Name          = Input.Name,
                    City          = Input.City,
                    StreetAddress = Input.StreetAddress,
                    State         = Input.State,
                    PostalCode    = Input.PostalCode,
                    PhoneNumber   = Input.PhoneNumber
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    if (!await _roleManager.RoleExistsAsync(SD.ManagerUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.ManagerUser));
                    }
                    if (!await _roleManager.RoleExistsAsync(SD.KitchenUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.KitchenUser));
                    }
                    if (!await _roleManager.RoleExistsAsync(SD.FrontDeskUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.FrontDeskUser));
                    }
                    if (!await _roleManager.RoleExistsAsync(SD.CustomerEnduser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.CustomerEnduser));
                    }

                    if (role == SD.KitchenUser)
                    {
                        await _userManager.AddToRoleAsync(user, SD.ManagerUser);
                    }
                    else if (role == SD.FrontDeskUser)
                    {
                        await _userManager.AddToRoleAsync(user, SD.FrontDeskUser);
                    }
                    else if (role == SD.ManagerUser)
                    {
                        await _userManager.AddToRoleAsync(user, SD.ManagerUser);
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, SD.CustomerEnduser);
                    }


                    _logger.LogInformation("User created a new account with password.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        //return RedirectToPage("RegisterConfirmation", new { email = Input.Email });

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        EmailConfirmationUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);
                        code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
                        var output = await _userManager.ConfirmEmailAsync(user, code);

                        if (role != SD.CustomerEnduser)
                        {
                            return(RedirectToAction("Index", "User", new { area = "Admin" }));
                        }
                        return(LocalRedirect(returnUrl));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task<ActionResult> ConfirmEmail(int userId, string code)
        {
            if (userId == 0 || code == null)
            {
                TempData.Add("confirmEmail", "No se ha podido confirmar el email");
                return View("Login");
            }
            IdentityResult result;
            try
            {
                var provider = new MachineKeyProtectionProvider();
                UserManager<User, int> um = new UserManager<User, int>(ur);
                um.UserTokenProvider = new DataProtectorTokenProvider<User, int>(provider.Create("EmailConfirmation"));
                result = await um.ConfirmEmailAsync(userId, code);
            }
            catch (ArgumentNullException)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                TempData.Add("confirmEmail", "Usuario no encontrado");
                return View("Login");
            }
            catch(ArgumentException)
            {
                TempData.Add("confirmEmail", "El email ya ha sido validado anteriormente");
                return View("Login");
            }

            if (result.Succeeded)
            {
                TempData.Add("confirmEmail", "Se ha confirmado su email correctamente");
                return View("Login");
            }

            TempData.Add("confirmEmail", result);
            return View("Login");
        }
        public void EmailConfirmed()
        {
            using (UserStore<IdentityUser> store = new UserStore<IdentityUser>())
            {
                using (UserManager<IdentityUser> manager = new UserManager<IdentityUser>(store))
                {
                    manager.UserTokenProvider = new EmailTokenProvider<IdentityUser>();
                    var user = CreateTestUser();

                    var taskUserSet = manager.GenerateEmailConfirmationTokenAsync(user.Id);
                    taskUserSet.Wait();
                    Assert.IsFalse(string.IsNullOrWhiteSpace(taskUserSet.Result), "GenerateEmailConfirmationToken failed.");
                    string token = taskUserSet.Result;

                    var taskConfirm = manager.ConfirmEmailAsync(user.Id, token);
                    taskConfirm.Wait();
                    Assert.IsTrue(taskConfirm.Result.Succeeded, string.Concat(taskConfirm.Result.Errors));

                    user = manager.FindByEmail(user.Email);
                    var taskConfirmGet = store.GetEmailConfirmedAsync(user);
                    taskConfirmGet.Wait();
                    Assert.IsTrue(taskConfirmGet.Result, "Email not confirmed");

                    try
                    {
                        var task = store.SetEmailConfirmedAsync(null, true);
                        task.Wait();
                    }
                    catch (Exception ex)
                    {
                        Assert.IsNotNull(ex, "Argument exception not raised");
                    }

                    try
                    {
                        var task = store.GetEmailConfirmedAsync(null);
                        task.Wait();
                    }
                    catch (Exception ex)
                    {
                        Assert.IsNotNull(ex, "Argument exception not raised");
                    }

                }
            }
        }