/// <summary>
    /// Checks for the three roles - Admin, Employee and Complainant and 
    /// creates them if not present
    /// </summary>
    public static void InitializeRoles()
    {  // Access the application context and create result variables.
        ApplicationDbContext context = new ApplicationDbContext();
        IdentityResult IdUserResult;

        // Create a RoleStore object by using the ApplicationDbContext object. 
        // The RoleStore is only allowed to contain IdentityRole objects.
        var roleStore = new RoleStore<IdentityRole>(context);

        RoleManager roleMgr = new RoleManager();
        if (!roleMgr.RoleExists("Administrator"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Administrator" });
        }
        if (!roleMgr.RoleExists("Employee"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Employee" });
        }
        if (!roleMgr.RoleExists("Complainant"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Complainant" });
        }
        if (!roleMgr.RoleExists("Auditor"))
        {
            roleMgr.Create(new ApplicationRole { Name = "Auditor" });
        }
      

        // Create a UserManager object based on the UserStore object and the ApplicationDbContext  
        // object. Note that you can create new objects and use them as parameters in
        // a single line of code, rather than using multiple lines of code, as you did
        // for the RoleManager object.
        var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        var appUser = new ApplicationUser
        {
            UserName = "Administrator",
            Email = "[email protected]"
        };
        IdUserResult = userMgr.Create(appUser, "Admin123");

        // If the new "canEdit" user was successfully created, 
        // add the "canEdit" user to the "canEdit" role. 
        if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Administrator"))
        {
            IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Administrator");
        }
         appUser = new ApplicationUser
        {
            UserName = "Auditor",
            Email = "[email protected]"
        };
        IdUserResult = userMgr.Create(appUser, "Auditor123");

        // If the new "canEdit" user was successfully created, 
        // add the "canEdit" user to the "canEdit" role. 
        if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "Auditor"))
        {
            IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "Auditor");
        }
    }
        public void SeedData(EmployerEmployeeHuntDbContext context)
        {
            var userStore = new UserStore<User>(context);
            var userManager = new UserManager<User>(userStore);

            var adminUser = new User
            {
                UserName = AdministratorUserName,
                Email = AdministratorUserName
            };

            var headhunterUser = new User
            {
                UserName = HeadhunterUserName,
                Email = HeadhunterUserName
            };

            var developerUser = new User
            {
                UserName = DeveloperUserName,
                Email = DeveloperUserName
            };

            var employerUser = new User
            {
                UserName = EmployerUserName,
                Email = EmployerUserName
            };

            userManager.Create(adminUser, AdministratorPassword);
            userManager.Create(headhunterUser, HeadhunterPassword);
            userManager.Create(developerUser, DeveloperPassword);
            userManager.Create(employerUser, EmployerPassword);

            userManager.AddToRole(adminUser.Id, GlobalConstants.AdministratorRoleName);
            userManager.AddToRole(headhunterUser.Id, GlobalConstants.HeadhunterRoleName);
            userManager.AddToRole(developerUser.Id, GlobalConstants.UserRoleName);
            userManager.AddToRole(employerUser.Id, GlobalConstants.UserRoleName);

            for (int i = 0; i < 60; i++)
            {
                var currentUser = new User
                {
                    Email = string.Format("user_{0}@somemail.com", i + 1),
                    UserName = string.Format("user_{0}", i + 1)
                };

                userManager.Create(currentUser, currentUser.Email);

                if (i % 2 == 0)
                {
                    userManager.AddToRole(currentUser.Id, GlobalConstants.HeadhunterRoleName);
                }
                else
                {
                    userManager.AddToRole(currentUser.Id, GlobalConstants.UserRoleName);
                }
            }
        }
