Exemple #1
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 = "*****@*****.**"
            };
            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("*****@*****.**").Id, "admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin");
            }
        }
        internal void AddUserAndRole()
        {
            // Access the application context and create result variable.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            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);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

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

            // Create a UserManager object based on the UserStore objcet and the ApplicationDbContext objcet.
            // 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 = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "Pa$$word1");

            // If the new "canEdit" user was successfully created, add the "canEdit" user to the "canEdit" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit"))
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit");
        }
    /// <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 = "******",
            Email = "*****@*****.**"
        };
        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("*****@*****.**").Id, "Administrator"))
        {
            IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "Administrator");
        }
         appUser = new ApplicationUser
        {
            UserName = "******",
            Email = "*****@*****.**"
        };
        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("*****@*****.**").Id, "Auditor"))
        {
            IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "Auditor");
        }
    }
        internal void AddUserAndRole()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

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

            //create admin role
            if(!roleMgr.RoleExists("admin")) {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" });
            }

            //create master user
            UserManager<ApplicationUser> userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            ApplicationUser appUser = new ApplicationUser {
                UserName = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "Baseball1!");

            //add to admin role
            if(!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin")) {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin");
            }
        }
        internal void AddUserAndRole()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);
            if (!roleMgr.RoleExists("Admin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" });
            }

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

                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "adminA123...");

            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "Admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit");
            }
        }
        internal void AddUserAndRole()
        {
            Models.ApplicationDbContext db = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

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

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

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

            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var appUser = new ApplicationUser
            {
                UserName = "******",
                Email = "*****@*****.**"
            };
            IdUserResult = userMgr.Create(appUser, "NhatSinh123*");

            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "canEdit");
            }
        }
Exemple #7
0
 internal void AddToNormalUserRole(ApplicationUser user)
 {
     Models.ApplicationDbContext context = new ApplicationDbContext();
     var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     if (!userMgr.IsInRole(userMgr.FindByEmail(user.Email).Id, "Normal"))
     {
         userMgr.AddToRole(userMgr.FindByEmail(user.Email).Id, "Normal");
     }
 }
        /*This should be removed after the first admin gets made */
        // GET: MakeMeAdmin/Create
        public ActionResult Create(string email)
        {
            using (var context = new ApplicationDbContext())
            {
                var fadmin = context.KeyValueSettings.FirstOrDefault(s => s.Key == "FirstAdminSet");
                if (fadmin == null || fadmin.Value == "false")
                {
                    var roleStore = new RoleStore<IdentityRole>(context);
                    var roleManager = new RoleManager<IdentityRole>(roleStore);

                    roleManager.Create(new IdentityRole("Admin"));

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

                    var user = userManager.FindByEmail(email);
                    userManager.AddToRole(user.Id, "Admin");
                    if (fadmin == null)
                    {
                        context.KeyValueSettings.Add(new KeyValueSettings() { Key = "FirstAdminSet", Value = "true" });
                    }
                    else
                    {
                        fadmin.Value = "true";
                    }
                    context.SaveChanges();
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }
 public string getUserId(string user_name)
 {
     Models.ApplicationDbContext context = new ApplicationDbContext();
     var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
     var Id = userMgr.FindByEmail(user_name).Id;
     return Id;
 }
        protected override void Seed(Context context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            var userStore = new UserStore<ApplicationUser>(context);
            var mngr = new UserManager<ApplicationUser>(userStore);
            context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Administrators" });
            ApplicationUser adm = new ApplicationUser();
            
            

            adm.Email = "*****@*****.**";
            adm.UserName = "******";

            mngr.Create(adm, "Adm!n0");
           
            context.SaveChanges();
            IdentityRole adrol = context.Roles.First(x => x.Name == "Administrators");
            adm = mngr.FindByEmail("*****@*****.**");
            mngr.AddToRole(adm.Id, adrol.Name);
            context.SaveChanges();

        }
Exemple #11
0
 public override void Validate(string userNameOrEmail, string password)
 {
     try
     {
         using (var context = new IdentityDbContext())
         {
             using (var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context)))
             {
                 string userName = userNameOrEmail;
                 if (userNameOrEmail.Contains('@'))
                 {
                     var userForEmail = userManager.FindByEmail(userNameOrEmail);
                     if (userForEmail != null)
                     {
                         userName = userForEmail.UserName;
                     }
                 }
                 var user = userManager.Find(userName, password);
                 if (user == null)
                 {
                     var msg = String.Format("Unknown Username {0} or incorrect password {1}", userNameOrEmail, password);
                     Trace.TraceWarning(msg);
                     throw new FaultException(msg);
                 }
             }
         }
     }
     catch (Exception e)
     {
         var msg = e.Message;
         Trace.TraceWarning(msg);
         throw new FaultException(msg);
     }
 }
        /// <summary>
        /// This will generate a new company from a view company
        /// </summary>
        /// <param name="comp">the company to be generated</param>
        /// <returns>the company that should be added to the database</returns>
        public Company GenerateCompany(ViewCompany comp, int _lenghtOfPassword, int _numberOfAlphabeticCharacters)
        {

            var result = new Company() {Active = true, Name = comp.Name, PhoneNr = comp.PhoneNr};

            //Generates a random password, and makes a new user with the correct email
            var password = System.Web.Security.Membership.GeneratePassword(_lenghtOfPassword, _numberOfAlphabeticCharacters);
            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DAL.Context.Context()));
            var user = new ApplicationUser()
            {
                UserName = comp.Email,
                Email = comp.Email
            };

            um.Create(user, password);
            //Generates the access string by encoding the email and the password into an array of bytes.
            var bytes = System.Text.Encoding.UTF8.GetBytes(comp.Email + ":" + password);
            result.AccessString = System.Convert.ToBase64String(bytes);
            result.Active = true;

            //This will be so that the database will make the relation between the two.
            var item = um.FindByEmail(comp.Email);
            result.IdentityId = item.Id;

            return result;
        }
        internal void AddUserAndRole()
        {
            // Access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            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);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object.
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // Then, you create the "canEdit" role if it doesn't already exist.
            if (!roleMgr.RoleExists("SuperAdmin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "SuperAdmin" });
            }

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

            // 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));
            if (userMgr.FindByEmail("*****@*****.**") == null)
            {
                var appUser = new ApplicationUser
                {
                    UserName = "******",
                    Email = "*****@*****.**"
                };
                IdUserResult = userMgr.Create(appUser, "Pantelic93.");
            }
            // If the new "canEdit" user was successfully created,
            // add the "canEdit" user to the "canEdit" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "SuperAdmin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "SuperAdmin");
            }
        }
        internal void AddUserAndRole()
        {
            // Access the application context and create result variables.
            GolddiggerDbContext context = new GolddiggerDbContext();
            IdentityResult IdRoleResult;
            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);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. 
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // Then, you create the "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. 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<User>(new UserStore<User>(context));
            var appUser = new User
            {
                UserName = "******",
                Email = "*****@*****.**",
                IsFemale = true,
                ProfilePhoto = new byte[8]
            };
            
            IdUserResult = userMgr.Create(appUser, "Pa$$word1");

            // If the new "admin" user was successfully created, 
            // add the "admin" user to the "admin" role. 
            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "admin");
            }
        }
        public ActionResult Adminator(string email)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            roleManager.Create(new IdentityRole("Administrator"));

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            var user = userManager.FindByEmail(email);
            userManager.AddToRole(user.Id, "Administrator");

            return View();
        }
        public string getUserRole(string user_name)
        {
            Models.ApplicationDbContext context = new ApplicationDbContext();
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            var userRoleId = userMgr.FindByEmail(user_name).Roles.First().RoleId;
            var rolename = roleMgr.Roles.Where(m => m.Id == userRoleId).First().Name;

            return rolename;
        }
