예제 #1
0
 public ActionResult Login(UserBasicModel user)
 {
     using (DbContextModel db = new DbContextModel())
     {
         var currentUser = db.UserAccounts.Where(u => u.Username == user.Username).FirstOrDefault();
         if (currentUser != null)
         {
             if ((string.Compare(Crypto.Hash(user.Password), currentUser.Password) == 0))
             {
                 System.Web.HttpContext.Current.Session["UserId"]   = currentUser.UserId.ToString();
                 System.Web.HttpContext.Current.Session["Username"] = currentUser.Username.ToString().ToLower();
                 System.Web.HttpContext.Current.Session["Role"]     = currentUser.Role.ToString();
                 if (currentUser.Role == Roles.Admin)
                 {
                     return(RedirectToAction("AdminDashboard", "Admin"));
                 }
                 return(RedirectToAction("DashboardIndex", "Dashboard"));
             }
             else
             {
                 ViewBag.Message = "Podane hasło jest nieprawidłowe";
             }
         }
         else
         {
             ViewBag.Message = "Podany użytkownik nie istnieje";
         }
     }
     return(View());
 }
예제 #2
0
        public ActionResult ChangePasswordAdmin(string confirmOldPassword, string newPassword, string confirmNewPassword)
        {
            using (DbContextModel db = new DbContextModel())
            {
                int UserId = Convert.ToInt32(Session["UserId"]);

                UserBasicModel userToEdit        = db.UserAccounts.FirstOrDefault(u => u.UserId.Equals(UserId));
                var            oldPasswordHashed = Crypto.Hash(confirmOldPassword);

                if ((string.Compare(userToEdit.Password, oldPasswordHashed) == 0))
                {
                    if (newPassword == confirmNewPassword)
                    {
                        userToEdit.Password        = Crypto.Hash(newPassword);
                        userToEdit.ConfirmPassword = Crypto.Hash(confirmNewPassword);
                        db.Entry(userToEdit).State = EntityState.Modified;
                        db.SaveChanges();
                        ViewBag.MessageInfoRight = "Hasło zostało zmienione.";
                        return(View());
                    }
                    else
                    {
                        ViewBag.MessageInfoWrong = "Potwierdź poprawnie nowe hasło.";
                        return(View());
                    }
                }
                else
                {
                    ViewBag.MessageInfoWrong = "Podałeś nieprawidłowe aktualne hasło.";
                    return(View());
                }
            }
        }
예제 #3
0
        public ActionResult Register(UserBasicModel userAccount)
        {
            var rolesList = new List <Roles>();

            rolesList.Add(Roles.Pracownik);
            rolesList.Add(Roles.Klient);
            ViewBag.Roles = new SelectList(rolesList);
            if (ModelState.IsValid)
            {
                using (DbContextModel db = new DbContextModel())
                {
                    var user = db.UserAccounts.SingleOrDefault(u => u.Username == userAccount.Username);
                    if (user != null)
                    {
                        ViewBag.Message = "Użytkownik o podanym loginie już istnieje.";
                    }
                    else
                    {
                        userAccount.Username        = userAccount.Username.ToLower();
                        userAccount.Password        = Crypto.Hash(userAccount.Password);
                        userAccount.ConfirmPassword = Crypto.Hash(userAccount.ConfirmPassword);
                        byte[] data = System.Text.Encoding.ASCII.GetBytes("0");
                        db.UserAccounts.Add(userAccount);
                        db.SaveChanges();
                        ModelState.Clear();
                        ViewBag.Message = "Poprawnie się zarejestrowałeś " + userAccount.Username;
                    }
                }
            }
            return(View());
        }
예제 #4
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            using (DbContextModel db = new DbContextModel())
            {
                var adminAccount = db.UserAccounts.Where(x => x.Role == Roles.Admin).FirstOrDefault();
                if (adminAccount == null)
                {
                    var password = Convert.ToBase64String(System.Security.Cryptography.SHA256.Create()
                                                          .ComputeHash(Encoding.UTF8.GetBytes("filip123")));
                    var confirmPassword = Convert.ToBase64String(System.Security.Cryptography.SHA256.Create()
                                                                 .ComputeHash(Encoding.UTF8.GetBytes("filip123")));
                    adminAccount = new UserBasicModel()
                    {
                        Username = "******", Email = "*****@*****.**", MobileNumber = "511 114 421", Role = Roles.Admin
                    };
                    adminAccount.Password        = password;
                    adminAccount.ConfirmPassword = confirmPassword;
                    byte[] image = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/Images/icons8-administrator-mężczyzna-480.png"));
                    adminAccount.UserPhoto = image;
                    db.UserAccounts.Add(adminAccount);
                    db.SaveChanges();
                }
            }
        }
