Example #1
0
        public async Task<ActionResult> Disconnect(ApplicationSignInManager signInManager, ApplicationUserManager userManager, string provider, string userId, string redirectUri)
        {
            var userLoginInfo = (await userManager.GetLoginsAsync(userId)).First(x => x.LoginProvider == provider);

            var result = await userManager.RemoveLoginAsync(userId, userLoginInfo);
            if (result.Succeeded)
            {
                var user = await userManager.FindByIdAsync(userId);
                if (user != null)
                {
                    await signInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                }
            }
            else
            {
                Logger.Error($"Unable to disconnect {provider} from user {userId}");
            }
            return new RedirectResult(redirectUri);
        }
Example #2
0
        public async Task <ActionResult> RemoveLogin(string loginProvider, string providerKey)
        {
            ManageMessageId?message;
            var             result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));

            if (result.Succeeded)
            {
                var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                if (user != null)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                message = ManageMessageId.RemoveLoginSuccess;
            }
            else
            {
                message = ManageMessageId.Error;
            }
            return(RedirectToAction("ManageLogins", new { Message = message }));
        }
        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));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, MiddleName = model.MiddleName, LastName = model.LastName, PhoneNumber = model.Phone
                };
                var result = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    var currentUser = await _userManager.FindByEmailAsync(user.Email).ConfigureAwait(false);

                    await _userManager.AddToRoleAsync(currentUser.Id, "User").ConfigureAwait(false);

                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : true).ConfigureAwait(false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id).ConfigureAwait(false);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, protocol: Request.Url.Scheme);
                    //await _userManager.SendEmailAsync(
                    //        user.Id,
                    //        "Подтвердите электронную почту",
                    //        "Чтобы подтвердить регистрацию <a href=\"" + callbackUrl + "\">кликните здесь</a>")
                    //    .ConfigureAwait(false);


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

                ModelState.AddModelErrors(result.Errors.Select(x => new ValidationResult(x)));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        //
        // GET: /Link/ProcessCode
        public async Task <ActionResult> ProcessCode(string code, string error, string error_description, string resource, string state)
        {
            if (TempData[StateKey] as string != state)
            {
                TempData["Error"] = "Invalid operation. Please try again";
                return(RedirectToAction("Index"));
            }

            var authResult = await AuthenticationHelper.GetAuthenticationResultAsync(code);

            var tenantId           = authResult.TenantId;
            var graphServiceClient = authResult.CreateGraphServiceClient();

            IGraphClient graphClient = new MSGraphClient(graphServiceClient);
            var          user        = await graphClient.GetCurrentUserAsync();

            var tenant = await graphClient.GetTenantAsync(tenantId);

            var isAccountLinked = await applicationService.IsO365AccountLinkedAsync(user.Id);

            if (isAccountLinked)
            {
                TempData["Error"] = $"Failed to link accounts. The Office 365 account '{user.UserPrincipalName}' is already linked to another local account.";
                return(RedirectToAction("Index"));
            }

            // Link the AAD User with local user.
            var localUser = await applicationService.GetCurrentUserAsync();

            await applicationService.UpdateLocalUserAsync(localUser, user, tenant);

            // Re-sign in user. Required claims (roles, tenent id and user object id) will be added to current user's identity.
            await signInManager.SignInAsync(localUser, isPersistent : false, rememberBrowser : false);

            TempData["Message"] = Resources.LinkO365AccountSuccess;
            TempData[HandleAdalExceptionAttribute.ChallengeImmediatelyTempDataKey] = true;
            return(RedirectToAction("Index", "Home"));
        }
Example #6
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 UserManager.AddToRoleAsync(user.Id, "user");

                    //создаем claim для хранения года рождения
                    var identityClaim = new IdentityUserClaim {
                        ClaimType = "RegistrationDate", ClaimValue = DateTime.Now.ToString()
                    };
                    // добавляем claim пользователю
                    user.Claims.Add(identityClaim);
                    // сохраняем изменения
                    await UserManager.UpdateAsync(user);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://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("Posts", "Blog"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #7
0
        public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var result = await _userManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());

                if (user != null)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }));
            }
            AddErrors(result);
            return(View(model));
        }