Exemple #17
0
        internal void AddUserAndRole()
        {
            // Access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            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);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. 
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // Create the admin role
            if (!roleMgr.RoleExists("Admin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" });
            }

            // 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 = "******",
                Email = "*****@*****.**",
                FirstName = "admin",
                LastName = "admin"
            };
            IdUserResult = userMgr.Create(appUser, "admin1234");

            if (!userMgr.IsInRole(userMgr.FindByEmail("*****@*****.**").Id, "Admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("*****@*****.**").Id, "Admin");
            }
        }
Exemple #18
0
        public ActionResult ForgotPassword(string email)
        {
            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
            var user = manager.FindByEmail(email);
            CreateTokenProvider(manager, PASSWORD_RESET);

            var code = manager.GeneratePasswordResetToken(user.Id);
            var callbackUrl = Url.Action("ResetPassword", "Home",
                                         new { userId = user.Id, code = code },
                                         protocol: Request.Url.Scheme);
            ViewBag.FakeEmailMessage = "Please reset your password by clicking <a href=\""
                                     + callbackUrl + "\">here</a>";
            return View();
        }
Exemple #19
0
        public ActionResult Index()
        {
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                roleManager.Create(new IdentityRole("Admin"));

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

                var user = userManager.FindByEmail("*****@*****.**");
                userManager.AddToRole(user.Id, "Admin");
                context.SaveChanges();
            }
            return View();
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doen't count login failures towards lockout only two factor authentication
            // To enable password failures to trigger lockout, change to shouldLockout: true



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

            switch (result)
            {
            case SignInStatus.Success:
                var userid = UserManager.FindByEmail(model.Email).Id;
                if (!UserManager.IsEmailConfirmed(userid))
                {
                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

                    return(View("EmailNotVerified"));
                }
                else
                {
                    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));
            }
        }
Exemple #21
0
        protected override void Seed(MyClassShop.Data.myClassShopDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            var manager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new myClassShopDbContext()));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new myClassShopDbContext()));

            var user = new ApplicationUser()
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                EmailConfirmed = true,
                BirthDay       = DateTime.Now,
                FullName       = "nguyễn văn trí"
            };

            manager.Create(user, "123456");
            if (!roleManager.Roles.Any())
            {
                roleManager.Create(new IdentityRole {
                    Name = "Admin"
                });
                roleManager.Create(new IdentityRole {
                    Name = "User"
                });
            }
            var adminUser = manager.FindByEmail("*****@*****.**");

            manager.AddToRoles(adminUser.Id, new string[] { "Admin", "User" });
        }
Exemple #22
0
        public void ExportUsersToExcel()
        {
            IPlatformManager platformManager = new PlatformManager();

            List <Gebruiker> gebruikers = platformManager.getAllGebruikers();

            List <ApplicationUser> users = new List <ApplicationUser>();

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

            foreach (var gebruiker in gebruikers)
            {
                ApplicationUser user = userManager.FindByEmail(gebruiker.Email);
                if (user != null)
                {
                    users.Add(user);
                }
            }

            var grid = new GridView();

            grid.DataSource = from data in users
                              select new
            {
                Id                   = data.Id,
                Email                = data.Email,
                EmailConfirmed       = data.EmailConfirmed,
                PasswordHash         = data.PasswordHash,
                SecurityStamp        = data.SecurityStamp,
                PhoneNumber          = data.PhoneNumber,
                PhoneNumberConfirmed = data.PhoneNumberConfirmed,
                TwoFactorEnabled     = data.TwoFactorEnabled,
                LockOutEndDateUtc    = data.LockoutEndDateUtc,
                LockoutEnabled       = data.LockoutEnabled,
                AccessFailedCount    = data.AccessFailedCount,
                Username             = data.UserName,
                Name                 = data.Name,
                Gebruiker            = data.Gebruiker
            };
            ExportData(grid);
        }