예제 #5
0
 public ActionResult AddManagerAccount(UserBasicModel manager)
 {
     using (DbContextModel db = new DbContextModel())
     {
         var user = db.UserAccounts.SingleOrDefault(u => u.Username == manager.Username);
         if (user != null)
         {
             ViewBag.Message = "Użytkownik o podanym loginie już istnieje.";
         }
         else
         {
             var password = Convert.ToBase64String(System.Security.Cryptography.SHA256.Create()
                                                   .ComputeHash(Encoding.UTF8.GetBytes(manager.Password)));
             var confirmPassword = Convert.ToBase64String(System.Security.Cryptography.SHA256.Create()
                                                          .ComputeHash(Encoding.UTF8.GetBytes(manager.ConfirmPassword)));
             manager.Username        = manager.Username.ToLower();
             manager.Password        = password;
             manager.ConfirmPassword = confirmPassword;
             manager.Role            = Roles.Manager;
             byte[] data = System.Text.Encoding.ASCII.GetBytes("0");
             db.UserAccounts.Add(manager);
             db.SaveChanges();
         }
     }
     return(View("AdminDashboard"));
 }
예제 #6
0
 // GET: Admin
 public ActionResult AdminDashboard()
 {
     using (DbContextModel db = new DbContextModel())
     {
         int            UserId       = Convert.ToInt32(Session["UserId"]);
         UserBasicModel adminAccount = db.UserAccounts.FirstOrDefault(u => u.UserId.Equals(UserId));
         return(View(adminAccount));
     }
 }
예제 #7
0
        public ActionResult EditAccountAdmin()
        {
            using (DbContextModel db = new DbContextModel())
            {
                int            userId     = Convert.ToInt32(Session["UserId"]);
                UserBasicModel userToEdit = db.UserAccounts.Where(u => u.UserId.Equals(userId)).FirstOrDefault();

                return(View(userToEdit));
            }
        }
예제 #8
0
        public ActionResult ChangePassword()
        {
            using (DbContextModel db = new DbContextModel())
            {
                int UserId = Convert.ToInt32(Session["UserId"]);

                UserBasicModel userToEdit = db.UserAccounts.FirstOrDefault(u => u.UserId.Equals(UserId));

                return(View(userToEdit));
            }
        }
예제 #9
0
        public async Task <ActionResult> Create(UserViewModel model)
        {
            try
            {
                UserBasicModel userModel = model.UserModel;
                var            password  = "******";

                var user = Mapper.Map <AspNetUser>(userModel);

                var newUser = new ApplicationUser
                {
                    UserName = user.Email,
                    Email    = user.Email
                };

                if (model.NewPassword != null)
                {
                    password = model.NewPassword;
                }

                var result = await UserManager.CreateAsync(newUser, password);

                if (result.Succeeded)
                {
                    if (model.IsAdmin)
                    {
                        UserManager.AddToRole(newUser.Id, "Admin");
                    }

                    return(RedirectToAction("Index"));
                }
                else
                {
                    Debug.Print(result.ToString());
                    var errorString = "User not created: \n";
                    foreach (var error in result.Errors)
                    {
                        errorString += error + "\n";
                    }
                    ModelState.AddModelError(string.Empty, errorString);

                    return(View());
                }
            }
            catch (Exception e)
            {
                var errorString = "User not created: \n";
                errorString += e.Message + "\n";


                ModelState.AddModelError(string.Empty, errorString);
                return(View());
            }
        }
예제 #10
0
 public ActionResult ProfileDetails(int id)
 {
     using (DbContextModel db = new DbContextModel())
     {
         UserBasicModel userDetails = db.UserAccounts.Where(u => u.UserId.Equals(id)).FirstOrDefault();
         if (userDetails.Skills != null)
         {
             userDetails.SkillsArray = userDetails.Skills.Split(',').ToArray();
             foreach (var skillId in userDetails.SkillsArray)
             {
                 var skillIdInt = Convert.ToInt32(skillId);
                 var skill      = db.Skills.Where(x => x.SkillId.Equals(skillIdInt)).FirstOrDefault();
                 userDetails.SkillsCollection.Add(skill);
             }
         }
         return(View(userDetails));
     }
 }
예제 #11
0
        public ActionResult EditAccount()
        {
            DbContextModel db = new DbContextModel();

            int UserId = Convert.ToInt32(Session["UserId"]);

            UserBasicModel userToEdit = db.UserAccounts.FirstOrDefault(u => u.UserId.Equals(UserId));

            if (userToEdit.Skills != null)
            {
                userToEdit.SkillsArray = userToEdit.Skills.Split(',').ToArray();
            }

            var             skills = db.Skills.ToList();
            MultiSelectList list   = new MultiSelectList(skills, "SkillId", "SkillName");

            ViewBag.Skills = list;

            return(View(userToEdit));
        }
