예제 #1
0
        private bool ValidateUserInternal(BTTUser user, string password)
        {
            if (user != null)
            {
                BTTUserActivity uact = GetActivityForUser(user);

                if (uact.FailedLogins > _MaxInvalidPasswordAttempts || uact.IsLockedOut)
                {
                    return(false);
                }
                string passwordValidate = TransformPassword(password, ref user.PasswordSalt);
                if (string.Compare(passwordValidate, user.Password) == 0)
                {
                    return(true);
                }
                else
                {
                    uact.FailedLogins += 1;
                    SaveUserActivity(uact);
                }
            }

            return(false);
        }
예제 #2
0
 public override MembershipUser GetUser(string username, bool userIsOnline)
 {
     try
     {
         BTTUser user = GetUser(username);
         if (user != null)
         {
             if (userIsOnline)
             {
                 BTTUserActivity uact = GetActivityForUser(user);
                 SaveUserActivity(uact);
             }
             return(CreateMembershipFromInternalUser(user));
         }
         else
         {
             return(null);
         }
     }
     catch
     {
         throw;
     }
 }
예제 #3
0
        // GET: Admin/BTTusers/DeleteProf/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            BTTUser user = db.BTTUsers.Find(id);

            if (user == null)
            {
                return(HttpNotFound());
            }

            ApplicationDbContext context = new ApplicationDbContext();

            var UserManager  = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            var accountEmail = UserManager.GetEmail(user.ASPNetIdentityID);

            ViewBag.First = user.FirstName;
            ViewBag.Last  = user.LastName;
            ViewBag.Email = accountEmail;

            return(View(user));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                //initialize a user manager
                var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));


                BTTUser user       = db.BTTUsers.Find(id);                        //get Account BeyondTheTutor (DATA)
                var     aspAccount = UserManager.FindById(user.ASPNetIdentityID); //get Account AspAccountIdentity (DATA)

                //information about 3rd party/external logins, for example users who login into our site via Google, Facebook, Twitter etc
                var logins = aspAccount.Logins;

                var accountRoles = UserManager.GetRoles(aspAccount.Id); //get roles

                //viewbag printouts for Target Account
                var accountEmail = aspAccount.Email.ToString(); // get email of account being deleted
                var firstName    = user.FirstName;              // first and
                var lastName     = user.LastName;               // last name
                var accountRole  = UserManager.GetRoles(aspAccount.Id).FirstOrDefault().ToString();
                //eof viewbag printouts


                db.BTTUsers.Remove(user); //remove BeyondTheTutor Account's (DATA)
                db.SaveChanges();


                using (var transaction = context.Database.BeginTransaction())
                {
                    foreach (var login in logins.ToList())
                    {
                        UserManager.RemoveLogin(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                    }

                    if (accountRoles.Count() > 0)
                    {
                        foreach (var item in accountRoles.ToList())
                        {
                            // item should be the name of the role
                            var result = UserManager.RemoveFromRole(aspAccount.Id, item);
                        }
                    }

                    UserManager.Delete(aspAccount);
                    transaction.Commit();
                }

                TempData["f"] = "You have successfully removed a " + accountRole + ": " + firstName + " " + lastName + ", " + accountEmail + "";

                return(RedirectToAction("Index"));
            }
            else
            {
                ViewBag.f = "Something went wrong. Please make sure your action was valid.";
                return(View());
            }
        }
예제 #5
0
 private static void SaveUser(BTTUser user)
 {
     user.ModifiedDate = DateTime.UtcNow;
     user.ModifiedBy   = new Guid(ConfigurationManager.AppSettings["adminGuid"]);
     ActiveRecordMediator <BTTUser> .Save(user);
 }
