public static async Task<IdentityResult> AddRoleToUser(User user, ApplicationUserManager manager, string authenticationType, string role)
        {
            var oAuthIdentity = await user.GenerateUserIdentityAsync(manager, authenticationType);

            Claim roleClaim = new Claim(ClaimTypes.Role, role);

            IdentityResult result = await manager.AddClaimAsync(user.Id, roleClaim);

            return result;
        }
        public async static void Seed(IRepositoryFactory repoFactory)
        {
            var users = repoFactory.GetRepository<User>("AspNetUsers");

            var allUsers = await users.All();
            if (!allUsers.Any())
            {
                var john = new User("*****@*****.**");
                var userStore = new MongoUserStore<User>(repoFactory);
                var userManager = new ApplicationUserManager(userStore);
                var jimi = new User("*****@*****.**");

                var johnResult = await userManager.CreateAsync(john, "JohnsPassword");
                var jimiResult = await userManager.CreateAsync(jimi, "JimisPassword");

                await userManager.AddClaimAsync(john.Id, new Claim(ClaimTypes.Name, "*****@*****.**"));
                await userManager.AddClaimAsync(john.Id, new Claim(ClaimTypes.Role, "Admin"));

                await userManager.AddClaimAsync(jimi.Id, new Claim(ClaimTypes.Name, "*****@*****.**"));
                await userManager.AddClaimAsync(jimi.Id, new Claim(ClaimTypes.Role, "User"));
            }
        }
        private async Task StoreFacebookAuthToken(ApplicationUser user)
        {
            var claimsIdentity =
                await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (claimsIdentity != null)
            {
                var currentClaims = await UserManager.GetClaimsAsync(user.Id);

                var facebookAccessToken = claimsIdentity.FindAll("FacebookAccessToken").First();
                if (currentClaims.Count <= 0)
                {
                    await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
                }

                else
                {
                    await UserManager.RemoveClaimAsync(user.Id, currentClaims[0]);

                    await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
                }
            }
        }
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            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"));
                }

                var user = new ApplicationUser {
                    UserName     = model.Email,
                    Email        = model.Email,
                    FirstName    = model.FirstName,
                    LastName     = model.LastName,
                    BarCode      = model.BarCode.Trim().ToUpper(),
                    SubscribedAt = DateTime.Now
                };

                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    // Create the LivrETS ID
                    user.LivrETSID = TRIBSTD01Helper.GenerateLivrETSID(user: user);
                    UserManager.Update(user);
                    await UserManager.AddClaimAsync(user.Id, new Claim("FirstName", user.FirstName));

                    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 static async Task ManageClaimsAfterDbUpdate(ApplicationUser userprofile, ClaimsIdentity identity, ApplicationUserManager userManager)
        {
            // Remove the existing claim value of current user from database
            if (identity.FindFirst("NameOfUser") != null)
            {
                await userManager.RemoveClaimAsync(userprofile.Id, identity.FindFirst("NameOfUser"));
            }
            if (identity.FindFirst("ProfilePicture") != null)
            {
                await userManager.RemoveClaimAsync(userprofile.Id, identity.FindFirst("ProfilePicture"));
            }
            if (identity.FindFirst("PackageId") != null)
            {
                await userManager.RemoveClaimAsync(userprofile.Id, identity.FindFirst("PackageId"));
            }

            // Update customized claim
            await userManager.AddClaimAsync(userprofile.Id, new Claim("NameOfUser", userprofile.Name));

            await userManager.AddClaimAsync(userprofile.Id, new Claim("ProfilePicture", !string.IsNullOrEmpty(userprofile.ProfilePicture) ? userprofile.ProfilePicture : ""));

            await userManager.AddClaimAsync(userprofile.Id, new Claim("PackageId", userprofile.PackageId.ToString()));
        }
        public static async Task AddDboClaims(this ApplicationUserManager userManager, ApplicationUser user)
        {
            var claims = await userManager.GetClaimsAsync(user.Id);

            foreach (var userClaim in GetUserClaims(user))
            {
                var old = claims.FirstOrDefault(c => c.Type == userClaim.Type);
                if (old != null)
                {
                    await userManager.RemoveClaimAsync(user.Id, old);
                }

                await userManager.AddClaimAsync(user.Id, userClaim);
            }
        }
Beispiel #7
0
        private async Task StoreFacebookAuthToken(ApplicationUser user)
        {
            var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (claimsIdentity != null)
            {
                // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim
                var currentClaims = await UserManager.GetClaimsAsync(user.Id);

                var facebookAccessToken = claimsIdentity.FindAll("FacebookAccessToken").First();
                if (currentClaims.Count() <= 0)
                {
                    await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
                }
            }
        }