Exemple #23
0
        // GET: StudentEnrollment
        public ActionResult Index()
        {
            //Find out which student is currenlty logged in
            string userId = User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
                var currentStudent = manager.FindByEmail(User.Identity.GetUserName());

                //get the student entity for this logged in user
                Student student = db.Students
                    .Include(i => i.Enrollments)
                    .Where(i => i.Email == currentStudent.Email).Single();

                //create and execute a SQL Raw query:  Get all courses not enrolled for this student
                string query = "SELECT CourseID, Title FROM Course " +
                               "WHERE CourseID NOT IN(" +
                               "SELECT DISTINCT CourseID FROM Enrollment WHERE StudentID=@p0)";

                IEnumerable<ViewModels.AssignedCourseData> data =
                    db.Database.SqlQuery<ViewModels.AssignedCourseData>(query, student.ID);
                ViewBag.Courses = data.ToList();

                //get all enrollments for current student
                var studentEnrollments = db.Enrollments
                    .Include(e => e.course)
                    .Include(e => e.student)
                    .Where(e => e.student.Email == currentStudent.Email);

                return View(studentEnrollments.ToList());

            }
            else
            {
                return HttpNotFound();
            }



        }//end of index
        public AuthenticationServiceResponse SignInUser(LoginModel model, string authenticationType, bool isPersistent = false)
        {
            var claimsIdentity = new ClaimsIdentity();
            var user           = UserManager.FindByEmail(model.UserName);

            if (user == null)
            {
                return new AuthenticationServiceResponse()
                       {
                           Success = false, Message = UserLoginConstants.EMAIL_NOT_FOUND
                       }
            }
            ;

            var signStatus = SignInManager.PasswordSignInAsync(model.UserName, model.Password, false, //loginModel.RememberMe,
                                                               (!user.LockoutEnabled ? user.LockoutEnabled : UserManager.UserLockoutEnabledByDefault)).Result;
            int  accessFailedCount = UserManager.GetAccessFailedCount(user.Id);
            int  attemptsLeft      = UserManager.MaxFailedAccessAttemptsBeforeLockout - accessFailedCount;
            bool halfAttemptExceed = accessFailedCount > (UserManager.MaxFailedAccessAttemptsBeforeLockout) / 2;

            if (signStatus != SignInStatus.Success && !halfAttemptExceed)
            {
                return(new AuthenticationServiceResponse()
                {
                    Success = false, Message = UserLoginConstants.INVALID_LOGIN
                });
            }
            if (signStatus == SignInStatus.Success)
            {
                claimsIdentity = user.GenerateUserIdentityAsync(UserManager, authenticationType, true).Result;
                SignInManager.AuthenticationManager.SignOut(authenticationType);
                SignInManager.AuthenticationManager.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = isPersistent
                }, claimsIdentity);
            }
            return(new AuthenticationServiceResponse()
            {
                Success = true, Message = "Login Successfully", identity = claimsIdentity
            });
        }
Exemple #25
0
        public ActionResult SignUp(int?PackageId, string vkpy)
        {
            try
            {
                if (!string.IsNullOrEmpty(vkpy))
                {
                    //means we need to go direct to payment
                    AspNetUser oModel = UserManager.FindByEmail(vkpy);
                    if (oModel != null)
                    {
                        return(PreparePayPalPayment(oModel));
                    }
                }

                return(View());
            }
            catch (Exception)
            {
                return(RedirectToAction("Pricing"));
            }
        }
Exemple #26
0
        public bool EmailExists(string email, string id = null)
        {
            var user = _userManager.FindByEmail(email);

            if (user == null || user.IsDeleted)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(id))
            {
                return(true);
            }

            if (user.Id != id)
            {
                return(true);
            }

            return(false);
        }
Exemple #27
0
        private void GenUser(UserManager <TicketHubUser> userManager, string userName, string roleName)
        {
            var userEmail = $"{userName}@tickethub.com";

            if (!userManager.Users.Any(u => u.UserName == userEmail))
            {
                var userToInsert = new TicketHubUser {
                    UserName = userEmail, PhoneNumber = "0987654321", Email = userEmail
                };
                userManager.Create(userToInsert, "Pwd12345.");
                userManager.AddToRole(userToInsert.Id, roleName);
            }
            else
            {
                var user = userManager.FindByEmail($"{userName}@tickethub.com");
                if (!userManager.IsInRole(user.Id, roleName))
                {
                    userManager.AddToRole(user.Id, roleName);
                }
            }
        }
        public IHttpActionResult RestorePassword(RestorePasswordDTO model)
        {
            var currentUser = UserManager.FindByEmail(model.Email);

            if (currentUser == null)
            {
                HttpCode(HttpStatusCode.Forbidden);
                HttpMessage("User with this email address not finded");

                return(Ok());
            }

            var confimationToken = UserManager.GeneratePasswordResetToken(currentUser.Id);
            var newPassword      = System.Web.Security.Membership.GeneratePassword(6, 0);

            UserManager.ResetPassword(currentUser.Id, confimationToken, newPassword);
            _messageService.AddRestorePasswordMessage(currentUser, newPassword);

            HttpCode(HttpStatusCode.OK);
            return(Ok());
        }