Example #8
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 UserManager.AddToRoleAsync(user.Id, UserRoles.User);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction(DefaultActions.Index, ControllerNames.Home));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> Password(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(JsonResultEx.Create(ModelState));
            }

            var result = await _applicationUserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword).ConfigureAwait(false);

            if (result.Succeeded)
            {
                var user = await _applicationUserManager.FindByIdAsync(User.Identity.GetUserId()).ConfigureAwait(false);

                if (user != null)
                {
                    await _applicationSignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false).ConfigureAwait(false);
                }
                return(JsonResultEx.Create());
            }

            AddErrors(result);
            return(JsonResultEx.Create(ModelState));
        }
Example #10
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 _userManager.AddToRoleAsync(user.Id, "User");

                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

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

            // Dotarcie do tego miejsca wskazuje, że wystąpił błąd, wyświetl ponownie formularz
            return(View(model));
        }
Example #11
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new UserAccount {
                    UserName = model.Email, Email = model.Email
                };
                var result = await accountUserManager.CreateAsync(user, model.Password);

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

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", result.Errors.FirstOrDefault());
                }
            }

            return(View(model));
        }
Example #12
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = new GameStoreUser {
                Email = model.Email, UserName = model.UserName
            };

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

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

            await signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

            userManager.AddToRole(user.Id, "Customer");
            return(ReturnToGamesList());
        }
Example #13
0
        public async Task <ActionResult> Create([Bind(Include = "EncadrantID,Nom,Prenom,DateEmbauche,Email,Password,Bureau")] Encadrant encadrant,
                                                string[] StageID
                                                )
        {
            if (StageID != null)
            {
                encadrant.Stages = new List <Stage>();
                foreach (var stage in StageID)
                {
                    var stageToAdd = db.Stages.Find(int.Parse(stage));
                    //var stageToAdd = db.Stages.Find(int.Parse(stage));
                    encadrant.Stages.Add(stageToAdd);
                }
            }
            ApplicationUserManager   userManager   = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationSignInManager signInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>();

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = encadrant.Email, Email = encadrant.Email
                };
                var result = await userManager.CreateAsync(user, encadrant.Password);

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

                    db.Encadrants.Add(encadrant);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            PopulateAssignedStageData(encadrant);
            return(View(encadrant));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    MiddleName  = model.MiddleName,
                    LastName    = model.LastName,
                    EGN         = model.EGN,
                    PhoneNumber = model.Number
                };

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

                UserManager.AddToRole(user.Id, GlobalConstants.NOT_VERIFIED_USER);

                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("NotVerified", "Validation"));
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #15
0
        public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var result = await _userManager.ChangePasswordAsync(User.Identity.GetUserId <int>(), model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                var user = await _userManager.FindByIdAsync(User.Identity.GetUserId <int>());

                if (user != null)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                //this.Flash("Success", ResultMessages.Success());
                return(RedirectToAction("Details", "User"));
            }
            AddErrors(result);
            return(View(model));
        }
Example #16
0
        public async Task <ActionResult> Register(AccountRegisterViewModel viewModel)
        {
            var existingUser = await _userManager.FindByEmailAsync(viewModel.Email);

            if (existingUser != null)
            {
                ModelState.AddModelError("Email", $"The provided email address '{viewModel.Email}' has already been used to register an account. Please sign-in using your existing account.");
            }

            if (ModelState.IsValid)
            {
                // Instantiate a User object
                var user = new User {
                    UserName = viewModel.Email, Email = viewModel.Email
                };

                // Create the user
                var result = await _userManager.CreateAsync(user, viewModel.Password);

                // If the user was successfully created...
                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // Sign-in the user and redirect them to the web app's "Home" page
                    return(RedirectToAction("Index", "Entries"));
                }
                // If there were errors...
                // Add model errors
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }
            return(View(viewModel));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = new User
            {
                UserName  = model.Email,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName
            };
            var result = await _userManager.CreateAsync(user, model.Password);

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

                return(RedirectToAction("Index", "Dashboard"));
            }
            AddErrors(result);
            return(View(model));
        }