Beispiel #8
0
        private async Task InsertAccessToken(ApplicationUser user, string loginProvider)
        {
            var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (externalIdentity != null)
            {
                var userClaims = await UserManager.GetClaimsAsync(user.Id);

                var accessTokenClaim = externalIdentity.FindAll(loginProvider + "_AccessToken").First();

                if (userClaims.Count() <= 0)
                {
                    await UserManager.AddClaimAsync(user.Id, accessTokenClaim);
                }
            }
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = UserManager.Find(model.Email, model.Password);

            if (user != null)
            {
                var UserClaim = user.Claims.AsEnumerable().ToList();

                foreach (IdentityUserClaim claim in UserClaim)
                {
                    await UserManager.RemoveClaimAsync(user.Id, new Claim(claim.ClaimType, claim.ClaimValue));
                }
                var UserClaims = db.tblGroupActions.AsEnumerable().Where(s => s.tblGroups.tblUserGroup.Any(l => l.FK_User == user.Id))
                                 .Select(k => new Claim(k.ActionName, k.ActionName)).ToList();

                foreach (Claim cliam in UserClaims)
                {
                    await UserManager.AddClaimAsync(user.Id, cliam);
                }
            }
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : true);

            switch (result)
            {
            case SignInStatus.Success:

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Beispiel #10
0
        public async Task <IHttpActionResult> CheckConnectionPath(GetConnectionPathsModel model)
        {
            var result = _connectionPathService.ConnectionItemCheck(model);

            if (result)
            {
                //add popcorn points
                var userId       = 0;
                var userIdString = User.Identity.GetUserId();
                Int32.TryParse(userIdString, out userId);
                var claims       = _applicationUserManager.GetClaimsAsync(userId);
                var popcorn      = claims.Result.FirstOrDefault(x => x.Type == "popcorn");
                var popcornPoint = popcorn?.Value;
                _applicationUserManager.RemoveClaim(userId, popcorn);
                await _applicationUserManager.AddClaimAsync(userId, new Claim("popcorn", popcornPoint + 10));
            }
            return(Ok(result));
        }
Beispiel #11
0
        public string postRegister(RegisterViewModel model)
        {
            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["AutoRegistration:Enabled"]))
            {
                return(JsonConvert.SerializeObject(new { error = true, errorMessage = "auto-rgeistration-disabled" }));
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = UserManager.CreateAsync(user, model.Password).Result;
                if (result.Succeeded)
                {
                    //create space and add space to user
                    Space space = new Space();
                    MySqlIdentityDbContext db = new MySqlIdentityDbContext();
                    db.Spaces.Add(space);
                    db.SaveChanges();
                    var addClaimResult = UserManager.AddClaimAsync(UserManager.FindByEmail(user.Email).Id, new Claim("SpaceId", space.Id)).Result;

                    // Add privilèges via role specify in the configuration to the user
                    addUserInRole(user);

                    // Send an email with the link to confirm email async
                    if (Convert.ToBoolean(ConfigurationManager.AppSettings["AutoRegistration:ConfirmationEmail:Enabled"]))
                    {
                        string code = UserManager.GenerateEmailConfirmationTokenAsync(user.Id).Result;
                        Task.Run(() => sendConfirmationEmail(user, code));
                    }

                    //Log in user
                    SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    return(JsonConvert.SerializeObject(new { error = false, user = user }));
                }
                return(JsonConvert.SerializeObject(new { error = true, errorMessage = "creationIssue" }));
            }

            // If we got this far, something failed, redisplay form
            return(JsonConvert.SerializeObject(new { error = true, errorMessage = "dataIssue" }));
        }
Beispiel #12
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email    = model.Email
                };
                string userRoles = null;
                List <SelectListItem> userClaims = model.UserClaims.Where(c => c.Selected).ToList();

                foreach (var item in userClaims)
                {
                    userRoles = item.Value;
                }


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

                var claimaddresult = await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, userRoles));//"newCustomClaim", "claimValue"

                //await UserManager.AddToRoleAsync(user.Id, "CanEdit");

                if (result.Succeeded && claimaddresult.Succeeded)
                {
                    //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("Index", "Home");
                    return(RedirectToAction("Login", "Account"));
                }
                AddErrors(result, claimaddresult);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #13
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // No cuenta los errores de inicio de sesión para el bloqueo de la cuenta
            // Para permitir que los errores de contraseña desencadenen el bloqueo de la cuenta, cambie a shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                // Obtiene usuario logeado
                var user  = UserManager.FindByEmail(model.Email);
                var jUser = JsonConvert.SerializeObject(new CurrentUser
                {
                    Email     = user.Email,
                    Name      = user.Name,
                    LastName  = user.LastName,
                    UserId    = user.Id,
                    UserName  = user.UserName,
                    ShortName = user.ShortName
                });

                // Agrego el claim con userData
                await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.UserData, jUser));

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Intento de inicio de sesión no válido.");
                return(View(model));
            }
        }
Beispiel #14
0
        private async Task StoreAuthTokenClaims(ApplicationUser user)
        {
            ClaimsIdentity claimsIdentity =
                await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (claimsIdentity != null)
            {
                var currentClaims = await UserManager.GetClaimsAsync(user.Id);

                var tokenClaims = claimsIdentity.Claims.Where(c => c.Type.StartsWith("urn:tokens"));
                foreach (var tokenClaim in tokenClaims)
                {
                    if (!currentClaims.Contains(tokenClaim))
                    {
                        await UserManager.AddClaimAsync(user.Id, tokenClaim);
                    }
                }
            }
        }