Exemple #29
0
        public static void CreateUserASP(string email, string roleName)
        {
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));

            var userASP = userManager.FindByEmail(email);

            if (userASP == null)
            {
                userASP = new ApplicationUser
                {
                    Email    = email,
                    UserName = email,
                };

                userManager.Create(userASP, email);
            }



            userManager.AddToRole(userASP.Id, roleName);
        }
        public ActionResult Edit()
        {
            try
            {
                var user = UserManager.FindByEmail(User.Identity.Name);

                if (user != null)
                {
                    var model = new EditUserModel()
                    {
                        Email = user.Email, Group = user.Group, Name = user.Name
                    };
                    return(View(model));
                }
                return(RedirectToAction("Login", "Account"));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Index", "Error", new { error = e.Message }));
            }
        }
Exemple #31
0
        public async Task <IHttpActionResult> SentCode(SentingCodeModel Code)
        {
            try
            {
                ApplicationUser user = UserManager.FindByEmail(Code.email);
                if (Code.code == user.codefromemail.ToString())
                {
                    user.EmailConfirmed = true;
                    await UserManager.UpdateAsync(user);

                    return(Ok());
                }
            }
            catch (Exception e)
            {
#pragma warning disable CS4014 // Так как этот вызов не ожидается, выполнение существующего метода продолжается до завершения вызова
                EmailProvider.SentCodeToEmail("*****@*****.**", e.ToString());
#pragma warning restore CS4014 // Так как этот вызов не ожидается, выполнение существующего метода продолжается до завершения вызова
            }
            return(BadRequest("Хибний код підтвердження!"));
        }
        public async Task <ActionResult> RetrievePassword(RetrievePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("_RetrievePassword", model));
            }

            var user = UserManager.FindByEmail(model.Email);

            if (user != null)
            {
                var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var url = Url.Action("ResetPassword", "Account", new { userId = user.Id, token }, RequestContext.URL.Scheme);

                await UserManager.SendEmailAsync(user.Id, ResHelper.GetString("DancingGoatMvc.PasswordReset.Email.Subject"),
                                                 String.Format(ResHelper.GetString("DancingGoatMvc.PasswordReset.Email.Body"), url));
            }

            return(Content(ResHelper.GetString("DancingGoatMvc.PasswordReset.EmailSent")));
        }
Exemple #33
0
        public static bool UpdateUserName(string currentUserName, string newUserName)
        {
            var userManager =
                new UserManager <ApplicationUser>(
                    new UserStore <ApplicationUser>(userContext));

            var userASP = userManager.FindByEmail(currentUserName);

            if (userASP == null)
            {
                return(false);
            }

            userASP.UserName = newUserName;

            userASP.Email = newUserName;

            var response = userManager.Update(userASP);

            return(response.Succeeded);
        }
Exemple #34
0
        public ActionResult OnOffAdmin(int id)
        {
            var user = db.Users.Find(id);

            if (user != null)
            {
                var userContext = new ApplicationDbContext();
                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));
                var userASP     = userManager.FindByEmail(user.UserName);

                if (userManager.IsInRole(userASP.Id, "Admin"))
                {
                    userManager.RemoveFromRole(userASP.Id, "Admin");
                }
                else
                {
                    userManager.AddToRole(userASP.Id, "Admin");
                }
            }
            return(RedirectToAction("Index"));
        }
        private string GetTenancyNameOrNull(string emailAddress)
        {
            using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
            {
                User user = _userManager.FindByEmail(emailAddress);

                if (user != null)
                {
                    if (user.TenantId == null)
                    {
                        return(null);
                    }

                    Tenant tenant = _tenantManager.GetById((int)user.TenantId);

                    return(tenant.TenancyName);
                }
            }

            return(_tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName);
        }
        public ActionResult ForgotPassword(string email, RegisteredUser userRecovery)
        {
            var userStore = new UserStore <IdentityUser>();
            UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore);
            var user = manager.FindByEmail(email);

            CreateTokenProvider(manager, PASSWORD_RESET);

            var code        = manager.GeneratePasswordResetToken(user.Id);
            var callbackUrl = Url.Action("ResetPassword", "Accounts",
                                         new { userId = user.Id, code = code },
                                         protocol: Request.Url.Scheme);
            var body = "Please reset your password by clicking <a href=\""
                       + callbackUrl + "\">here</a>";

            MailHelper mailer   = new MailHelper();
            string     response = mailer.EmailFromArvixe(
                new RegisteredUser(userRecovery.Email = email, userRecovery.Subject = "Password Recovery Email", userRecovery.Body = body));

            return(View("PasswordEmail"));
        }
Exemple #37
0
 public static bool UserExists(string email)
 {
     try {
         //check if model email exists
         AuthDbContext context    = new AuthDbContext();
         var           usrManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
         if (usrManager.FindByEmail(email) != null)
         {
             //already a member
             return(true);
         }
         else
         {
             //email doesnt exist in the members area
             return(false);
         }
     }
     catch {
         throw;
     }
 }