예제 #12
0
        public ActionResult EditAccount(UserBasicModel userAfterEdit, HttpPostedFileBase file)
        {
            int UserId = Convert.ToInt32(Session["UserId"]);

            using (DbContextModel db = new DbContextModel())
            {
                if (userAfterEdit.SkillsArray != null)
                {
                    userAfterEdit.Skills = string.Join(",", userAfterEdit.SkillsArray);
                }

                UserBasicModel user = db.UserAccounts.FirstOrDefault(u => u.UserId.Equals(UserId));
                user.MobileNumber  = userAfterEdit.MobileNumber;
                user.DisplayedRole = userAfterEdit.DisplayedRole;
                user.Description   = userAfterEdit.Description;
                if (file != null)
                {
                    byte[] data = FileHandler.GetBytesFromFile(file);
                    user.UserPhoto = data;
                }
                user.Skills          = userAfterEdit.Skills;
                db.Entry(user).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                }
                catch
                {
                    ViewBag.MessageAfterEditProfileDetails = "Edycja danych nie powiodła się";
                }
                ViewBag.MessageAfterEditProfileDetails = "Edycja danych przebiegła pomyślnie";
                if (user.SkillsArray != null)
                {
                    user.SkillsArray = user.Skills.Split(',').ToArray();
                }
                var             skills = db.Skills.ToList();
                MultiSelectList list   = new MultiSelectList(skills, "SkillId", "SkillName");
                ViewBag.Skills = list;
                return(View(user));
            }
        }
예제 #13
0
        public ActionResult Delete(UserBasicModel model)
        {
            //Do not allow deletion of the main accounts
            var adminAccounts = DataContext.AspNetUsers.Where(u =>
                                                              u.UserName == "*****@*****.**" ||
                                                              u.UserName == "*****@*****.**" ||
                                                              u.UserName == "*****@*****.**"
                                                              ).ToList();

            if (adminAccounts.Any(a => a.Id == model.Id))
            {
                AddClientMessage(ClientMessage.Warning, "This is a reserved user which cannot be deleted");
                return(View(model));
            }

            if (DataContext.Deals.Any(x => x.Creator_User_Id == model.Id))
            {
                try
                {
                    //Move all Wonders to a default admin user
                    var adminUser     = DataContext.AspNetUsers.FirstOrDefault(u => u.UserName.Equals("*****@*****.**"));
                    var wondersToMove = DataContext.Deals.Where(w => w.Creator_User_Id == model.Id);
                    foreach (var deal in wondersToMove)
                    {
                        deal.Creator_User_Id = adminUser.Id;
                    }
                }
                catch (Exception e)
                {
                    //return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "This user has created Wonders - please remove these before attempting to delete this user");
                    AddClientMessage(ClientMessage.Warning, "User has created wonders, so cannot be deleted");
                    return(View(model));
                }
            }

            var user      = DataContext.AspNetUsers.FirstOrDefault(u => u.Id == model.Id);
            var userPrefs = DataContext.Preferences.FirstOrDefault(u => u.UserId == model.Id);

            if (userPrefs != null)
            {
                DataContext.Preferences.Remove(userPrefs);
            }

            if (user != null)
            {
                try
                {
                    user.MyRejects.Clear();
                    user.MyWonders.Clear();
                    UserManager.RemoveFromRoles(model.Id, UserManager.GetRoles(model.Id).ToArray());

                    foreach (var login in DataContext.AspNetUserLogins.Where(u => u.UserId == user.Id))
                    {
                        DataContext.AspNetUserLogins.Remove(login);
                    }

                    DataContext.AspNetUsers.Remove(user);
                }
                catch (Exception e)
                {
                    AddClientMessage(ClientMessage.Warning, "User cannot be deleted");
                    return(View(model));
                }
            }

            return(RedirectToAction("Index"));
        }
예제 #14
0
        public async Task <ActionResult> Edit(UserViewModel model)
        {
            try
            {
                UserBasicModel userModel = model.UserModel;

                var user = await UserManager.FindByIdAsync(userModel.Id);

                user.UserName = userModel.Email;
                user.Email    = userModel.Email;

                var updateUserResult = await UserManager.UpdateAsync(user);

                if (updateUserResult.Succeeded)
                {
                    //Set PW and admin if required
                    if (model.NewPassword != null)
                    {
                        var pwChangeResult = await UserManager.ChangePasswordAsync(model.UserModel.Id, model.OldPassword, model.NewPassword);

                        if (!pwChangeResult.Succeeded)
                        {
                            Debug.Print(pwChangeResult.ToString());
                            var errorString = "Password not updated: \n";
                            foreach (var error in pwChangeResult.Errors)
                            {
                                errorString += error + "\n";
                            }
                            ModelState.AddModelError(string.Empty, errorString);

                            return(View());
                        }
                    }

                    if (model.IsAdmin)
                    {
                        if (!UserManager.IsInRole(model.UserModel.Id, "Admin"))
                        {
                            UserManager.AddToRole(model.UserModel.Id, "Admin");
                        }
                    }
                    else
                    {
                        if (UserManager.IsInRole(model.UserModel.Id, "Admin"))
                        {
                            UserManager.RemoveFromRole(model.UserModel.Id, "Admin");
                        }
                    }

                    return(RedirectToAction("Index"));
                }
                else
                {
                    Debug.Print(updateUserResult.ToString());
                    var errorString = "User not updated: \n";
                    foreach (var error in updateUserResult.Errors)
                    {
                        errorString += error + "\n";
                    }
                    ModelState.AddModelError(string.Empty, errorString);

                    return(View());
                }


                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                return(View());
            }
        }