Beispiel #15
0
        private async Task StoreWordpressToken(ApplicationUser user)
        {
            var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (claimsIdentity != null)
            {
                // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim
                var currentClaims = await UserManager.GetClaimsAsync(user.Id);

                var wordpressToken = claimsIdentity.Claims.Where(a => a.Type.Contains("wordpress:access_token")).FirstOrDefault();
                if (wordpressToken != null)
                {
                    if (currentClaims.Count(a => a.Type.Contains("wordpress:access_token")) > 0)
                    {
                        await UserManager.RemoveClaimAsync(user.Id, wordpressToken);
                    }
                    await UserManager.AddClaimAsync(user.Id, wordpressToken);
                }
            }
        }
Beispiel #16
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userdetail = new PersonalInformation();
                userdetail.Fullname  = model.Fullname;
                userdetail.Extension = model.Extension;
                userdetail.Company   = model.Company;
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, PersonalInformation = userdetail
                };

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

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

                    //ClaimType Role as Admin = Role as Admin
                    //It works the same
                    var claimFullname = new Claim("Fullname", userdetail.Fullname);
                    //var claimContact = new Claim(ClaimTypes.Role, "Contact");

                    await UserManager.AddClaimAsync(user.Id, claimFullname);

                    //var addClaimResult = await UserManager.AddClaimAsync(user.Id, claimHomeAll);

                    // 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
            return(View(model));
        }
Beispiel #17
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (Request.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = model.UserName, Email = model.Email
                };
                if (model.Picture != null)
                {
                    using (var stream = model.Picture.InputStream)
                    {
                        var memoryStream = stream as MemoryStream;

                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            await stream.CopyToAsync(memoryStream);
                        }
                        user.Picture = memoryStream.ToArray();
                    }
                }
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "User"));

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

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #18
0
        private async Task StoreClaimTokens(ApplicationUser user)
        {
            ClaimsIdentity claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (claimsIdentity != null)
            {
                var currentClaims = await UserManager.GetClaimsAsync(user.Id);

                var tokenClaims = claimsIdentity.Claims.Where(c => c.Type.StartsWith("urn:tokens:"));

                foreach (var tokenClaim in tokenClaims)
                {
                    var currentClaim = currentClaims.SingleOrDefault(x => x.Type == tokenClaim.Type);
                    if (currentClaims != null)
                    {
                        await UserManager.RemoveClaimAsync(user.Id, currentClaim);
                    }
                    await UserManager.AddClaimAsync(user.Id, tokenClaim);
                }
            }
        }
Beispiel #19
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var user = await UserManager.FindByNameAsync(model.Email);

            var t = await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FirstName + " " + user.LastName));

            // for user full name
            var userClaims = User as ClaimsPrincipal;
            var identity   = userClaims.Identity as ClaimsIdentity;

            identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName + " " + user.LastName));

            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                Session["Userid"] = user.FirstName + " " + user.LastName.ToString();
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Beispiel #20
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                var currentUser = UserManager.FindByEmail(model.Email);

                var jUser = JsonConvert.SerializeObject(new CurrentUser {
                    UserId   = currentUser.Id,
                    Name     = currentUser.Email,
                    UserName = currentUser.Email,
                });

                await UserManager.AddClaimAsync(currentUser.Id, new Claim(ClaimTypes.UserData, jUser));

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Beispiel #21
0
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

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

            if (!ModelState.IsValid)
            {
                await LoadAsync(user);

                return(Page());
            }

            var identity = await _userClaimsPrincipalFactory.CreateAsync(user);

            var currentClaim = identity.Claims.FirstOrDefault(c => c.Type == "permission" && c.Value == "can_read");

            if (Input.CanRead != (currentClaim?.Value == "can_read"))
            {
                if (Input.CanRead)
                {
                    await _userManager.AddClaimAsync(user, new Claim("permission", "can_read"));
                }
                else
                {
                    await _userManager.RemoveClaimAsync(user, currentClaim);
                }
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Your permissions have been updated";
            return(RedirectToPage());
        }