예제 #6
0
        // See: https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97
        // In this method we will create default User roles and Admin user for login
        private void CreateRolesandUsers()
        {
            // The context that Identity created
            ApplicationDbContext context = new ApplicationDbContext();

            //the main database
            BeyondTheTutorContext db = new BeyondTheTutorContext();

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


            /*roleManager.Delete(roleManager.FindByName(ROLES[0]));
            *  roleManager.Delete(roleManager.FindByName(ROLES[1]));
            *  roleManager.Delete(roleManager.FindByName(ROLES[2]));
            *  roleManager.Delete(roleManager.FindByName(ROLES[3]));*/


            // Create admin role and seed with the admin user/
            // Assumes neither already exists
            if (!roleManager.RoleExists(ROLES[0]))
            {
                // Create role
                var            role = new IdentityRole(ROLES[0]); // role name is "Admin"
                IdentityResult res  = roleManager.Create(role);

                // Create user with this role
                string userPWD   = "admin2020";                // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"];
                string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"];
                var    user      = new ApplicationUser {
                    UserName       = userEmail,
                    EmailConfirmed = true,
                    Email          = userEmail
                };
                // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same
                // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work

                res = UserManager.Create(user, userPWD);

                if (res.Succeeded)
                {
                    var special_user = new BTTUser
                    {
                        FirstName        = "Tracy",
                        LastName         = "Boyson",
                        ASPNetIdentityID = user.Id
                    };

                    var sub_user = new Admin
                    {
                        ID = special_user.ID
                    };

                    sub_user.BTTUser = special_user;
                    db.BTTUsers.Add(special_user);
                    db.Admins.Add(sub_user);
                    db.SaveChangesAsync();
                }

                if (res.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, ROLES[0]);
                }
            }

            // Do we need another role?  i.e. "User"

            // Create admin role and seed with the admin user/
            // Assumes neither already exists
            if (!roleManager.RoleExists(ROLES[1]))
            {
                // Create role
                var            role = new IdentityRole(ROLES[1]); // role name is "Professor"
                IdentityResult res  = roleManager.Create(role);

                // Create user with this role
                string userPWD   = "professor2020";                // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"];
                string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"];
                var    user      = new ApplicationUser
                {
                    UserName       = userEmail,
                    Email          = userEmail,
                    EmailConfirmed = true
                };
                // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same
                // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work

                res = UserManager.Create(user, userPWD);

                if (res.Succeeded)
                {
                    var special_user = new BTTUser
                    {
                        FirstName        = "Becka",
                        LastName         = "Morgan",
                        ASPNetIdentityID = user.Id
                    };

                    var sub_user = new Professor
                    {
                        ID            = special_user.ID,
                        AdminApproved = true
                    };

                    sub_user.BTTUser = special_user;
                    db.BTTUsers.Add(special_user);
                    db.Professors.Add(sub_user);
                    db.SaveChangesAsync();
                }

                if (res.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, ROLES[1]);
                }
            }

            // Create admin role and seed with the admin user/
            // Assumes neither already exists
            if (!roleManager.RoleExists(ROLES[2]))
            {
                // Create role
                var            role = new IdentityRole(ROLES[2]); // role name is "Student"
                IdentityResult res  = roleManager.Create(role);

                // Create user with this role
                string userPWD   = "student2020";                // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"];
                string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"];
                var    user      = new ApplicationUser
                {
                    UserName       = userEmail,
                    Email          = userEmail,
                    EmailConfirmed = true
                };
                // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same
                // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work

                res = UserManager.Create(user, userPWD);

                if (res.Succeeded)
                {
                    var special_user = new BTTUser
                    {
                        FirstName        = "Brandon",
                        LastName         = "Linton",
                        ASPNetIdentityID = user.Id
                    };

                    var sub_user = new Student
                    {
                        ID             = special_user.ID,
                        ClassStanding  = "Junior",
                        GraduatingYear = 2022
                    };

                    sub_user.BTTUser = special_user;
                    db.BTTUsers.Add(special_user);
                    db.Students.Add(sub_user);
                    db.SaveChangesAsync();
                }

                if (res.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, ROLES[2]);
                }
            }

            // Create admin role and seed with the admin user/
            // Assumes neither already exists
            if (!roleManager.RoleExists(ROLES[3]))
            {
                // Create role
                var            role = new IdentityRole(ROLES[3]); // role name is "Tutor"
                IdentityResult res  = roleManager.Create(role);

                // Create user with this role
                string userPWD   = "tutor2020";                // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"];
                string userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"];
                var    user      = new ApplicationUser
                {
                    UserName       = userEmail,
                    Email          = userEmail,
                    EmailConfirmed = true
                };
                // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same
                // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work

                res = UserManager.Create(user, userPWD);

                if (res.Succeeded)
                {
                    var special_user = new BTTUser
                    {
                        FirstName        = "Victoria",
                        LastName         = "Rhine",
                        ASPNetIdentityID = user.Id
                    };

                    var sub_user = new Tutor
                    {
                        ID            = special_user.ID,
                        VNumber       = "V00000000",
                        ClassOf       = 2020,
                        AdminApproved = true
                    };

                    sub_user.BTTUser = special_user;
                    db.BTTUsers.Add(special_user);
                    db.Tutors.Add(sub_user);
                    db.SaveChangesAsync();
                }

                if (res.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, ROLES[3]);
                }


                //tutor number two
                userPWD   = "tutor2020";                 // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"];
                userEmail = "*****@*****.**"; // System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"];
                var tutor = new ApplicationUser
                {
                    UserName       = userEmail,
                    Email          = userEmail,
                    EmailConfirmed = true
                };

                res = UserManager.Create(tutor, userPWD);

                if (res.Succeeded)
                {
                    var special_user = new BTTUser
                    {
                        FirstName        = "Shay",
                        LastName         = "Green",
                        ASPNetIdentityID = tutor.Id
                    };

                    var sub_user = new Tutor
                    {
                        ID            = special_user.ID,
                        VNumber       = "V11111111",
                        ClassOf       = 2021,
                        AdminApproved = true
                    };

                    sub_user.BTTUser = special_user;
                    db.BTTUsers.Add(special_user);
                    db.Tutors.Add(sub_user);
                    db.SaveChangesAsync();
                }

                if (res.Succeeded)
                {
                    var result1 = UserManager.AddToRole(tutor.Id, ROLES[3]);
                }
            }

            /*{
             *
             *  IdentityResult res;
             *
             *  // Create user with this role
             *  string userPWD = "student2020";// System.Web.Configuration.WebConfigurationManager.AppSettings["AdminPassword"];
             *  string userEmail = "*****@*****.**";// System.Web.Configuration.WebConfigurationManager.AppSettings["AdminEmail"];
             *  var user = new ApplicationUser
             *  {
             *      UserName = userEmail,
             *      Email = userEmail,
             *      EmailConfirmed = true
             *  };
             *  // Username and email must be the same unless you want to make changes to the login code, which assumes they are the same
             *  // It will appear to work but once you clear your cache (to delete the cookie) or use another browser it won't work
             *
             *  res = UserManager.Create(user, userPWD);
             *
             *  if (res.Succeeded)
             *  {
             *      var special_user = new BTTUser
             *      {
             *          FirstName = "Maksim",
             *          LastName = "Stoyanov",
             *          ASPNetIdentityID = user.Id
             *      };
             *
             *      var sub_user = new Student
             *      {
             *          ID = special_user.ID,
             *          ClassStanding = "Senior",
             *          GraduatingYear = 2020
             *      };
             *
             *      sub_user.BTTUser = special_user;
             *      db.BTTUsers.Add(special_user);
             *      db.Students.Add(sub_user);
             *      db.SaveChangesAsync();
             *  }
             *
             *  UserManager.AddToRole(user.Id, ROLES[2]);
             * }*/

            /*
             * // creating Creating Professor role
             * if (!roleManager.RoleExists(ROLES[1])) // Professor Role
             * {
             *  var role = new IdentityRole();
             *  role.Name = ROLES[1];
             *  roleManager.Create(role);
             * }*/
        }