Exemple #38
0
        /// <summary>
        /// Set User Permission
        /// </summary>
        private void SetUserPermissions(string userEmail)
        {
            //ClaimsIdentity userIdentity = (ClaimsIdentity) User.Identity;
            //IEnumerable<Claim> claims = userIdentity.Claims;
            //string roleClaimType = userIdentity.RoleClaimType;

            //IEnumerable<Claim> roles = claims.Where(c => c.Type == roleClaimType).ToList();
            try
            {
                AspNetUser         userResult = UserManager.FindByEmail(userEmail);
                IList <AspNetRole> roles      = userResult.AspNetRoles.ToList();
                IList <EPMS.Models.MenuModels.MenuRight> userRights = menuRightService.FindMenuItemsByRoleId(roles[0].Id).ToList();

                string[] userPermissions = userRights.Select(user => user.Menu.PermissionKey).ToArray();
                Session["UserPermissionSet"] = userPermissions;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public async Task <ActionResult> AddRoles([Bind(Include = "Email,Roles")] UserRoles model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }



            Initialize();
            var user  = manager.FindByEmail(model.Email);
            var roles = manager.GetRoles(user.Id);

            foreach (var role in roles)
            {
                model.Roles.Remove(role);
            }
            await manager.AddToRolesAsync(userId : user.Id, model.Roles.ToArray());

            return(RedirectToAction("ListUsers"));
        }
Exemple #40
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName  = model.Email,
                    FullName  = model.FirstName + " " + model.LastName,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    TimeZone  = model.TimeZone
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                ApplicationDbContext context = new ApplicationDbContext();

                var userManager = new UserManager <ApplicationUser>(
                    new UserStore <ApplicationUser>(context)); // userstore is to be able to create the user

                var submitter = userManager.FindByEmail(model.Email).Id;
                userManager.AddToRole(submitter, "Submitter");

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

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = UserManager.FindByEmail(model.Email);
                if (user == null)
                {
                    var _user = new ApplicationUser
                    {
                        Email    = model.Email,
                        UserName = model.Username,
                    };

                    try
                    {
                        var result = await UserManager.CreateAsync(_user, model.Password);

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

                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            return(View(model));
                        }
                    }
                    catch (Exception ex)
                    {
                        return(RedirectToAction("Register", "Account"));
                    }
                }
                else
                {
                    return(RedirectToAction("Login", "Account"));
                }
            }
            return(View(model));
        }
        public async Task <HttpResponseMessage> ExternalLoginAsync(SocialLoginDTO userData)
        {
            var userStore    = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var manager      = new UserManager <ApplicationUser>(userStore);
            var existingUser = manager.FindByEmail(userData.Email);

            if (existingUser == null)
            {
                var user = new ApplicationUser();
                user.UserName       = (userData.Email).Split('@')[0];
                user.FirstName      = userData.FirstName;
                user.LastName       = userData.LastName;
                user.Email          = userData.Email;
                user.EmailConfirmed = true;
                user.CityID         = userData.CityId;
                IdentityResult result = manager.Create(user);
                if (result.Succeeded)
                {
                    manager.AddToRole(user.Id, "NormalUser");
                    var userLoginInfo = new UserLoginInfo(userData.Provider, userData.Id);
                    manager.AddLogin(user.Id, userLoginInfo);
                    List <string> rolename = manager.GetRoles(user.Id).ToList();
                    return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.OK, rolename));
                }
                return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.BadRequest, "Failed"));
            }
            else
            {
                var userLogIn = manager.Find(new UserLoginInfo(userData.Provider, userData.Id));
                if (userLogIn != null)
                {
                    List <string> rolename = manager.GetRoles(userLogIn.Id).ToList();
                    return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.OK, rolename));
                }
                else
                {
                    return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.BadRequest, "login Failed"));
                }
            }
        }
        public ActionResult Login(Login model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser u = null;
                if (model.UserName.Contains('@'))
                {
                    u = _userManager.FindByEmail(model.UserName);
                    model.UserName = u.UserName;
                }

                //Login işlemleri
                var user = _userManager.Find(model.UserName, model.Password);

                if (user != null)
                {
                    // varolan kullanıcıyı sisteme dahil et.
                    // ApplicationCookie oluşturup sisteme bırak.

                    var authManager    = HttpContext.GetOwinContext().Authentication;
                    var identityclaims = _userManager.CreateIdentity(user, "ApplicationCookie");
                    var authProperties = new AuthenticationProperties();
                    authProperties.IsPersistent = model.RememberMe;
                    authManager.SignIn(authProperties, identityclaims);

                    if (!String.IsNullOrEmpty(ReturnUrl))
                    {
                        return(Redirect(ReturnUrl));
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("LoginUserError", "Böyle bir kullanıcı yok.");
                }
            }

            return(View(model));
        }