Beispiel #22
0
        private async Task SeedAsync(ApplicationDbContext context)
        {
            if (!context.Roles.Any(r => r.Name == "AppAdmin"))
            {
                var store   = new CustomRoleStore(context);
                var manager = new ApplicationRoleManager(store);
                var role    = new AppRole {
                    Name = "AppAdmin"
                };

                await manager.CreateAsync(role);

                var roleGreo = new AppRole {
                    Name = "AppGreo"
                };
                await manager.CreateAsync(roleGreo);
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new CustomUserStore(context);
                var manager = new ApplicationUserManager(store);
                var user    = new AppUser
                {
                    FirstName            = "Dmitry", LastName = "Chumak",
                    UserName             = "******",
                    SubdivisionId        = 0,
                    Email                = "*****@*****.**",
                    EmailConfirmed       = true,
                    PhoneNumber          = "0123456789",
                    PhoneNumberConfirmed = true
                };


                await manager.CreateAsync(user, "Qwerty123_");



                //Add User To Role
                await manager.AddToRoleAsync(user.Id, "AppAdmin");

                ////Add User Claims
                await manager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, "A Person"));

                await manager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Gender, "Man"));

                await manager.AddClaimAsync(user.Id, new Claim(ClaimTypes.DateOfBirth, "01.01.2001"));
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store     = new CustomUserStore(context);
                var manager   = new ApplicationUserManager(store);
                var userGreo1 = new AppUser
                {
                    FirstName            = "greo401",
                    LastName             = "greo401",
                    UserName             = "******",
                    SubdivisionId        = 1,
                    Email                = "*****@*****.**",
                    EmailConfirmed       = true,
                    PhoneNumber          = "0123456789",
                    PhoneNumberConfirmed = true
                };


                await manager.CreateAsync(userGreo1, "Greo401_");

                //Add User To Role
                await manager.AddToRoleAsync(userGreo1.Id, "AppGreo");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store     = new CustomUserStore(context);
                var manager   = new ApplicationUserManager(store);
                var userGreo2 = new AppUser
                {
                    FirstName            = "greo402",
                    LastName             = "greo402",
                    UserName             = "******",
                    SubdivisionId        = 2,
                    Email                = "*****@*****.**",
                    EmailConfirmed       = true,
                    PhoneNumber          = "0123456789",
                    PhoneNumberConfirmed = true
                };


                await manager.CreateAsync(userGreo2, "Greo402_");

                //Add User To Role
                await manager.AddToRoleAsync(userGreo2.Id, "AppGreo");
            }
        }
        private async Task SeedAsync(ApplicationDbContext context)
        {
            if (!context.Roles.Any(r => r.Name == "OSBB_Admin"))
            {
                var store   = new CustomerRoleStore(context);
                var manager = new ApplicationRoleManager(store);
                var role    = new AppRole {
                    Name = "OSBB_Admin"
                };

                await manager.CreateAsync(role);
            }

            if (!context.Roles.Any(r => r.Name == "OSBB_User"))
            {
                var store   = new CustomerRoleStore(context);
                var manager = new ApplicationRoleManager(store);
                var role    = new AppRole {
                    Name = "OSBB_User"
                };

                await manager.CreateAsync(role);
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new CustomerUserStore(context);
                var manager = new ApplicationUserManager(store);
                var user    = new AppUser
                {
                    UserName             = "******",
                    Email                = "*****@*****.**",
                    EmailConfirmed       = true,
                    PhoneNumber          = "+380974141759",
                    PhoneNumberConfirmed = true,
                    ApartmentNumber      = 0
                };

                await manager.CreateAsync(user, "pa$$w0rd");

                await manager.AddToRoleAsync(user.Id, "OSBB_Admin");

                await manager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Name, "Admin"));
            }

            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                var store   = new CustomerUserStore(context);
                var manager = new ApplicationUserManager(store);
                var user    = new AppUser
                {
                    UserName             = "******",
                    Email                = "*****@*****.**",
                    EmailConfirmed       = true,
                    PhoneNumber          = "+380974141759",
                    PhoneNumberConfirmed = true,
                    ApartmentNumber      = 1000
                };

                await manager.CreateAsync(user, "1qazwsx");

                await manager.AddToRoleAsync(user.Id, "OSBB_User");

                await manager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Name, "User"));
            }
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            bool flag    = false;
            var  context = new IdentityDbContext();
            var  Roles   = m.RoleClaimGetAllStrings();
            var  form    = new RegisterFormViewModel();
            var  obj     = context.Users.ToList();

            foreach (var item in obj)
            {
                if (model.Email.CompareTo(item.Email) == 0)
                {
                    form.RoleList        = new MultiSelectList(Roles);
                    ViewBag.ErrorMessage = "Email is already Taken!";
                    return(View(form));
                }
                else if (model.UserId.CompareTo(item.UserName) == 0)
                {
                    form.RoleList        = new MultiSelectList(Roles);
                    ViewBag.ErrorMessage = "User Name is already Taken!";
                    return(View(form));
                    //return Content("<script language='javascript' type='text/javascript'>alert('User Name already taken!');</script>");
                }
                else
                {
                }
            }
            if (!flag)
            {
                var user = new ApplicationUser {
                    UserName = model.UserId, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // 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>");

                    //Add Claims

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, model.Email));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "User"));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, model.LastName));


                    foreach (var role in model.Roles)
                    {
                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, role.Trim()));
                    }

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

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

            // If we got this far, something failed, redisplay form
            form.RoleList = new MultiSelectList(Roles);
            return(View(form));
        }