Example #18
0
        public async Task <ActionResult> Register(AccountRegisterViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await _userManager.FindByNameAsync(viewModel.Username);

                if (existingUser != null)
                {
                    ModelState.AddModelError("Email", $"The provided email address '{viewModel.Username}' has already been used to register an account. Please sign-in using your existing account.");
                }

                var user = new User {
                    UserName = viewModel.Username
                };

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


                if (result.Succeeded)
                {
                    //Dodeliti useru role User ili Admin
                    await _userManager.AddToRoleAsync(user.Id, _roleRepository.GetRoleById("2").Name);

                    await _signInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Index", "Gif"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            return(View(viewModel));
        }
Example #19
0
        public async Task <ActionResult> UserRegistration(UserViewModel userViewModel, string ButtonType)
        {
            if (ButtonType == "Next")
            {
                if (ModelState.IsValid)
                {
                    CurrentUserModel = userViewModel;
                    ApplicationDbContext context = new ApplicationDbContext();

                    var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

                    var user = new ApplicationUser {
                        UserName = CurrentUserModel.Username, Email = CurrentUserModel.Email, DisplayName = CurrentStaff.GetFullName()
                    };
                    var result = await UserManager.CreateAsync(user, CurrentUserModel.Password);

                    if (result.Succeeded)
                    {
                        if (CurrentStaff.StaffType == BLL.Constants.StaffTypes.TEACHER)
                        {
                            UserManager.AddToRole(user.Id, "Teacher");
                            var teacher = new Teacher()
                            {
                                ID = CurrentStaff.ID
                            };
                            _unitOfWork.Teachers.Add(teacher);
                        }


                        CurrentStaff.user_id = user.Id;

                        _service.Update(CurrentStaff);
                        _unitOfWork.Addresss.Update(CurrentStaff.Address); // just to make sure



                        try
                        {
                            ApplicationSignInManager SignInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>();
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            await _unitOfWork.SaveAsync();
                        }
                        catch (DbUpdateConcurrencyException)
                        {
                        }


                        ModelState.Clear();

                        return(View("SuccessRegistration", CurrentStaff));
                    }
                }
            }


            else if (ButtonType == "Back")
            {
                return(View("StaffInfo", CurrentStaff));
            }



            return(View());
        }
Example #20
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Role == "Ученик" || model.Role == "Student")
                {
                    model.Role = "Student";
                }
                else if (model.Role == "Ръководител" || model.Role == "Leader")
                {
                    model.Role = "Teacher";
                }
                var user = new ApplicationUser
                {
                    UserName   = model.Email,
                    Email      = model.Email,
                    FirstName  = model.FirstName,
                    SecondName = model.SecondName,
                    LastName   = model.LastName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, model.Role);
                    this.userService.AddAppUser(user.Id, model.Role);
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    //  this.userService.AddAppUser(user.Id, model.Role, schoolId);
                    // 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"));
                }
                var newErrors = new List <string>();
                for (int i = 0; i < result.Errors.Count(); i++)
                {
                    if (result.Errors.ElementAt(i) == "Passwords must have at least one digit ('0'-'9').")
                    {
                        newErrors.Add(Common.HaveOneDigit);
                    }
                    if (result.Errors.ElementAt(i).Contains("is already taken."))
                    {
                        if (result.Errors.ElementAt(i).Contains("Email"))
                        {
                            newErrors.Add(Common.EmailOccupied);
                        }
                    }
                }
                var newResult = new IdentityResult(newErrors);
                AddErrors(newResult);
            }

            // If we got this far, something failed, redisplay form
            model.Roles = new SelectList(new List <string>()
            {
                Common.Student, Common.Leader
            });
            return(View(model));
        }
        public async Task SignInWithEmail(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            await _signInManager.SignInAsync(user, isPersistent : false);
        }
Example #22
0
 public Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
 {
     return(_signInManager.SignInAsync(user, isPersistent, rememberBrowser));
 }
