public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Email, model.Password);
                if (user != null)
                {


                    await SignInAsync(user, model.RememberMe);

                  
                    ApplicationDbContext context = new ApplicationDbContext();
                   
                     var UserManager1 = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                     var UserID = UserManager.FindByEmail(model.Email).Id;
                     if (UserManager1.IsInRole(UserID, "Admin"))
                     {
                         return RedirectToAction("Index", "Home");
                     }
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
示例#2
0
 public static bool IsInRole(string user, string role)
 {
     using (TasklyDbContext db = new TasklyDbContext())
     {
         using (var store = new UserStore<TasklyUser>(db))
         {
             using (var manager = new UserManager<TasklyUser>(store))
             {
                 return manager.IsInRole(user, role);
             }
         }
     }
 }
        public ActionResult DeleteRoleForUser(string userName, string roleName)
        {
            List<string> userRoles;
            List<string> roles;
            List<string> users;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                roles = (from r in roleManager.Roles select r.Name).ToList();

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

                users = (from u in userManager.Users select u.UserName).ToList();

                var user = userManager.FindByName(userName);
                if (user == null)
                    throw new Exception("User not found!");

                if (userManager.IsInRole(user.Id, roleName))
                {
                    userManager.RemoveFromRole(user.Id, roleName);
                    context.SaveChanges();

                    ViewBag.ResultMessage = "Role removed from this user successfully !";
                }
                else
                {
                    ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                }

                var userRoleIds = (from r in user.Roles select r.RoleId);
                userRoles = (from id in userRoleIds
                             let r = roleManager.FindById(id)
                             select r.Name).ToList();
            }

            ViewBag.RolesForThisUser = userRoles;
            ViewBag.Roles = new SelectList(roles);
            ViewBag.Users = new SelectList(users);
            return View("RoleAddToUser");
        }
        public ActionResult RoleAddToUser(string roleName, string userName)
        {
            List<string> roles;
            List<string> users;
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

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

                users = (from u in userManager.Users select u.UserName).ToList();

                var user = userManager.FindByName(userName);
                if (user == null)
                    throw new Exception("User not found!");

                var role = roleManager.FindByName(roleName);
                if (role == null)
                    throw new Exception("Role not found!");

                if (userManager.IsInRole(user.Id, role.Name))
                {
                    ViewBag.ResultMessage = "This user already has the role specified !";
                }
                else
                {
                    userManager.AddToRole(user.Id, role.Name);
                    context.SaveChanges();

                    ViewBag.ResultMessage = "Username added to the role succesfully !";
                }

                roles = (from r in roleManager.Roles select r.Name).ToList();
            }

            ViewBag.Roles = new SelectList(roles);
            ViewBag.Users = new SelectList(users);
            return View();
        }