Example #3
0
        private static void SetupRolesAndUsers(DbContext context)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            // add roles
            if (!roleManager.RoleExists(Role.Guest.ToString()))
                roleManager.Create(new IdentityRole(Role.Guest.ToString()));
            if (!roleManager.RoleExists(Role.Supplier.ToString()))
                roleManager.Create(new IdentityRole(Role.Supplier.ToString()));
            if (!roleManager.RoleExists(Role.Deactivated.ToString()))
                roleManager.Create(new IdentityRole(Role.Deactivated.ToString()));
            if (!roleManager.RoleExists(Role.User.ToString()))
                roleManager.Create(new IdentityRole(Role.User.ToString()));
            var adminRole = roleManager.FindByName(Role.Admin.ToString());
            if (adminRole == null)
            {
                adminRole = new IdentityRole(Role.Admin.ToString());
                roleManager.Create(adminRole);
            }
            #if DEBUG
            //add admin user
            var admin = userManager.Find(Admin_User, Admin_Pass);
            if (admin == null)
            {
                admin = new ApplicationUser
                {
                    UserName = Admin_User,
                    Email = Admin_Mail,
                    EmailConfirmed = true
                };
                var result = userManager.Create(admin, Admin_Pass);
                // TODO: verify returned IdentityResult
                userManager.AddToRole(admin.Id, Role.Admin.ToString());
                result = userManager.SetLockoutEnabled(admin.Id, false);
            }

            var rolesForUser = userManager.GetRoles(admin.Id);
            if (!rolesForUser.Contains(adminRole.Name))
            {
                var result = userManager.AddToRole(admin.Id, adminRole.Name);
            }

            //add normal user
            if (userManager.Find("[email protected]", "1q2w3e4r") == null)
            {
                var user = new ApplicationUser
                {
                    UserName = "[email protected]",
                    Email = "[email protected]",
                    EmailConfirmed = true
                };
                userManager.Create(user, "1q2w3e4r");
                // TODO: verify returned IdentityResult
                userManager.AddToRole(user.Id, Role.User.ToString());
            }
            #endif
        }
Example #4
0
        public static void Seed(ApplicationDbContext context)
        {
            UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(context);
            UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

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

            if (!roleManager.RoleExists("Admin"))
                roleManager.Create(new Role { Name = "Admin" });

            if (!roleManager.RoleExists("User"))
                roleManager.Create(new Role { Name = "User" });

            IdentityResult result = null;

            ApplicationUser user1 = userManager.FindByName("[email protected]");

            if (user1 == null)
            {
                user1 = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" };
            }

            result = userManager.Create(user1, "asdfasdf");
            if (!result.Succeeded)
            {
                string error = result.Errors.FirstOrDefault();
                throw new Exception(error);
            }

            userManager.AddToRole(user1.Id, "Admin");
            user1 = userManager.FindByName("[email protected]");

            ApplicationUser user2 = userManager.FindByName("[email protected]");

            if (user2 == null)
            {
                user2 = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" };
            }

            result = userManager.Create(user2, "asdfasfd");
            if (!result.Succeeded)
            {
                string error = result.Errors.FirstOrDefault();
                throw new Exception(error);
            }

            userManager.AddToRole(user2.Id, "User");
            user2 = userManager.FindByName("[email protected]");
        }
Example #5
0
 protected void CreateUser_Click(object sender, EventArgs e)
 {
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = UserName.Text };
     IdentityResult result = manager.Create(user, Password.Text);
     if (result.Succeeded)
     {
         ApplicationUser newUser = manager.Find(UserName.Text, Password.Text);
         var sa = new StoredAccount();
         sa.CreateNewAccount(newUser.Id,Email.Text);
         var returnUrl = Request.QueryString["ReturnUrl"];
         IdentityHelper.SignIn(manager, user, isPersistent: false);
         if (returnUrl == null)
         {
             IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response);
         }
         else
         {
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
         }
     }
     else
     {
         ErrorMessage.Text = result.Errors.FirstOrDefault();
     }
 }
        public ActionResult Doctors_Create([DataSourceRequest]DataSourceRequest request, DoctorGridViewModel doctor)
        {
            if (this.ModelState.IsValid)
            {
                //TODO:Create service for users
                var context = new MyMedicalGuideDbContext();
                var userManager = new UserManager<User>(new UserStore<User>(context));
                var userDoctor = new User()
                {
                    Email = doctor.Email,
                    FirstName = doctor.FirstName,
                    LastName = doctor.LastName,
                    PhoneNumber = doctor.PhoneNumber,
                    UserName = doctor.Username
                };
                var hospitalId = this.TempData["hospitalId"];
                userManager.Create(userDoctor, doctor.Password);
                var DoctorDb = new MyMedicalGuide.Data.Models.Doctor() { User = userDoctor, HospitalId = (int)hospitalId, DepartmentId = doctor.DepartmentId, CreatedOn = DateTime.Now };
                context.Doctors.Add(DoctorDb);

                userManager.AddToRole(userDoctor.Id, "Doctor");

            }

            return this.Json(new[] { doctor }.ToDataSourceResult(request, this.ModelState));
        }
Example #7
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnectionEF
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser() { UserName = txtUName.Text };
            user.Email = txtEmail.Text;
            user.PhoneNumber = txtPhone.Text;
            IdentityResult result = manager.Create(user, txtPass.Text);

            if (result.Succeeded)
            {
                lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                Response.Redirect("/admin/main.aspx");

            }
            else
            {
                lblStatus.Text = result.Errors.FirstOrDefault();
            }
        }