Example #23
0
 public async Task SignInAsync(IApplicationUser user, bool isPersistent, bool rememberBrowser)
 {
     await ApplicationSignInManager.SignInAsync(user as ApplicationUser, isPersistent, rememberBrowser);
 }
        public async Task <ActionResult> RegisterUser(RegisterViewModel user)
        {
            //Add ModelState errors for null first and last name
            if (user.FirstName == null)
            {
                ModelState.AddModelError("firstname", "Please enter a First Name");
            }

            if (user.LastName == null)
            {
                ModelState.AddModelError("lastname", "Please enter a Last Name");
            }



            if (ModelState.IsValid)
            {
                var appUser = new ApplicationUser {
                    UserName = user.Email, Email = user.Email
                };


                var result = await UserManager.CreateAsync(appUser, user.Password);

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

                    //Create Personal Trainer record
                    //Will need to add a checkbox to capture the user type

                    if (user.UserType == "trainer")
                    {
                        PersonalTrainer personalTrainer = new PersonalTrainer()
                        {
                            UserID    = appUser.Id,
                            FirstName = user.FirstName,
                            LastName  = user.LastName,
                            Email     = appUser.Email
                        };

                        db.PersonalTrainers.Add(personalTrainer);
                        db.SaveChanges();
                    }

                    if (user.UserType == "client")
                    {
                        Client client = new Client()
                        {
                            UserID    = appUser.Id,
                            FirstName = user.FirstName,
                            LastName  = user.LastName,
                            Email     = appUser.Email
                        };

                        db.Clients.Add(client);
                        db.SaveChanges();
                    }


                    // For more information on how to enable account confirmation and password reset please visit https://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>");

                    ApplicationUser newUser = new ApplicationUser();
                    newUser = db.Users.Where(u => u.Email == user.Email).SingleOrDefault();

                    return(Json(new { registerStatus = "success", UID = newUser.Id, user }));
                }

                if (!result.Succeeded)
                {
                    AddErrors(result);
                    return(Json(new { registerStatus = "fail", result, user }));
                }
            }

            //Set RegisterButtonError to true so the script that opens the Register Popup runs
            ViewBag.RegisterButtonError = "true";
            //create a list of the errors from ModelState
            List <string> errors = new List <string>();

            //The Errors array is inside the Values array, so we need a nested foreach
            foreach (var v in ModelState.Values)
            {
                foreach (var e in v.Errors)
                {
                    errors.Add(e.ErrorMessage);
                }
            }
            // If we got this far, something failed, return errors
            return(Json(new { registerStatus = "modelfail", user, errors }));
        }
Example #25
0
        public async Task <ActionResult> ExternalLoginConfirmation([Bind(Exclude = "UserPhoto")] ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }

            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"));
                }

                // To convert the user uploaded Photo as Byte Array before save to DB
                byte[] imageData = null;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];

                    using (var binary = new BinaryReader(poImgFile.InputStream))
                    {
                        imageData = binary.ReadBytes(poImgFile.ContentLength);
                    }
                }

                var user = new ApplicationUser
                {
                    UserName        = model.Email,
                    Email           = model.Email,
                    FullName        = model.FullName,
                    GenderId        = model.GenderId,
                    Birthdate       = model.Birthdate,
                    IsSecuredByNHIF = model.IsSecuredByNHIF,
                    //Here we pass the byte array to user context to store in db
                    UserPhoto = imageData
                };
                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);
            }

            // If we got this far, something failed, redisplay form
            var genders = _context.Genders.ToList();

            var viewModel = new ExternalLoginConfirmationViewModel
            {
                Genders = genders
            };

            ViewBag.errorMessage = "Неуспешен вход!";
            ViewBag.ReturnUrl    = returnUrl;
            return(View(viewModel));
        }
        public async Task SignInAsync(string email, bool isPersistent, bool rememberBrowser)
        {
            AppUser user = await GetUserByEmail(email);

            await _signInManager.SignInAsync(user, isPersistent, rememberBrowser);
        }
Example #27
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            using (var context = new ApplicationDbContext())
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser
                    {
                        UserName = model.Username,

                        Email = model.EmailAddress,
                        // UserProfileInfo is the model class where user information is stored.
                        // The first part (LastName) is the property of the model, the second part
                        // (model.LastName) is from the RegisterViewModel located within
                        // AccountViewModels.cs model.
                        UserProfileInfo = new UserProfileInfo
                        {
                            UserID       = model.UserID,
                            Username     = model.Username,
                            LastName     = model.LastName,
                            FirstName    = model.FirstName,
                            BirthDate    = model.BirthDate,
                            CreateDate   = model.CreateDate,
                            Address      = model.Address,
                            ZipCode      = model.ZipCode,
                            CellPhone    = model.CellPhone,
                            EmailAddress = model.EmailAddress,
                            Password     = model.Password,
                            Activity     = true
                        }
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    var roleStore   = new RoleStore <IdentityRole>(context);
                    var roleManager = new RoleManager <IdentityRole>(roleStore);

                    var userStore   = new UserStore <ApplicationUser>(context);
                    var userManager = new UserManager <ApplicationUser>(userStore);
                    //userManager.AddToRole(user.Id, "User");



                    if (result.Succeeded)
                    {
                        UserManager.AddToRole(user.Id, "Active");
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        //db.UserProfileInfos.Add(new UserProfileInfo
                        //    {
                        //        UserID = model.UserID,
                        //        Username = model.Username,
                        //        LastName = model.LastName,
                        //        FirstName = model.FirstName,
                        //        BirthDate = model.BirthDate,
                        //        CreateDate = model.CreateDate,
                        //        Address = model.Address,
                        //        ZipCode = model.ZipCode,
                        //        CellPhone = model.CellPhone,
                        //        EmailAddress = model.EmailAddress,
                        //        Password = model.Password
                        //    }
                        //);
                        //db.SaveChanges();

                        //var 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 this link: <a href=\"" + callbackUrl + "\">link</a>");
                        //ViewBag.Link = callbackUrl;
                        //return View("DisplayEmail");
                        //await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles)
                        return(RedirectToAction("Login", "Account"));
                    }
                    AddErrors(result);


                    // If we got this far, something failed, redisplay form
                }
            return(View(model));
        }