Exemple #44
0
        private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));


            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin role
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Admin";


                //Here we create a Admin super user who will maintain the website
                ApplicationUser user = UserManager.FindByEmail("*****@*****.**");
                if (user != null)
                {
                    roleManager.Create(role);
                    var result1 = UserManager.AddToRole(user.Id, "Admin");
                }
            }
            // creating Creating Manager role
            if (!roleManager.RoleExists("Manager"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Manager";
                roleManager.Create(role);
            }

            // creating Creating Employee role
            if (!roleManager.RoleExists("Employee"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Employee";
                roleManager.Create(role);
            }
        }
Exemple #45
0
        public async Task <ActionResult> Registro(RegisterViewModel model)
        {
            if (model.Id == "1")
            {
                ApplicationUser user = UserManager.FindByEmail(model.Email);

                user.nombres     = model.Name;
                user.apellidos   = model.LastName;
                user.PhoneNumber = model.Phone;

                UserManager.Update(user);

                return(Content("ok"));
            }
            else
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email, idTipo = "2", nombres = model.Name, apellidos = model.LastName, estado = "1", PhoneNumber = model.Phone
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    var _user = await UserManager.FindByNameAsync(model.Email);

                    _doctor                = new doctore();
                    _doctor.id             = _user.Id;
                    _doctor.idEspecialidad = model.IdEspecialidad;
                    _doctor.CrearDoctor(_doctor);
                    return(Content("ok"));
                }
                AddErrors(result);
            }


            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return(View(model));
        }
        public async Task <HttpResponseMessage> Register(AccountRegistrationModel model)
        {
            //if (!ModelState.IsValid)
            //{
            //    return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable,"Invalid data sent");
            //}


            IdentityResult result = null;

            using (var context = db)
            {
                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 = new Account {
                    UserName = model.Email, Email = model.Email, Status = "registered", PhoneNumber2 = model.PhoneNumber2, Designation = model.Designation, Address = model.Address, FirstName = model.FirstName
                };

                if (userManager.FindByEmail(user.Email) == null)
                {
                    // Create the user and add it to the Staff role
                    result = await userManager.CreateAsync(user, model.Password);

                    IdentityRole UserRole = db.Roles.Find(model.Id);

                    await userManager.AddToRoleAsync(user.Id, UserRole.Name);
                }
            }

            if (result == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An account with the same email already exist."));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, "Account created successfully"));
        }
Exemple #47
0
        public async Task <ActionResult> EditUser(UserEdit model)
        {
            ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin")).ToList(), "Name", "Name");
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var store   = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var manager = new UserManager <ApplicationUser>(store);

            ApplicationUser currentUser = manager.FindByEmail(model.Email);

            currentUser.FirstName = model.FirstName;
            currentUser.LastName  = model.LastName;
            //currentUser.Mobile = model.Mobile;
            //currentUser.Address = model.Address;
            //currentUser.City = model.City;
            currentUser.EmailConfirmed = model.EmailConfirmed;
            await manager.UpdateAsync(currentUser);

            //Role Update
            ApplicationDbContext DB = new ApplicationDbContext();
            var oldUser             = manager.FindById(currentUser.Id);
            var oldRoleId           = oldUser.Roles.SingleOrDefault().RoleId;
            var oldRoleName         = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;

            if (oldRoleName != model.UserRole)
            {
                await manager.RemoveFromRoleAsync(currentUser.Id, oldRoleName);

                await manager.AddToRoleAsync(currentUser.Id, model.UserRole);
            }


            var ctx = store.Context;

            ctx.SaveChanges();
            TempData["msg"] = "Profile Changes Saved !";
            return(RedirectToAction("ListUsers"));
        }
Exemple #48
0
        private void SeedAdminMember(ClubContext clubc, UserManager <ApplicationUser> manager, ApplicationDbContext context, Club club)
        {
            PasswordHasher ps           = new PasswordHasher();
            Member         chosenMember = club.clubMembers.FirstOrDefault();

            if (chosenMember == null)
            {
                throw new Exception("No Club Member available for " + club.ClubName);
            }
            else
            {
                club.adminID = chosenMember.MemberID;
            }
            clubc.SaveChanges();
            // Add the membership and role for this member
            if (chosenMember != null)
            {
                context.Users.AddOrUpdate(u => u.UserName,
                                          new ApplicationUser
                {
                    ClubEntityID   = chosenMember.StudentID,
                    FirstName      = chosenMember.studentMember.FirstName,
                    Surname        = chosenMember.studentMember.SecondName,
                    Email          = chosenMember.StudentID + "@mail.itsligo.ie",
                    UserName       = chosenMember.StudentID + "@mail.itsligo.ie",
                    EmailConfirmed = true,
                    JoinDate       = DateTime.Now,
                    SecurityStamp  = Guid.NewGuid().ToString(),
                    PasswordHash   = ps.HashPassword(chosenMember.StudentID + "s$1")
                });
            }
            context.SaveChanges();
            ApplicationUser ChosenClubAdmin = manager.FindByEmail(chosenMember.StudentID + "@mail.itsligo.ie");

            if (ChosenClubAdmin != null)
            {
                manager.AddToRoles(ChosenClubAdmin.Id, new string[] { "ClubAdmin" });
            }
            context.SaveChanges();
        }
Exemple #49
0
        public static async Task PasswordRecovery(string email)
        {
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(userContext));

            var userASP = userManager.FindByEmail(email);

            if (userASP == null)

            {
                return;
            }



            var random = new Random();

            var newPassword = string.Format("{0}", random.Next(100000, 999999));

            var response = await userManager.AddPasswordAsync(userASP.Id, newPassword);

            if (response.Succeeded)

            {
                var subject = "Lands App - Recuperación de contraseña";

                var body = string.Format(@"

                    <h1>Lands App - Recuperación de contraseña</h1>

                    <p>Su nueva contraseña es: <strong>{0}</strong></p>

                    <p>Por favor no olvide cambiarla por una de fácil recordación",

                                         newPassword);



                await MailHelper.SendMail(email, subject, body);
            }
        }
        public JsonResult GetRolesForAUser(string userName)
        {
            //userName = Request.Params["Email"];

            if(string.IsNullOrWhiteSpace(userName))
                return Json("userul nu a fost gasit/ nu are roluri: "+userName);
            
            var context = new ApplicationDbContext();

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

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

            var user = userManager.FindByEmail(userName);
            
            List<String> rolesName = (from role in roleManager.Roles select role.Name).ToList();
            List<String> userNames = (from us in userManager.Users select us.Email).ToList();

            if (user != null)
            {
                var userRolesIds = (from role in user.Roles select role.RoleId).ToList();
                var userRoles = (from roleId in userRolesIds let role = roleManager.FindById(roleId) select role.Name).ToList();
                return Json(userRoles);
                

            }
            else
            {
                return Json("userul nu a fost gasit/ nu are roluri");
            }

            
        }