Example #8
0
        public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName,
           string password, bool lockOutEnabled)
        {
            var user = userManager.FindByName(email);

            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = firstName,
                    LastName = lastName,
                    EmailConfirmed = true
                };
                try
                {
                    userManager.Create(user, password);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex);
                }
                userManager.SetLockoutEnabled(user.Id, lockOutEnabled);
            }
            return user;
        }
Example #9
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };
                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("/user/index.aspx");

                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception d)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            //crete new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser()
            {
                UserName = UserNameTextBox.Text,
                PhoneNumber = PhoneNumberTextBox.Text,
                Email = EmailTextBox.Text
            };
            //create new user in the dbb and store the resukt
            IdentityResult result = userManager.Create(user, PasswordTextBox.Text);
            //check if succesfully registered
            if (result.Succeeded)
            {
                //authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);//store info in session

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                //redirect to main menu
                Response.Redirect("~/Secured/TodoList.aspx");

            }
            else
            {
                //display error in the AlertFlash div
                StatusLabel.Text = result.Errors.FirstOrDefault();
                AlertFlash.Visible = true;
            }
        }
Example #11
0
        public static void Initialize(MacheteContext DB)
        {
            IdentityResult ir;

            var rm = new RoleManager<IdentityRole>
               (new RoleStore<IdentityRole>(DB));
            ir = rm.Create(new IdentityRole("Administrator"));
            ir = rm.Create(new IdentityRole("Manager"));
            ir = rm.Create(new IdentityRole("Check-in"));
            ir = rm.Create(new IdentityRole("PhoneDesk"));
            ir = rm.Create(new IdentityRole("Teacher"));
            ir = rm.Create(new IdentityRole("User"));
            ir = rm.Create(new IdentityRole("Hirer")); // This role is used exclusively for the online hiring interface

            var um = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(DB));
            var user = new ApplicationUser()
            {
                UserName = "jadmin",
                IsApproved = true,
                Email = "[email protected]"
            };

            ir = um.Create(user, "ChangeMe");
            ir = um.AddToRole(user.Id, "Administrator"); //Default Administrator, edit to change
            ir = um.AddToRole(user.Id, "Teacher"); //Required to make tests work
            DB.Commit();
        }
Example #12
0
        internal static void SeedAdmin(SciHubDbContext context)
        {
            const string adminUserName = "theDecider666";
            const string adminPassword = "deciderd";

            if (context.Users.Any(u => u.UserName == adminUserName))
            {
                return;
            }

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

            var admin = new User
            {
                UserName = adminUserName,
                Email = "[email protected]",
                FirstName = "Admin",
                LastName = "Adminos",
                Avatar = UserDefaultPictureConstants.Female,
                Gender = Gender.Female,
                About = "I am the Decider!"
            };

            userManager.Create(admin, adminPassword);
            userManager.AddToRole(admin.Id, UserRoleConstants.Admin);
            userManager.AddToRole(admin.Id, UserRoleConstants.Default);

            context.SaveChanges();
        }
        internal void AddUserAndRole()
        {
            Models.ApplicationDbContext context = new Models.ApplicationDbContext();

            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

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

            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            if (!roleMgr.RoleExists("administrator"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" });
            }

            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "administrator",
            };
            IdUserResult = userMgr.Create(appUser, "1qaz2wsxE");
            var user = userMgr.FindByName("administrator");
            if (!userMgr.IsInRole(user.Id, "administrator"))
            {
                //userMgr.RemoveFromRoles(user.Id, "read", "edit");
                IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator");
            }
        }
Example #14
0
        internal static void SeedAdmin(GiftBoxDbContext context)
        {
            const string AdminEmail = "[email protected]";
            const string AdminPassword = "123456";

            if (context.Users.Any(u => u.Email == AdminEmail))
            {
                return;
            }

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

            var admin = new User
            {
                FirstName = "Adrian",
                UserRole = "Admin",
                LastName = "Apostolov",
                Email = AdminEmail,
                UserName = "Adrian.Apostolov",
                PhoneNumber = "0889972697",
                ImageUrl = GlobalConstants.DefaultUserPicture,
            };

            userManager.Create(admin, AdminPassword);
            userManager.AddToRole(admin.Id, GlobalConstants.AdminRole);
            userManager.AddToRole(admin.Id, GlobalConstants.UserRole);
            userManager.AddToRole(admin.Id, GlobalConstants.HomeAdministrator);

            context.SaveChanges();
        }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);
            //IdentityResult IdUserResult;

            var user = new IdentityUser() { UserName = UserName.Text };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

               // IdUserResult = manager.AddToRole(manager.FindByName(user.UserName).Id, "member");

                Session["uPass"] = Password.Text;
                Response.Redirect("~/WebForm2.aspx");
                // StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Example #16