Example #28
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                string petName = model.RealName.ToPetName();
                string sex     = model.Sex == 0 ? "  先生" : "  女士";
                var    user    = new ApplicationUser
                {
                    UserName    = model.UserName,
                    Email       = model.Email,
                    Sex         = model.Sex,
                    PhoneNumber = model.PhoneNumber,
                    RealName    = model.RealName,
                    PetName     = petName + sex,
                    HomeTown    = model.Region + model.HomeTown
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    if (model.UserName == "XiaoFeng")
                    {
                        //var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationMaiLaFeng()));
                        string name = "Admin";
                        //创建测试角色
                        RoleManager.Create(new IntRole("employees", "普通员工"));
                        RoleManager.Create(new IntRole("depmanager", "部门经理"));
                        RoleManager.Create(new IntRole("hrmanager", "人事经理"));
                        RoleManager.Create(new IntRole("director", "主管总监"));
                        RoleManager.Create(new IntRole("deputygeneralmanager", "副总经理"));
                        RoleManager.Create(new IntRole("generalmanager", "总经理"));
                        RoleManager.Create(new IntRole());
                        if (!RoleManager.RoleExists(name))
                        {
                            var roleresult = RoleManager.Create(new IntRole(name));
                            //角色创建成功
                            if (roleresult.Succeeded)
                            {
                                //为admin用户添加管理员角色
                                var resultFinall = UserManager.AddToRole(user.Id, name);
                                if (resultFinall.Succeeded)
                                {
                                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                                }
                            }
                            else
                            {
                                var resultFinall = UserManager.AddToRole(user.Id, name);
                                if (resultFinall.Succeeded)
                                {
                                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                                }
                            }
                        }
                    }

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                    // 发送包含此链接的电子邮件
                    // 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, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">這裏</a>来确认你的帐户");

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

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
Example #29
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            var user1 = await UserManager.FindByNameAsync(model.Email);

            if (user1 != null)
            {
                if (!await UserManager.IsEmailConfirmedAsync(user1.Id))
                {
                    ViewBag.errorMessage = "Before Registration, you need to confirm your email sent by Admin. Check your email!";
                    return(View("Error"));
                }
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser
                    {
                        OwnerName = model.OwnerName,
                        UserName  = model.OwnerName,
                        Email     = model.Email,

                        Owner = new Owner
                        {
                            Email           = model.Email,
                            OwnerName       = model.OwnerName,
                            CompanyName     = model.CompanyName,
                            Description     = model.Description,
                            DateOfJoining   = model.DateOfJoining,
                            FoundedIn       = model.FoundedIn,
                            Street1         = model.Street1,
                            Street2         = model.Street2,
                            City            = model.City,
                            State           = model.State,
                            Country         = model.Country,
                            Pin             = model.Pin,
                            ContactNumber   = model.ContactNumber,
                            WebsiteUrl      = model.WebsiteUrl,
                            TwitterHandler  = model.TwitterHandler,
                            FacebookPageUrl = model.FacebookPageUrl
                        }
                    };

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

                    if (result.Succeeded)
                    {
                        UserManager.AddToRole(user.Id, "RegisterAdmin");
                        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
            ViewBag.errorMessage = "Before Registration, you need to be invited from Admin.";
            return(View("InviteError"));
        }
 public async Task SignUserAsync(User user)
 {
     await _signInManager.SignInAsync(user, false, false);
 }
Example #31
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

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

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }