public ApplicationUser CreateUser(ApplicationUser user)
 {
     throw new NotImplementedException();
 }
 public ApplicationUser EditUser(ApplicationUser user)
 {
     _context.Entry(user).State = EntityState.Modified;
     _context.SaveChanges();
     return user;
 }
 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
 }
        /// <summary>
        /// Seed an initial Admin user
        /// </summary>
        private void SeedInitialUserAndRole()
        {
            string emailAddress = "*****@*****.**";
            if (!_context.Users.Any(u => u.UserName == emailAddress))
            {
                var roleStore = new RoleStore<IdentityRole>(_context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var store = new UserStore<ApplicationUser>(_context);
                var manager = new UserManager<ApplicationUser>(store);
                Tenant tenant = _context.Tenants.First(t => t.Name == "Polar");
                if (tenant != null)
                {
                    IList<Tenant> tenants = new List<Tenant>();
                    tenants.Add(tenant);
                    var user = new ApplicationUser { UserName = emailAddress, Email = emailAddress, UserTenants = tenants };

                    roleManager.Create(new IdentityRole { Name = EnumHelper.Roles.Admin.ToString() });
                    manager.Create(user, "password");
                    manager.AddToRole(user.Id, EnumHelper.Roles.Admin.ToString());

                    SeedUserSettings seedUserSettings = new SeedUserSettings(user.Id);

                }
            }
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("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 };
                IdentityResult result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent: 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);
                        // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");

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

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            string gCaptcha = HttpContext.Request.Params["g-recaptcha-response"];
            string userIpAddress = Request.ServerVariables["REMOTE_ADDR"];
            if (!string.IsNullOrWhiteSpace(gCaptcha) && UtilityHelper.IsGoogleReCaptchaValid(gCaptcha, userIpAddress))
            {
                if (ModelState.IsValid)
                {
                    Tenant tenant = new Tenant
                    {
                        Name = model.OrganisationName
                    };
                    IList<Tenant> tenants = new List<Tenant>();
                    tenants.Add(tenant);

                    var user = new ApplicationUser() { 
                        UserName = model.Email, 
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        OrganisationalRole = model.OrganisationalRole,
                        PhoneNumber = model.TelephoneNumber,
                        Email = model.Email, 
                        UserTenants = tenants };
                    IdentityResult result = await UserManager.CreateAsync(user, model.Password);
                    result = await UserManager.AddToRoleAsync(user.Id, EnumHelper.Roles.Author.ToString());

                    SeedUserSettings seedUserSettings = new SeedUserSettings(user.Id);

                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent: 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");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            Alert(EnumHelper.Alerts.Error, HIResources.Strings.Change_Error);
            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult Create([Bind(Include = "Email,PhoneNumber,Role,LockoutEnabled,TenantId")] UserViewModel userViewModel)
        {
            string errors = string.Empty;
            if (ModelState.IsValid)
            {
                if (!User.IsInRole(EnumHelper.Roles.Admin.ToString()) && userViewModel.Role.Equals(EnumHelper.Roles.Admin.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    throw new Exception("Illegal privilege escalation");
                }

                IUserService userService = GetUserService();
                ApplicationUser applicationUser = new ApplicationUser
                {
                    Email = userViewModel.Email,
                    PhoneNumber = userViewModel.PhoneNumber,
                    UserName = userViewModel.Email,
                    LockoutEnabled = userViewModel.LockoutEnabled,
                    ForcePasswordReset = true,
                    UserTenants = new List<Tenant>
                    {
                        new Tenant
                        {
                            TenantId = int.Parse(userViewModel.TenantId)
                        }
                    },
                    TemporaryRole = userViewModel.Role
                };
                applicationUser = userService.CreateUser(applicationUser);

                errors = userService.Errors == null ? string.Empty : userService.Errors.ToString();
                if(!string.IsNullOrWhiteSpace(applicationUser.Id))
                {
                    Alert(EnumHelper.Alerts.Success, HIResources.Strings.Change_Success);
                    return RedirectToAction("Index");
                }
            }
            Alert(EnumHelper.Alerts.Error, string.Format("{0}, {1}",
                HIResources.Strings.Change_Error,
                errors));
            PopulateUserDropDowns(userViewModel);
            return View(userViewModel);
        }
 public bool Create(ApplicationUser applicationUser, string password)
 {
     IdentityResult result = _userManager.Create(applicationUser, password);
     return result.Succeeded;
 }
 public async Task<bool> SignIn(ApplicationUser user, bool isPersistent)
 {
     _authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     _authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(_userManager));
     return true;
 }