Beispiel #25
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Obtenez des informations sur l’utilisateur auprès du fournisseur de connexions externe
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                // - [10007] - ADD: Social network picture
                ViewBag.LoginProvider = info.Login.LoginProvider;
                //if (model.Email == info.Email || info.Login.LoginProvider == "Twitter" || info.Login.LoginProvider == "Facebook")
                //{

                var user = new ApplicationUser {
                    Pseudo = info.DefaultUserName, UserName = info.DefaultUserName, Email = model.Email
                };
                user.RegistrationDate = DateTime.Now;
                user.AvatarUrl        = "~/Content/Avatars/BlankPhoto.jpg";
                if (info.Login.LoginProvider == "Google")
                {
                    var     imageJSON = info.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:google:image")).Value;
                    JObject o         = JObject.Parse(imageJSON);
                    user.AvatarUrl = o["url"].ToString();
                    user.UseSocialNetworkPicture = true;
                }
                if (info.Login.LoginProvider == "Microsoft")
                {
                    var microsoftAccountId = info.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:microsoftaccount:id")).Value;
                    user.AvatarUrl = string.Format("https://apis.live.net/v5.0/{0}/picture", microsoftAccountId);
                    user.UseSocialNetworkPicture = true;
                }
                if (info.Login.LoginProvider == "Facebook")
                {
                    var facebookAccountId = info.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:facebook:id")).Value;
                    user.AvatarUrl = string.Format("http://graph.facebook.com/{0}/picture", facebookAccountId);
                    user.UseSocialNetworkPicture = true;
                }
                if (info.Login.LoginProvider == "Twitter")
                {
                    var twitterScreenname = info.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:twitter:screenname")).Value;
                    user.AvatarUrl = string.Format("https://twitter.com/{0}/profile_image?size=original", twitterScreenname);
                    user.UseSocialNetworkPicture = true;
                }
                if (info.Login.LoginProvider == "GitHub")
                {
                    var githubId = info.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:github:id")).Value;
                    user.AvatarUrl = string.Format("https://avatars.githubusercontent.com/u/{0}?v=3", githubId);
                    user.UseSocialNetworkPicture = true;
                }

                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        // Add user to role Member
                        await UserManager.AddToRoleAsync(user.Id, "Member");

                        await UserManager.AddToRoleAsync(user.Id, "CanEdit");

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

                        const string ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
                        foreach (var c in info.ExternalIdentity.Claims.Where(c => !c.Type.StartsWith(ignoreClaim)))
                        {
                            if (user.Claims.All(t => t.ClaimType != c.Type))
                            {
                                await UserManager.AddClaimAsync(user.Id, c);
                            }
                        }
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
                //}
                //else
                //{
                //    var ir = new IdentityResult("Bad Email");
                //    AddErrors(ir);
                //}
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Beispiel #26
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                // If we got this far, something failed, redisplay form
                return(View(model));
            }

            // Before attempting to add the user, let's validate the claims

            // Reference to the manager
            Manager m = new Manager();

            // Status field to indicate whether the requested claims are allowed
            // The first "not found" or mal-formed claim will change it to "false"
            bool canRegister = true;

            // Look at the role claims first

            // Initialize
            var roles = string.IsNullOrEmpty(model.Roles) ? "" : model.Roles.Trim();
            // Attempt to convert into a string array
            var roleList = roles.Split(',');

            foreach (var roleClaimValue in roleList)
            {
                if (m.AppClaimGetByMatch("role", roleClaimValue.Trim().ToLower()) == null)
                {
                    canRegister = false;
                }
            }

            // Next, look at the custom claims

            // Initialize
            var customClaims = string.IsNullOrEmpty(model.CustomClaims) ? "" : model.CustomClaims.Trim();
            // Attempt to convert into a string array
            var customClaimList = customClaims.Split(',');

            foreach (var customClaimValue in customClaimList)
            {
                // Each custom claim is in the format Type=Value
                // So, we'll use string-split to help us with this task
                var claim = customClaimValue.Split('=');

                // Make sure we can continue
                if (claim.Length == 2)
                {
                    var claimType  = claim[0].Trim();
                    var claimValue = claim[1].Trim();

                    // Now, attempt to find a matching claim (similar to above, in the role claim code block)
                    if (m.AppClaimGetByMatch(claimType, claimValue) == null)
                    {
                        canRegister = false;
                    }
                }
                else
                {
                    canRegister = false;
                }
            }

            if (canRegister)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

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

                if (result.Succeeded)
                {
                    // Add claims
                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, model.Email));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, model.GivenName));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, model.Surname));

                    await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "User"));

                    // Role claims processing - roleList - they were validated above

                    foreach (var roleClaimValue in roleList)
                    {
                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, roleClaimValue.Trim()));
                    }

                    // Custom claims processing - customClaimList - they were validated above

                    foreach (var customClaimValue in customClaimList)
                    {
                        var claim      = customClaimValue.Split('=');
                        var claimType  = claim[0].Trim();
                        var claimValue = claim[1].Trim();

                        await UserManager.AddClaimAsync(user.Id, new Claim(claimType, claimValue));
                    }

                    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"));
                } // if (result.Succeeded)

                AddErrors(result);
            } // if (canRegister)

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task<bool> InsertOrUpdate(IdentityUserViewModel model, ApplicationUserManager userManager)
        {

            var user = await userManager.FindByIdAsync(model.Id);

            if (user == null)
            {
                user = new ApplicationUser();
                user.Assign(model);


                var result = await userManager.CreateAsync(user, "1234567");
                if (!result.Succeeded) return false;
                model.Id = user.Id;
            }
            else
            {
                user.Email = model.Email;
                user.UserName = model.UserName;
                user.DUI = model.DUI;
                user.PhoneNumber = model.PHONE_2;
                user.ADDRESS = model.ADDRESS;
                user.Category = model.Category;
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.DUI = model.DUI;
                user.PHONE_2 = model.PHONE_2;
                user.ProfilePicture = model.ProfilePicture;
                user.CenterId = model.CenterId;
                //user.Address = model.Address;
                //user.FirstName = model.FirstName;
                //user.LastName = model.LastName;
                //user.DocumentNum = model.DocumentNum;
                //user.ProfilePicture = model.ProfilePicture;
                await userManager.UpdateAsync(user);
            }

            if (model.ForceChangePassword)
            {
                var tok = await userManager.GeneratePasswordResetTokenAsync(model.Id);

                var result = await userManager.ResetPasswordAsync(model.Id, tok, model.Password);

                if (!result.Succeeded) return false;
            }
            var roles = await userManager.GetRolesAsync(model.Id);

            if (!roles.Any() && !string.IsNullOrEmpty(model.Role))
            {
                var res = await userManager.AddToRoleAsync(model.Id, model.Role);
            }

            if (roles.All(r => r != model.Role) && roles.Any())
            {
                var result = await userManager.AddToRoleAsync(model.Id, model.Role);
            }
            roles.Where(r => r != model.Role).ToList().ForEach(role => userManager.RemoveFromRole(model.Id, role));

            if (model.CenterId != 0)
            {

                var claim = await Context.UserClaims.FirstOrDefaultAsync(c => c.UserId == user.Id && c.ClaimType == "CenterId");

                var claims = await userManager.GetClaimsAsync(user.Id);
                if (claim != null)
                {
                    claim.ClaimValue = model.CenterId.Value.ToString();
                    await Context.SaveChangesAsync();
                }
                else
                {
                    await userManager.AddClaimAsync(model.Id, new System.Security.Claims.Claim("CenterId", model.CenterId.ToString()));
                }
            }


            return true;
        }
 public async Task <IdentityResult> AddClaimForUserAsync(string userId, Claim claim)
 {
     return(await _userManager.AddClaimAsync(userId, claim));
 }
        public async Task<IdentityResult> UpdateRoles(JObject roles)
        {
            string userId = ((dynamic)roles).Id.Value;
            string roleId = ((dynamic)roles).RoleId.Value;
            string roleName = ((dynamic)roles).RoleName.Value;

            IdentityResult result = null;

            #region TODO: Remove unused commented code
            //IdentityRole role = (from r in _contextProvider.Context.Roles where r.Id == roleId select r).FirstOrDefault();
            //var user = _contextProvider.Context.Users.Where(x => x.Id == userId).FirstOrDefault();
            //if (user.Roles.Any(x => x.RoleId == roleId))
            //{
            //    // User is in the Admin Role

            //}
            //else
            //{

            //    //User is not in the Admin Role
            //}

            //var role = (from r in _contextProvider.Context.Roles where r.Id == roleId select r).FirstOrDefault();
            //var users = _contextProvider.Context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(role.Id)).ToList();
            //if (users.Find(x => x.Id == userId) != null)
            //{
            //    // User is in the Admin Role
            //}
            //else
            //{

            //    //User is not in the Admin Role
            //}
            #endregion

            var userStore = new UserStore<ApplicationUser>(_contextProvider.Context);
            var userManager = new ApplicationUserManager(userStore);

            var roleStore = new RoleStore<IdentityRole>(_contextProvider.Context);
            var roleManager = new ApplicationRoleManager(roleStore);

            ApplicationUser user = await userManager.FindByIdAsync(userId);//.ConfigureAwait(false);

            IList<string> role = new List<string>();
            role.Add(roleName);
            if (user.Roles.Any(x => x.RoleId == roleId))
            {
                //remove user and roll mapping
                result = await userManager.RemoveUserFromRolesAsync(userId, role).ConfigureAwait(false);
                result = await userManager.RemoveClaimAsync(userId, new Claim(IdentityConstants.ClaimTypes.Role, roleName));
            }
            else
            {
                result = await userManager.AddUserToRolesAsync(userId, role).ConfigureAwait(false);
                result = await userManager.AddClaimAsync(userId, new Claim(IdentityConstants.ClaimTypes.Role, roleName));

                //User is not in the Admin Role
            }
            #region TODO: Remove unused commented code
            //if (user.Roles.Count > 0)
            //{
            //    var roleExists = user.Roles.First(x => x.RoleId == roleId);
            //    if (roleExists != null)
            //    {
            //        //remove user and roll mapping
            //        //result = await userManager.RemoveFromRoleAsync(userId, roleId).ConfigureAwait(false);
            //        //remove user and its claim
            //        //Claim c = new Claim();
            //        //c.Type = "role";
            //        //c.Value
            //        //result = await userManager.RemoveClaimAsync(userId,new Claim() { })

            //    }
            //    else
            //    {
            //        //result = await userManager.AddToRoleAsync(userId,roleId);
            //    }

            //}
            #endregion
            return await userManager.UpdateAsync(user).ConfigureAwait(false);
        }
        // Load user accounts
        public static async void LoadUserAccounts()
        {
            // Get a reference to the objects we need
            var ds          = new ApplicationDbContext();
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(ds));

            // Add the user(s) that the app needs when loaded for the first time
            // Change any of the data below to better match your app's needs
            if (userManager.Users.Count() == 0)
            {
                // User account manager...
                var uam = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                var uamResult = await userManager.CreateAsync(uam, "Password123!");

                if (uamResult.Succeeded)
                {
                    // Add claims
                    await userManager.AddClaimAsync(uam.Id, new Claim(ClaimTypes.Email, "*****@*****.**"));

                    await userManager.AddClaimAsync(uam.Id, new Claim(ClaimTypes.Role, "UserAccountManager"));

                    await userManager.AddClaimAsync(uam.Id, new Claim(ClaimTypes.GivenName, "User Account"));

                    await userManager.AddClaimAsync(uam.Id, new Claim(ClaimTypes.Surname, "Manager"));
                }

                // Developer/programmer...
                var dev = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                var devResult = await userManager.CreateAsync(dev, "Password123!");

                if (devResult.Succeeded)
                {
                    // Add claims
                    await userManager.AddClaimAsync(dev.Id, new Claim(ClaimTypes.Email, "*****@*****.**"));

                    await userManager.AddClaimAsync(dev.Id, new Claim(ClaimTypes.Role, "Developer"));

                    await userManager.AddClaimAsync(dev.Id, new Claim(ClaimTypes.GivenName, "App"));

                    await userManager.AddClaimAsync(dev.Id, new Claim(ClaimTypes.Surname, "Developer"));
                }

                // Me...
                var mmarangoni1 = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                var mmarangoni1Result = await userManager.CreateAsync(mmarangoni1, "Password123!");

                if (mmarangoni1Result.Succeeded)
                {
                    // Add claims
                    await userManager.AddClaimAsync(mmarangoni1.Id, new Claim(ClaimTypes.Email, "*****@*****.**"));

                    await userManager.AddClaimAsync(mmarangoni1.Id, new Claim(ClaimTypes.Role, "Developer"));

                    await userManager.AddClaimAsync(mmarangoni1.Id, new Claim(ClaimTypes.GivenName, "Matthew"));

                    await userManager.AddClaimAsync(mmarangoni1.Id, new Claim(ClaimTypes.Surname, "Marangoni"));
                }
            }
        }