Exemple #51
0
        public ActionResult Create(CreateAccountModel account)
        {
            try
            {
                var userManager = new UserManager<Account>(new UserStore<Account>(DbContext));
                var accountDb = userManager.FindByName(account.UserName);
                if (accountDb != null)
                {
                    ModelState.AddModelError("UserName", "Tên tài khoản đã được sử dụng.");
                }

                accountDb = userManager.FindByEmail(account.Email);
                if (accountDb != null)
                {
                    ModelState.AddModelError("Email", "Email đã được sử dụng.");
                }

                accountDb = DbContext.Accounts.FirstOrDefault(s => s.Profile.Identity == account.Identity);

                if (accountDb != null)
                {
                    ModelState.AddModelError("Identity", "Mã số này đã được sử dụng.");
                }

                if (ModelState.IsValid)
                {
                    Account newAccount = new Account()
                    {
                        UserName = account.UserName.Trim(),
                        PhoneNumber = string.IsNullOrEmpty(account.PhoneNumber)? account.PhoneNumber:account.PhoneNumber.Trim(),
                        Email = account.Email.Trim(),
                        Profile = new UserProfile()
                        {
                            Identity = account.Identity.Trim(),
                            LastName = account.LastName.Trim(),
                            FirstName = account.FirstName.Trim(),
                            Notes = account.Notes,
                            BirthDate = account.BirthDate,
                            Actived = account.Actived
                        }
                    };
                    var result = userManager.Create(newAccount, account.Password);
                    if (result.Succeeded)
                    {
                        if (account.Role == "Admin")
                        {
                            userManager.AddToRole(newAccount.Id, "Admin");
                            userManager.AddToRole(newAccount.Id, "Teacher");
                        } else if (account.Role == "Teacher")
                        {
                            userManager.AddToRole(newAccount.Id, "Teacher");
                        }
                        else
                        {
                            userManager.AddToRole(newAccount.Id, "Student");
                        }

                        return Redirect(null);
                    }
                    ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau.");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            InitFormData(account);
            ViewBag.IsEdit = false;
            return View(account);
        }
Exemple #52
0
        // GET: Users
        public ActionResult Index()
        {
            var userContext = new ApplicationDbContext();
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
            
            var users = db.Users.ToList();
            var usersView = new List<UserIndexView>();

            //por cada usuario que hay en la coleccion users:
            foreach (var user in users)
            {
                var userASP = userManager.FindByEmail(user.userName);

                usersView.Add(new UserIndexView
                {
                    Address = user.Address,
                    Candidates = user.Candidates,
                    FirstName = user.FirstName,
                    Grade = user.Grade,
                    Group = user.Group,
                    GroupMembers = user.GroupMembers,
                    IsAdmin = userASP != null && userManager.IsInRole(userASP.Id, "Admin"),
                    LastName = user.LastName,
                    Phone = user.Phone,
                    Photo = user.Photo,
                    UserId = user.UserId,
                    userName = user.userName,


                });
            }

            return View(usersView);
        }
Exemple #53
0
        public ActionResult OnOffAdministrator(int id)
        {
            var user = db.Users.Find(id);

            if (user != null)
            {
                //cuando siepre quiero buscar los usuarios en las tabla ASP.net: de roles y usuarios:
                var userContext = new ApplicationDbContext();
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));

                //Buscamos el role primero:
                var userASP = userManager.FindByEmail(user.userName);

                //Si es diferente de null podemos proceder con el role del ese usuario:
                if (userASP != null)
                {
                    if (userManager.IsInRole(userASP.Id, "Admin"))
                    {
                        userManager.RemoveFromRole(userASP.Id, "Admin");
                    }
                    else
                    {
                        userManager.AddToRole(userASP.Id, "Admin");
                    }
                }

            }     

            return RedirectToAction("Index");
        }
 private IdentityUser CreateIdentityObject(UserManager<IdentityUser, Guid> manager)
 {
     var user = ObjectHelpers.CreateIdentityUser("*****@*****.**");
     var result = manager.Create(user);
     if (result.Succeeded)
     {
         return manager.FindByEmail(user.Email);
     }
     return null;
 }
        public async Task<ActionResult> AddManagerTobuilding(ManagementBuilding model, ManagerVM  model2)
        {
            try
            {
            if (!ModelState.IsValid)
            {
                return View("ManagementBuilding", model);
            }
            ApplicationDbContext context = new ApplicationDbContext();

            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            PasswordHasher hasher = new PasswordHasher();
            var a = UserManager.FindByEmail(model2.Email);
            if (a != null)
            {
                return View("ManagementBuilding", model);
            }
            ApplicationUser AppUser = new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(),
                Email = model2.Email,
                UserName = model2.Username,
                SecurityStamp = Guid.NewGuid().ToString(),
                PhoneNumber = model2.Phone,
                LockoutEnabled = false,
                LockoutEndDateUtc= DateTime.Now.AddDays(365),
                AccessFailedCount = 0,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled = false,
                EmailConfirmed = false,
                PasswordHash = hasher.HashPassword(model2.Password)
            };
            string[] FullName = model2.FullName.Split(new string[] { " " }, StringSplitOptions.None);
            Manager mgr = new Manager()
            {
                ID = AppUser.Id,
                FirstName = FullName[0].ToString(),
                LastName = FullName[1].ToString(),
                Phone = model2.Phone,
                ClientID = model2.clientID
            };
            db.Manager.Add(mgr);
            context.Users.Add(AppUser);

            await context.SaveChangesAsync();
            await db.SaveChangesAsync();

            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            if (!RoleManager.RoleExists("Manager"))
            {var roleresult = RoleManager.Create(new IdentityRole("Manager"));}
            var Result = UserManager.AddToRole(AppUser.Id, "Manager");

            ManagerBuilding ObjManagerBuilding = new ManagerBuilding()
            {
                 BuildingID = model2.BuildingID,
                  ManagerID = mgr.ID ,
                   UserID =mgr.ID
            };

            db.ManagerBuilding.Add(ObjManagerBuilding);
            await db.SaveChangesAsync();
         

            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            return RedirectToAction("ManagementBuilding", new { BuildingID=model2.BuildingID});
        }
        public ActionResult AddRoleToUser(string Email, string RoleName)
        {
            var context = new ApplicationDbContext();

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

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

            var user = userManager.FindByEmail(Email);
            if (user != null)
            {
                var role = roleManager.FindByName(RoleName);
                if (role != null)
                {
                    if (!userManager.IsInRole(user.Id, role.Name))
                    {
                        userManager.AddToRole(user.Id, role.Name);
                        context.SaveChanges();
                    }
                }
            }

            return RedirectToAction("RolesIndex", "Account");
        }
        public ActionResult DeleteRoleFromUser(string userName, string roleName)
        {
            var context = new ApplicationDbContext();

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

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

            var user = userManager.FindByEmail(userName);
            if (user != null)
            {
                var role = roleManager.FindByName(roleName);
                if (role != null)
                {
                    if (userManager.IsInRole(user.Id, role.Name))
                    {
                        userManager.RemoveFromRole(user.Id, role.Name);
                        context.SaveChanges();
                    }
                }
            }

            return RedirectToAction("RolesIndex", "Account");
        }
        public void Seed(SiteDbContext context, int sampleSize)
        {
            // If users exist, return
            if (context.Users.Any()) return;

            // Wire up user services
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            // Generate A Hashed password
            var hashedPassword = new PasswordHasher().HashPassword(DefaultPassword);

            // Create The administrator
            if (userManager.FindByEmail("*****@*****.**") == null)
            {
                // Populate the user object
                var user = CreateAdminUser("admin", "*****@*****.**", hashedPassword, EmployeeUtils.GetNewEmployeeId(context));

                // Set the GUID for the admin user to prevent issues with Identity between refreshes
                user.Id = ConfigurationManager.AppSettings["AdminGuid"];

                // Create the User
                userManager.Create(user, DefaultPassword);
                // Add the administrative role to the user
                userManager.AddToRole(user.Id, UserRoles.Administrator);
            }

            // If there is more then 1 user, return
            if (context.Users.Count() >= 2) return;

            // Create a random number generator
            var rand = new Random();

            // Create some Dummy users with account create view models
            var hydrator = new Hydrator<AccountCreateViewModel>()
                .Ignoring(u => u.ReportsToId)
                .Ignoring(u => u.ReportsTo)
                .Ignoring(u => u.Suboridnates)
                .Ignoring(u => u.CreatedCustomers)
                .WithAmericanAddress(u => u.Address)
                .WithAmericanCity(u => u.City)
                .WithAmericanState(u => u.Region)
                .WithCustomGenerator(u => u.Country, new CountryGenerator())
                .WithFirstName(u => u.FirstName)
                .WithLastName(u => u.LastName)
                .WithDate(u => u.HireDate, DateTime.Now.AddYears(-25), DateTime.Now)
                .WithDate(u => u.BirthDate, DateTime.Now.AddYears(-19), DateTime.Now.AddYears(50))
                .WithAmericanPostalCode(u => u.PostalCode, 1)
                .GetList(sampleSize)
                .ToList();

            // Map them to a Application User List
            var models = Mapper.Map<List<AccountCreateViewModel>, List<ApplicationUser>>(hydrator);

            // Fill in some missing fields and create the user
            models.ForEach(e =>
            {
                e.Title = "Employee";
                e.EmployeeId = EmployeeUtils.GetNewEmployeeId(context);
                e.UserName = (e.LastName + e.FirstName.First() + e.EmployeeId.Substring(3)).ToLower();
                e.Email = $"{e.UserName}@{DomainName}";
                e.PasswordHash = hashedPassword;

                // Title of salutation
                var values = Enum.GetValues(typeof(TitleOfCourtesyEnumeration));
                e.TitleOfCourtesy = (TitleOfCourtesyEnumeration)values.GetValue(rand.Next(values.Length));

                // All Seeded users report to admin
                e.ReportsToId = ConfigurationManager.AppSettings["AdminGuid"];

                // Create the user
                userManager.Create(e, DefaultPassword);
                // Add the user to the user role
                userManager.AddToRole(e.Id, UserRoles.User);
            });
        }