0
        public ActionResult Register(User user)
        {
            string temp = user.Password;
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user2 = new IdentityUser() { UserName = user.Username };
            IdentityResult result = manager.Create(user2, user.Password);

            if (result.Succeeded)
            {
                TempData["message"] = "Identity user create worked";

                //var temp2 =  this.ControllerContext.HttpContext;
                var authenticationManager = HttpContext.GetOwinContext().Authentication;
                //var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user2, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                //Response.Redirect("~/Login.aspx");
                //return View("Login");

                if (User.Identity.IsAuthenticated)
                {
                    TempData["message"] += "/n   User.Identity.IsAuthenticate working";
                }

                return View("Index");
            }
            else
            {
                TempData["message"] = "Failed: " + result.Errors.FirstOrDefault();
            }
            return View("Index");
        }
Example #17
0
 private void CreateAndLoginUser(string username, string email)
 {
     Session["dummy"] = "dummy";
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = username, Email = email, Id = Guid.NewGuid().ToString() };
     var userM = (from y in manager.Users where y.UserName == username select y).FirstOrDefault();
     if(userM == null)
     {
         IdentityResult result = manager.Create(user);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
         AddErrors(result);
     }
     else
     {
         IdentityHelper.SignIn(manager, userM, isPersistent: false);
         IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
         return;
     }
 }
Example #18
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = new UserManager();
            var user = new ApplicationUser() { UserName = UserName.Text };
            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {

                result = manager.AddToRole(user.Id, "Student");

                var std = new Student();
                std.FirstName = FirstName.Text;
                std.LastName = lastName.Text;
                std.UserId = user.Id;
                std.BirthDate = DateTime.Now;

                CourseContext cc = new CourseContext();
                cc.Students.Add(std);
                cc.SaveChanges();

                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);

            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Example #19
0
        internal void AddUserAndRole()
        {
            // access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object.
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // create admin role if it doesn't already exist
            if (!roleMgr.RoleExists("admin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" });
            }

            // create a UserManager object based on the UserStore object and the ApplicationDbContext object.
            // defines admin email account
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "[email protected]",
                Email = "[email protected]"
            };
            IdUserResult = userMgr.Create(appUser, "Pa$$word1");

            // If the new admin user was successfully created, add the new user to the "admin" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("[email protected]").Id, "admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("[email protected]").Id, "admin");
            }
        }
Example #20
0
 public bool CreateUser(ApplicationUser user, string password)
 {
     var um = new UserManager<ApplicationUser>(
         new UserStore<ApplicationUser>(new SubHubContext()));
     var idResult = um.Create(user, password);
     return idResult.Succeeded;
 }
Example #21
0
        protected void RadGridUserList_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            var editableitem = ((GridEditableItem)e.Item);
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            ///
            var useStore = new UserStore<AppUser>(new ApplicationDbContext());
            var manager = new UserManager<AppUser>(useStore);

            string LogInUserName=(editableitem.FindControl("RtxtLoginID") as RadTextBox).Text.Trim();

            var user = new AppUser { UserName = LogInUserName, FName = (editableitem.FindControl("RtxtFirstName") as RadTextBox).Text, LName = (editableitem.FindControl("RtxtLastName") as RadTextBox).Text };
            IdentityResult result = manager.Create(user, (editableitem.FindControl("RtxtPassword") as RadTextBox).Text);

            if (result.Succeeded)
            {
                //Get The Current Created UserInfo
                AppUser CreatedUser = manager.FindByName(LogInUserName);

                var RoleAddResult = manager.AddToRole(CreatedUser.Id.Trim(), (editableitem.FindControl("RDDListRole") as RadDropDownList).SelectedItem.Text.Trim());

                lblMessage.Text = string.Format("User {0} is creted successfully", user.UserName);
            }

            else
            {

                lblMessage.Text = result.Errors.FirstOrDefault();
                e.Canceled = true;
            }
        }
        public static void ClassInitialize(TestContext testContext)
        {
            // Since users are not cleaned up by transactions, we create the users we need for the test once.
            using (var context = new EventContext())
            {
                var userManager = new UserManager<AppUser>(new UserStore<AppUser>(context));
                AppUser user1 = new AppUser() { UserName = "TestUser" };
                userManager.Create(user1, "TestPassword");

                AppUser user2 = new AppUser() { UserName = "TestUser2" };
                userManager.Create(user2, "TestPassword");

                AppUser user3 = new AppUser() { UserName = "TestUser3" };
                userManager.Create(user3, "TestPassword");
            }
        }