Beispiel #31
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                CUIT cuit = new CUIT(model.Cuit);
                if (cuit.EsValido)
                {
                    var empresaAux = db.Empresa.Where(x => x.Cuit == model.Cuit).FirstOrDefault();
                    if (empresaAux == null)
                    {
                        var user = new ApplicationUser {
                            UserName = model.Cuit, Email = model.Email
                        };
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            Empresa empresa = new Empresa();
                            empresa.RazonSocial      = model.RazonSocial;
                            empresa.NombreFantasia   = model.NombreFantasia;
                            empresa.Cuit             = model.Cuit;
                            empresa.IdActividad      = model.IdActividad;
                            empresa.IdLocalidad      = model.IdLocalidad;
                            empresa.Calle            = model.Calle;
                            empresa.Altura           = model.Altura;
                            empresa.TelefonoFijo     = model.TelefonoFijo;
                            empresa.TelefonoCelular  = model.TelefonoCelular;
                            empresa.Email            = model.Email;
                            empresa.FechaAltaEmpresa = DateTime.Today;
                            db.Empresa.Add(empresa);
                            db.SaveChanges();

                            var currentUser = UserManager.FindByName(user.UserName);

                            var roleresult = UserManager.AddToRole(currentUser.Id, "Empresa");

                            await UserManager.AddClaimAsync(user.Id, new Claim("IdEmpresa", (empresa.IdEmpresa).ToString()));

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

                            // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite https://go.microsoft.com/fwlink/?LinkID=320771
                            // Enviar correo electrónico con este vínculo
                            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, "Confirmar cuenta", "Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>");

                            var emailBody = "Hola " + empresa.RazonSocial + "!<br /> Para confirmar la cuenta, haga clic <a href=\"" + callbackUrl + "\">aquí</a>";
                            try
                            {
                                //Configuring webMail class to send emails
                                //gmail smtp server
                                WebMail.SmtpServer = "mail.xindicoweb.com.ar";
                                //gmail port to send emails
                                WebMail.SmtpPort = 587;
                                WebMail.SmtpUseDefaultCredentials = true;
                                //sending emails with secure protocol
                                //WebMail.EnableSsl = true;
                                //EmailId used to send emails from application
                                WebMail.UserName = "******";
                                WebMail.Password = "******";

                                //Sender email address.
                                WebMail.From = "*****@*****.**";

                                //Send email
                                WebMail.Send(to: user.Email, subject: "Confirmar Cuenta", body: emailBody, isBodyHtml: true);
                            }
                            catch (Exception e)
                            {
                                var AuthenticationManagerAux = HttpContext.GetOwinContext().Authentication;
                                AuthenticationManagerAux.SignOut();

                                db.Empresa.Remove(empresa);
                                db.SaveChanges();
                                UserManager.Delete(user);
                            }

                            var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
                            AuthenticationManager.SignOut();

                            return(RedirectToAction("RegisterSuccess"));
                        }
                        AddErrors(result);
                    }
                    else
                    {
                        ModelState.AddModelError("Cuit", "Ya Existe una empresa registrada con ese Cuit");
                    }
                }
                else
                {
                    ModelState.AddModelError("Cuit", "Cuit ingresado no es valido");
                }
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            ViewBag.IdActividad = new SelectList(db.Actividad.OrderBy(x => x.Nombre), "IdActividad", "Nombre", model.IdActividad);
            var localidad = db.Localidad.Find(model.IdLocalidad);

            ViewBag.IdProvincia = new SelectList(db.Provincia, "IdProvincia", "Nombre", localidad.IdProvincia);
            var localidades = db.Localidad.OrderBy(x => x.Nombre);

            foreach (var loc in localidades)
            {
                loc.Nombre = loc.Nombre + " (" + loc.CodPostal + ")";
            }
            ViewBag.IdLocalidad = new SelectList(localidades, "IdLocalidad", "Nombre", model.IdLocalidad);

            return(View(model));
        }