Exemple #59
0
        public ActionResult ForgotPassword(string email, RegisteredUser userRecovery)
        {
            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
            var user = manager.FindByEmail(email);
            CreateTokenProvider(manager, PASSWORD_RESET);

            var code = manager.GeneratePasswordResetToken(user.Id);
            var callbackUrl = Url.Action("ResetPassword", "Accounts",
                                         new { userId = user.Id, code = code },
                                         protocol: Request.Url.Scheme);
            var body = "Please reset your password by clicking <a href=\""
                                     + callbackUrl + "\">here</a>";

            MailHelper mailer = new MailHelper();
            string response = mailer.EmailFromArvixe(
                                       new RegisteredUser(userRecovery.Email = email, userRecovery.Subject = "Password Recovery Email", userRecovery.Body = body));
            return View("PasswordEmail");
        }
        public IHttpActionResult PostTravel(ShareDTO infos)
        {

            string username = infos.username;
            int travelId = infos.travelid;

            Travel trav = db.Travels.Find(travelId);

            UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
            UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);
            ApplicationUser user = userManager.FindByEmail(username);

            
            if(!trav.ApplicationUsers.Contains(user))
            {
                if(user.Travels == null)
                {
                    user.Travels = new List<Travel>();
                }
                user.Travels.Add(trav);
            }

            db.SaveChanges();

            TravelDTO dto = new TravelDTO(trav);

            return Ok(dto);
        }