Example #23
0
 public void GetUserClaimSyncTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("u1");
     var result = manager.Create(user);
     UnitTestHelper.IsSuccess(result);
     Assert.NotNull(user);
     var claims = new[]
     {
         new Claim("c1", "v1"),
         new Claim("c2", "v2"),
         new Claim("c3", "v3")
     };
     foreach (Claim c in claims)
     {
         UnitTestHelper.IsSuccess(manager.AddClaim(user.Id, c));
     }
     var userClaims = new List<Claim>(manager.GetClaims(user.Id));
     Assert.Equal(3, userClaims.Count);
     foreach (Claim c in claims)
     {
         Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
     }
 }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        var userMgr = new UserManager();

        var employee = new Employee()
        {
            UserName = UserName.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            PhoneNumber = PhoneNumber.Text,
            Email = Email.Text,
            Department = (Grievance.GrievanceTypes)Convert.ToInt32(Department.SelectedValue)
        };
        IdentityResult IdUserResult = userMgr.Create(employee, Password.Text);

        if (IdUserResult.Succeeded)
        {
            if (!userMgr.IsInRole(employee.Id, "Employee")) // Only users of type "Employee" can be created from the "Register Employee" page.
            {
                IdUserResult = userMgr.AddToRole(employee.Id, "Employee");
            }
            SuccessMessage.Text = "Employee created successfully";
            SuccessMessage.Visible = true;
            ErrorMessage.Visible = false;

           UserName.Text =  FirstName.Text = LastName.Text = PhoneNumber.Text = Email.Text = Password.Text = ConfirmPassword.Text = string.Empty;
        }
        else
        {
            ErrorMessage.Text = IdUserResult.Errors.FirstOrDefault();
            ErrorMessage.Visible = true;
            SuccessMessage.Visible = false;
        }
        
    }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                    lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception q)
            {
                Response.Redirect("/error.aspx");
            }
        }
Example #26
0
        private void CreateUser(ApplicationDbContext context, string userName, string userEmail, string userPass, string userRole)
        {
            if (context.Users.Any())
            {
                return;
            }

            var store = new UserStore<User>(context);
            var manager = new UserManager<User>(store)
            {
                PasswordValidator = new PasswordValidator
                {
                    RequiredLength = WebConstants.MinUserPasswordLength,
                    RequireNonLetterOrDigit = false,
                    RequireDigit = false,
                    RequireLowercase = false,
                    RequireUppercase = false,
                }
            };

            var user = new User
            {
                UserName = userName,
                Email = userEmail
            };

            manager.Create(user, userPass);
            manager.AddToRole(user.Id, userRole);
        }
 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
Example #28
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

            using (var context = new ApplicationDbContext())
            {
                if (context.Roles.Where(a => String.Compare(a.Name, "admin", true) == 0).Count() == 0)
                {
                    context.Roles.Add(new IdentityRole("admin"));
                    context.SaveChanges();
                }

                var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                var user = new ApplicationUser() { UserName = "Admin", Email = "[email protected]" };
                var createResult = um.Create(user, "Aa123!");
                if(createResult.Succeeded)
                {
                    var roleresult = um.AddToRole(user.Id, "admin");
                }
            }
        }
Example #29
0
        public HttpResponseMessage AddUser(UserSignUpViewModel userParam)
        {
            UserManager userManager = new UserManager();
            HistoryManager historyManager = new HistoryManager();
            try
            {
                var user = new User();
                user.UserName = userParam.UserName;
                user.Password = userParam.Password;
                user.Email = userParam.Email;
                user.FirstName = userParam.FirstName;
                user.MiddleName = userParam.MiddleName;
                user.LastName = userParam.LastName;

                userManager.Create(user);
                var dbUser = userManager.FindUserEmail(user.Email);
                historyManager.AddHistory(new History(dbUser)
                {
                    Activity = Activities.Joined,
                    Description = Helper.GenerateActivityDescription(dbUser, Activities.Joined)
                });
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }
Example #30
0
        public static void CreateUserByRole(RoleEnum role, ApplicationUser user, string password, ApplicationDbContext db)
        {
            user.Id = Guid.NewGuid().ToString();

            var store = new UserStore<ApplicationUser>(db);
            var manager = new UserManager<ApplicationUser>(store);

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    manager.Create(user, password);
                    db.SaveChanges();

                    manager.AddToRole(user.Id, Enum.GetName(typeof(RoleEnum), (int)role));
                    db.SaveChanges();

                    dbContextTransaction.Commit();
                }
                catch (Exception)
                {
                    dbContextTransaction.Rollback();
                }
            }
        }