Beispiel #32
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            // Verify that the user is an Employee...
            var m = new Manager();

            if (ModelState.IsValid)
            {
                if (m.IsNewUserAnEmployee(model.Email))
                {
                    // Attempt to register the user...

                    // Configure all the 'required' properties in the following statement
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName
                    };

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

                    if (result.Succeeded)
                    {
                        // ##################################################

                        // Add claims

                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, model.Email));

                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));

                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, model.LastName));

                        await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "Employee"));

                        // Configure the organization unit

                        m.ConfigureUserWithOU(model.Email, model.OU);

                        // ##################################################

                        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);
                }
                else
                {
                    ModelState.AddModelError("", "This person is not an Employee, and cannot create an account.");
                }
            }

            // If we got this far, something failed, redisplay form

            AutoMapper.Mapper.CreateMap <RegisterViewModel, RegisterViewModelForm>();

            //create and configure a register form
            var registerForm = AutoMapper.Mapper.Map <RegisterViewModelForm>(model);
            var ous          = m.GetAllOUs();


            registerForm.OUList = new SelectList(ous, "OUName", "OUName", model.OU);
            //registerForm.RolesList = new MultiSelectList(new List<string> { "Student", "Teacher", "Coordinator" }, model.Roles);

            return(View(registerForm));
        }
        // Load user accounts
        public static async void LoadUserAccounts()
        {
            // Get a reference to the objects we need
            var ds          = new ApplicationDbContext();
            var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(ds));

            // Add the user(s) that the app needs when loaded for the first time
            // Change any of the data below to better match your app's needs
            if (userManager.Users.Count() == 0)
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                var result = await userManager.CreateAsync(user, "Password123!");

                if (result.Succeeded)
                {
                    // Add claims
                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, "*****@*****.**"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "UserAccountAdministrator"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, "User Account"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, "Administrator"));
                }

                user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                result = await userManager.CreateAsync(user, "Password123!");

                if (result.Succeeded)
                {
                    // Add claims
                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, "*****@*****.**"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "Student"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, "Student"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, "One"));
                }

                user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                result = await userManager.CreateAsync(user, "Password123!");

                if (result.Succeeded)
                {
                    // Add claims
                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Email, "*****@*****.**"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, "Student"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.GivenName, "Student"));

                    await userManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Surname, "Two"));
                }
            }
        }