예제 #7
0
        public async Task <ActionResult> Register(RegistrationTypes model)
        {
            bool isStudent, isTutor, isProfessor, _error;

            isStudent = isTutor = isProfessor = _error = false;
            string _email, _password, _firstname, _lastname, _confmessage, _class_standing, _vnumber;

            _email = _password = _firstname = _lastname = _class_standing = _vnumber = null;

            short _classof = 0000;

            var response = Request["g-recaptcha-response"];
            //secret that was generated in key value pair
            string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["ReCapSecretKey"];

            var client = new WebClient();
            var reply  =
                client.DownloadString(
                    string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));

            var captchaResponse = JsonConvert.DeserializeObject <CaptchaResponse>(reply);

            //when response is false check for the error message
            if (captchaResponse.Success.Equals(false))
            {
                if (captchaResponse.ErrorCodes.Count <= 0)
                {
                    return(View());
                }

                var error = captchaResponse.ErrorCodes[0].ToLower();
                switch (error)
                {
                case ("missing-input-secret"):
                    ViewBag.Message = "The secret parameter is missing.";
                    break;

                case ("invalid-input-secret"):
                    ViewBag.Message = "The secret parameter is invalid or malformed.";
                    break;

                case ("missing-input-response"):
                    ViewBag.Message = "The response parameter is missing.";
                    break;

                case ("invalid-input-response"):
                    ViewBag.Message = "The response parameter is invalid or malformed.";
                    break;

                default:
                    ViewBag.Message = "Error occured. Please try again";
                    break;
                }

                _error = true;
            }
            else
            {
                ViewBag.Message = "Valid";
            }

            if (ModelState.IsValid && !_error)
            {
                if (model.studentVM != null)
                {
                    isStudent       = true;
                    _firstname      = model.studentVM.FirstName;
                    _lastname       = model.studentVM.LastName;
                    _password       = model.studentVM.Password;
                    _class_standing = model.studentVM.ClassStanding;
                    _classof        = model.studentVM.GraduatingYear;
                    _email          = model.studentVM.Email;
                }
                if (model.tutorVM != null)
                {
                    isTutor    = true;
                    _firstname = model.tutorVM.FirstName;
                    _lastname  = model.tutorVM.LastName;
                    _password  = model.tutorVM.Password;
                    _vnumber   = model.tutorVM.VNumber;
                    _classof   = model.tutorVM.ClassOf;
                    _email     = model.tutorVM.Email;
                }
                if (model.professorVM != null)
                {
                    isProfessor = true;
                    _firstname  = model.professorVM.FirstName;
                    _lastname   = model.professorVM.LastName;
                    _password   = model.professorVM.Password;
                    _email      = model.professorVM.Email;
                }

                if (isTutor || isProfessor)
                {
                    _confmessage    = "Confirm your account email and wait for admin approval";
                    ViewBag.Message = "Once you've confirmed that " + _email + " is your email address and recieved admin approval, you'll be able to use your account.";
                }
                else
                {
                    ViewBag.Message = "Once you've confirmed that " + _email + " is your email address, you can continue to your account.";
                    _confmessage    = "Confirm your account email";
                }

                //var user = new ApplicationUser { UserName = model.FirstName + " " + model.LastName, Email = model.Email };
                var user = new ApplicationUser
                {
                    UserName = _email,
                    Email    = _email
                };

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

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

                    string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, _confmessage, _firstname);

                    TempData["Message"] = ViewBag.Message;

                    // Won't be shown to the user if we redirect to home
                    ViewBag.Message = "Check your email and confirm your account; you must be confirmed "
                                      + "if you ever need to recover your password.";
                    // TODO: Handle errors, do this upon refactoring into repository pattern
                    // Succeeded in creating a new Identity account, so let's create a new


                    var special_user = new BTTUser
                    {
                        FirstName        = _firstname,
                        LastName         = _lastname,
                        ASPNetIdentityID = user.Id
                    };

                    BeyondTheTutorContext db = new BeyondTheTutorContext();

                    if (model.studentVM != null)
                    {
                        var sub_user = new Student
                        {
                            ClassStanding  = _class_standing,
                            GraduatingYear = _classof
                        };

                        sub_user.BTTUser = special_user;
                        db.BTTUsers.Add(special_user);
                        db.Students.Add(sub_user);
                        UserManager.AddToRole(user.Id, "Student");
                    }
                    if (model.tutorVM != null)
                    {
                        var sub_user = new Tutor
                        {
                            VNumber = _vnumber,
                            ClassOf = _classof,
                        };

                        sub_user.BTTUser = special_user;
                        db.BTTUsers.Add(special_user);
                        db.Tutors.Add(sub_user);
                        UserManager.AddToRole(user.Id, "Tutor");
                    }
                    if (model.professorVM != null)
                    {
                        var sub_user = new Professor
                        {
                        };
                        sub_user.BTTUser = special_user;
                        db.BTTUsers.Add(special_user);
                        db.Professors.Add(sub_user);
                        UserManager.AddToRole(user.Id, "Professor");
                    }


                    await db.SaveChangesAsync();

                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

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

            // If we got this far, something failed, redisplay form
            if (model.professorVM != null)
            {
                ViewBag.validationError = "professor";
            }
            else if (model.tutorVM != null)
            {
                ViewBag.validationError = "tutor";
            }
            else if (model.studentVM != null)
            {
                ViewBag.validationError = "student";
            }

            ViewBag.ReCapKey = System.Web.Configuration.WebConfigurationManager.AppSettings["ReCapKey"];

            return(View(model));
        }