示例#5
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdUserResult;
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            DateTime dateValue;
            bool noDate = false;
            if (!DateTime.TryParse(BirthdayRegister.Text, out dateValue))
                noDate = true;
            ApplicationUser user;
            if (noDate)
            {
                user = new ApplicationUser()
                {
                    UserName = EmailRegister.Text,
                    Email = EmailRegister.Text,
                    NIF = NIFRegister.Text,
                    FullName = FullNameRegister.Text
                };
            } else
            {
                user = new ApplicationUser()
                {
                    UserName = EmailRegister.Text,
                    Email = EmailRegister.Text,
                    BirthDate = dateValue,
                    NIF = NIFRegister.Text,
                    FullName = FullNameRegister.Text
                };
            }

            try
            {
                IdentityResult result = manager.Create(user, PasswordRegister.Text);

                if (result.Succeeded)
                {
                    if (ReferralRegister.Text != null && ReferralRegister.Text != "")
                    {
                        string constring = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                        SqlConnection con = new SqlConnection(constring);
                        using (SqlCommand cmd = new SqlCommand("sp_incrementPoints", con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@referrer", ReferralRegister.Text);
                            cmd.Parameters.AddWithValue("@points", 10);
                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                    if (!userMgr.IsInRole(user.Id, "member"))
                        IdUserResult = userMgr.AddToRole(user.Id, "member");

                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else
                {
                    ErrorRegister.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception) { }
        }
示例#6
0
        private static void SetupUsers(ApplicationDbContext db)
        {
            using (var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())))
            using (var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            {
                // Creating roles
                foreach (var role in Enum.GetValues(typeof(Constants.UserRole)))
                {
                    if (rm.RoleExists(role.ToString())) continue;
                    var result = rm.Create(new IdentityRole(role.ToString()));

                    if (!result.Succeeded)
                        throw new ApplicationException("Creating role " + role + " failed with error(s):\n" + GetAllErrors(result));
                }
                // Creating users
                foreach (var newUser in UsersToSetup)
                {
                    var existingUser = um.FindByEmail(newUser.Email);
                    if (existingUser == null)
                    {
                        var result = um.Create(new ApplicationUser
                        {
                            Email = newUser.Email,
                            EmailConfirmed = true,
                            UserName = newUser.Email,
                            LockoutEnabled = newUser.LockoutEnabled
                        },
                        newUser.Password);

                        if (!result.Succeeded)
                            throw new ApplicationException("Creating user " + newUser.Email + " failed with error(s):\n" + GetAllErrors(result));
                    }
                    existingUser = um.FindByEmail(newUser.Email);

                    if (!um.IsInRole(existingUser.Id, Constants.UserRole.Admin.ToString()))
                    {
                        var result = um.AddToRole(existingUser.Id, Constants.UserRole.Admin.ToString());

                        if (!result.Succeeded)
                            throw new ApplicationException("Adding role " + Constants.UserRole.Admin + " for " + newUser.Email + " failed with error(s):\n" + GetAllErrors(result));
                    }
                }
                db.SaveChanges();
            }
        }
示例#7
0
        public ActionResult AddRoleToUser(string roleName, string userName)
        {
            List<string> roles;

            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);
                var user = userManager.FindByName(userName);

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

                if (roleManager == null)
                {
                    throw new Exception("Roles not found!");
                }

                var role = roleManager.FindByName(roleName);
                if (userManager.IsInRole(user.Id, role.Name))
                {
                    ViewBag.ErrorMessage = "This user already has the role specified!";
                    roles = (from r in roleManager.Roles select r.Name).ToList();
                    ViewBag.Roles = new SelectList(roles);
                    ViewBag.UserName = userName;
                    return View();
                }
                else
                {
                    userManager.AddToRole(user.Id, role.Name);
                    context.SaveChanges();
                    List<string> userRoles;
                    var userRoleIds = (from r in user.Roles select r.RoleId);
                    userRoles = (from id in userRoleIds
                                 let r = roleManager.FindById(id)
                                 select r.Name).ToList();

                    ViewBag.UserName = userName;
                    ViewBag.RolesForUser = userRoles;
                    return View("ViewUserRoles");
                }
            }
        }
示例#8
0
        public ActionResult DeleteRoleForUser(string userName = null, string roleName = null)
        {
            if ((!string.IsNullOrWhiteSpace(userName)) || (!string.IsNullOrWhiteSpace(roleName)))
            {
                List<string> userRoles;

                using (var context = new ApplicationDbContext())
                {
                    var roleStore = new RoleStore<IdentityRole>(context);
                    var roleManager = new RoleManager<IdentityRole>(roleStore);
                    var userStore = new UserStore<ApplicationUser>(context);
                    var userManager = new UserManager<ApplicationUser>(userStore);
                    var user = userManager.FindByName(userName);

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

                    if (userManager.IsInRole(user.Id, roleName))
                    {
                        userManager.RemoveFromRole(user.Id, roleName);
                        context.SaveChanges();
                    }

                    var userRoleIds = (from r in user.Roles select r.RoleId);
                    userRoles = (from id in userRoleIds
                                 let r = roleManager.FindById(id)
                                 select r.Name).ToList();
                }
                ViewBag.UserName = userName;
                ViewBag.RolesForUser = userRoles;
                return View("ViewUserRoles");
            }

            else
            {
                return View("Index");
            }
        }
        private void CreateAndLoginUser()
        {
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdUserResult;
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            if (!IsValid)
            {
                return;
            }
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
            DateTime dateValue;
            bool noDate = false;
            if (!DateTime.TryParse(BirthdayRegister.Text, out dateValue))
                noDate = true;
            ApplicationUser user;

            if (noDate)
            {
                user = new ApplicationUser()
                {
                    UserName = email.Text,
                    Email = email.Text,
                    NIF = NIFRegister.Text,
                    FullName = FullNameRegister.Text
                };
            }
            else
            {
                user = new ApplicationUser()
                {
                    UserName = email.Text,
                    Email = email.Text,
                    BirthDate = dateValue,
                    NIF = NIFRegister.Text,
                    FullName = FullNameRegister.Text
                };
            }
            IdentityResult result = manager.Create(user);
            if (result.Succeeded)
            {
                if (!userMgr.IsInRole(user.Id, "member"))
                    IdUserResult = userMgr.AddToRole(user.Id, "member");

                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    signInManager.SignIn(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
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // Send this link via email: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    Response.Redirect("~");
                    return;
                }
            }
            AddErrors(result);
        }