Beispiel #34
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var curruser = await UserManager.FindByNameAsync(model.Email);

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

                if (result == SignInStatus.Success)
                {
                    var user = await UserManager.FindByNameAsync(model.Email);

                    // Check if email is confirmed or not !
                    if (!await UserManager.IsEmailConfirmedAsync(user.Id))
                    {
                        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                        //_logger.LogWarning(2, "User account not verified yet.");

                        return(RedirectToAction("UnConfirmed", "Account", new { uid = user.Id }));
                        //return RedirectToAction(nameof(AccountController.UnConfirmed), "Account", new { uid = user.Id });
                        //return RedirectToAction("UnConfirmed", new { user = user });
                    }

                    //add other claims if any
                    await UserManager.AddClaimAsync(user.Id, new Claim("OrgId", user.OrganizationId.ToString()));

                    //_logger.LogInformation(1, "User logged in.");
                    return(RedirectToLocal(returnUrl));
                }
                //if (result.RequiresTwoFactor)
                //{
                //	return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                //}
                if (result == SignInStatus.LockedOut)
                {
                    //_logger.LogWarning(2, "User account locked out.");
                    return(View("Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

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



            //if (!ModelState.IsValid)
            //{
            //	return View(model);
            //}

            //// This doesn't count login failures towards account lockout
            //// To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //	case SignInStatus.Success:
            //		return RedirectToLocal(returnUrl);
            //	case SignInStatus.LockedOut:
            //		return View("Lockout");
            //	case SignInStatus.RequiresVerification:
            //		return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //	case SignInStatus.Failure:
            //	default:
            //		ModelState.AddModelError("", "Invalid login attempt.");
            //		return View(model);
            //}
        }