示例#1
0
        //[Authorize(Roles = "Administrator")]
        public IActionResult AddNewUser()
        {
            var model = new AddNewUserViewModel();

            model.Roles = new SelectList(_dbcontext.Roles);
            return(View(model));
        }
示例#2
0
        public async Task <IActionResult> AddNewUser(AddNewUserViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = vm.Email, Email = vm.Email
                };
                var result = await _userManager.CreateAsync(user, vm.Password);

                if (result.Succeeded)
                {
                    var addRole = await _userManager.AddToRoleAsync(user, vm.RoleId);

                    if (addRole.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
                }
            }
            return(View(vm));
        }
示例#3
0
        public async Task <bool> AddNewUserAsync(ClaimsPrincipal claim, AddNewUserViewModel data)
        {
            string userId = ExtBusinessLogic.UserValue(claim);

            data.CreatedBy = userId;
            ApplicationUser user            = _mapper.Map <ApplicationUser>(data);
            bool            userAlreadyExit = _userManager.Users.Any(x => x.UserName == user.UserName);

            if (userAlreadyExit)
            {
                throw new WebApiApplicationException(StatusCodes.Status409Conflict, ErrorMessages.ErrorCreatingLocalUser,
                                                     new object[]
                {
                    new
                    {
                        Code        = ErrorMessages.UserExistCode,
                        Description = ErrorMessages.UserExistDescription.Replace("[USERNAME]", user.UserName)
                    }
                });
            }

            var result = await _userManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                throw new WebApiApplicationException(StatusCodes.Status409Conflict, ErrorMessages.ErrorCreatingLocalUser, result.Errors.ToList());
            }

            await SendConfirmationEmail(user);

            return(true);
        }
        public IActionResult UpdateUserDetails(AddNewUserViewModel userDetails)
        {
            string sessionStatus = ((int)HttpContext.Session.GetInt32("sessionCompanyStatus")).ToRole();

            if (sessionStatus == (Role.Admin).ToString())
            {
                users.Update(userDetails.User);
                return(RedirectToAction(nameof(AllUsers)));
            }
            return(Unauthorized());
        }
        public IActionResult addNewUser(AddNewUserViewModel addedUser)
        {
            string sessionStatus = ((int)HttpContext.Session.GetInt32("sessionCompanyStatus")).ToRole();

            if (sessionStatus == (Role.Admin).ToString())
            {
                users.Insert(addedUser.User);
                return(RedirectToAction("Index", "Home"));
            }
            return(Unauthorized());
        }
        public IActionResult UserEdit(int id)
        {
            string sessionStatus = ((int)HttpContext.Session.GetInt32("sessionCompanyStatus")).ToRole();

            if (sessionStatus == (Role.Admin).ToString())
            {
                User u = users.Select(id);
                AddNewUserViewModel vm = new AddNewUserViewModel();
                vm.User = u;
                return(View(vm));
            }
            return(Unauthorized());
        }
示例#7
0
        public ActionResult Create(string message)
        {
            ViewBag.Msg      = message;
            ViewBag.Branches = branchRepo.GetAll().AsEnumerable().Select(i => new SelectListItem
            {
                Text  = i.Name,
                Value = i.ID.ToString()
            });

            ViewBag.Roles = roleRepo.GetAll().AsEnumerable().Select(i => new SelectListItem
            {
                Text  = i.Name,
                Value = i.ID.ToString()
            });
            var model = new AddNewUserViewModel();

            return(View(model));
        }
        public ActionResult Create(AddNewUserViewModel model)
        {
            ViewBag.Msg      = "";
            ViewBag.Branches = branchRepo.GetAll().AsEnumerable().Select(i => new SelectListItem
            {
                Text  = i.Name,
                Value = i.ID.ToString()
            });

            ViewBag.Roles = roleRepo.GetAll().AsEnumerable().Select(i => new SelectListItem
            {
                Text  = i.Name,
                Value = i.ID.ToString()
            });

            if (ModelState.IsValid)
            {
                //unique username and email
                if (!userLogic.IsUniqueUsername(model.Username))
                {
                    ViewBag.Msg = "Username must be unique";
                    return(View());
                }
                if (!userLogic.IsUniqueEmail(model.Email))
                {
                    ViewBag.Msg = "Email must be unique";
                    return(View());
                }

                string autoGenPassword = utilLogic.GetRandomPassword();
                string hashedPassword  = UserLogic.HashPassword(autoGenPassword);
                User   user            = new Core.Models.User {
                    FirstName = model.FirstName, LastName = model.LastName, Username = model.Username, PasswordHash = hashedPassword, Email = model.Email, PhoneNumber = model.PhoneNumber, Role = roleRepo.GetById(model.RoleId), Branch = branchRepo.GetById(model.BranchId)
                };

                userRepo.Insert(user);

                userLogic.SendPasswordToUser(model.LastName + " " + model.FirstName, model.Email, model.Username, autoGenPassword);

                return(RedirectToAction("Create", new { message = "User added" }));
            }
            ViewBag.Msg = "Please enter a valid name";
            return(View());
        }
        public async Task <IActionResult> AddUser(AddNewUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index"));
            }

            var newUser = new IdentityUser
            {
                UserName = model.UserName,
                Email    = model.Email
            };

            IdentityResult result = await _userManager.CreateAsync(newUser, model.Password);

            if (result.Succeeded)
            {
                _userManager.AddToRoleAsync(newUser, model.Rol).Wait();
            }

            return(RedirectToAction("Index"));
        }
示例#10
0
        public ActionResult AddNewUser(AddNewUserViewModel model)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext()));

            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true
            };

            if (ModelState.IsValid)
            {
                Regex  phoneRegex      = new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
                string FormarttedPhone = phoneRegex.Replace(model.Phone, "($1) $2-$3");

                var user = new ApplicationUser()
                {
                    UserName = model.UserName, Email = model.Email, PhoneNumber = FormarttedPhone
                };
                IdentityResult result = manager.Create(user, model.Password);
                if (result.Succeeded)
                {
                    manager.AddToRole(user.Id, model.Role);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                    return(View(model));
                }

                return(RedirectToAction("ManageUsers"));
            }
            return(View(model));
        }
示例#11
0
        public ActionResult Create(AddNewUserViewModel model)
        {
            ViewBag.Msg      = "";
            ViewBag.Branches = branchRepo.GetAll().AsEnumerable().Select(i => new SelectListItem
            {
                Text  = i.Name,
                Value = i.ID.ToString()
            });

            ViewBag.Roles = roleRepo.GetAll().AsEnumerable().Select(i => new SelectListItem
            {
                Text  = i.Name,
                Value = i.ID.ToString()
            });

            if (ModelState.IsValid)
            {
                //unique username and email that has been been confirmed by any user.
                if (!userLogic.IsUniqueUsername(model.Username))
                {
                    ViewBag.Msg = "Username must be unique";
                    return(View());
                }
                if (!userLogic.IsUniqueEmail(model.Email))
                {
                    // edit, email musn't be unique
                    // only if email has been confirmed by another user.
                    // if email has been confirmed by any user.
                    // check if anyone with email has confirmed it.
                    if (userLogic.IsEmailConfirmed(model.Email))
                    {
                        ViewBag.Msg = "Email must be unique";
                        return(View());
                    }
                }

                string autoGenPassword  = utilLogic.GetRandomPassword();
                string hashedPassword   = UserLogic.HashPassword(autoGenPassword);
                string verificationCode = Guid.NewGuid().ToString();

                User user = new Core.Models.User {
                    TokenExpiryDate = DateTime.Now.AddMinutes(tokenExpiryMinutes), VerificationCode = verificationCode, FirstName = model.FirstName, LastName = model.LastName, Username = model.Username, PasswordHash = hashedPassword, Email = model.Email, PhoneNumber = model.PhoneNumber, EmailConfirmed = false, Role = roleRepo.GetById(model.RoleId), Branch = branchRepo.GetById(model.BranchId)
                };

                userRepo.Insert(user);

                // send email confirmation
                var callbackUrl = Url.Action("ConfirmEmail", "UserManager", new { userId = user.ID, code = verificationCode }, protocol: Request.Url.Scheme);

                try
                {
                    userLogic.SendEmailConfirmationTokenToUser(callbackUrl, model.Email);
                    userLogic.SendPasswordToUser(model.LastName + " " + model.FirstName, model.Email, model.Username, autoGenPassword);
                }
                catch (Exception)
                {
                    return(RedirectToAction("Create", new { message = "[User added : " + autoGenPassword + "][ CallbackUrl : " + callbackUrl + " ] .Send Mail Failed." }));
                }

                // tell them confirmation link has been sent to user mail
                // you dont need to show the user pass and call back since mail send was successful.
                return(RedirectToAction("Create", new { message = "[User added : " + model.Username + "][Confirmation link and password has been sent to user mail]" }));
            }
            ViewBag.Msg = "Please enter a valid name";
            return(View());
        }
示例#12
0
        public async Task <ActionResult> AddNewUser(
            [Bind(
                 Include =
                     "Email,Password,UserName,EnrollmentDate,PhoneNumber,PhoneNumberConfirmed" +
                     ",TwoFactorEnabled,Address,LockoutEnabled,LockoutEndDateUtc,AccessFailedCount,EmailConfirmed,ComboItemsStrTable"
                 )] AddNewUserViewModel addNewUserViewModel)
        {
            MyIdentityManager myIdentityManager = new MyIdentityManager();

            if (!ModelState.IsValid)  //if the modelstate is not valid, pass the errors to a string, and display via httpnotfount. Not the best way, but works
            {
                #region error reporting
                var modelStateerrors = ModelState.Where(x => x.Value.Errors.Count > 0)
                                       .Select(x => new { x.Key, x.Value.Errors }).ToArray();
                string errorList = "";


                if (modelStateerrors != null)
                {
                    foreach (var modelerr in modelStateerrors)
                    {
                        foreach (var modelerro in modelerr.Errors)
                        {
                            errorList = errorList + " | " + modelerro.ErrorMessage;
                        }
                    }
                }
                //return PartialView("CustomError", errorList);
                #endregion
            }
            //our user, to ASPNET user. Relying to ASPNET's input error checks etc
            DateTime temp = DateTime.Now;
            var      user = new ApplicationUser {
                Email                = addNewUserViewModel.Email,
                UserName             = addNewUserViewModel.Email,
                Address              = addNewUserViewModel.Address,
                EnrollmentDate       = addNewUserViewModel.EnrollmentDate ?? temp, //if the user leaves that blank, fill it with datetime.now
                PhoneNumber          = addNewUserViewModel.PhoneNumber,
                PhoneNumberConfirmed = addNewUserViewModel.PhoneNumberConfirmed,
                TwoFactorEnabled     = addNewUserViewModel.TwoFactorEnabled,
                LockoutEnabled       = addNewUserViewModel.LockoutEnabled,
                LockoutEndDateUtc    = addNewUserViewModel.LockoutEndDateUtc,
                AccessFailedCount    = addNewUserViewModel.AccessFailedCount ?? 0, //if the user leaves that blank, make it 0
                EmailConfirmed       = addNewUserViewModel.EmailConfirmed
            };
            var  createUserResult         = myIdentityManager.CreateNewUser(user, addNewUserViewModel.Password);
            bool addComboItemToUserResult = false;
            if (createUserResult.Succeeded)
            {
                //foreach (var selectListItem in addNewUserViewModel.ComboItems)
                //{
                //    MyComboItemManager myComboItemManager = new MyComboItemManager();
                //    if (selectListItem.Selected)
                //    {
                //        addComboItemToUserResult = myComboItemManager.AddComboItemToUser(user.Id, selectListItem.Value);
                //    }
                //}

                //if (addComboItemToUserResult)
                // the above is the proper way. DropDownList returns a string[] instead a fking IEnumerable<SelectListItem>. FK that

                MyComboItemManager myComboItemManager = new MyComboItemManager();
                addComboItemToUserResult = myComboItemManager.UpdateComboItemsforUser(user.Id, addNewUserViewModel.ComboItemsStrTable);
                myComboItemManager.DisposeAll();
                myIdentityManager.Dispose();
                return(Json(new { success = true }));
                //else
                //    return HttpNotFound("Could not add Comboitems to User");
            }
            else
            {
                return(HttpNotFound("User data not valid, please try again"));
            }
        }
示例#13
0
        //GET: AdminMainPage/AddUser
        public async Task <ActionResult> AddNewUser()
        {
            AddNewUserViewModel addNewUserViewModel = new AddNewUserViewModel();

            return(PartialView(addNewUserViewModel));
        }
示例#14
0
        public async Task <ActionResult <ApiResponse <AddNewUserViewModel> > > AddUser([FromBody] AddNewUserViewModel data)
        {
            var result = await _auth.AddNewUserAsync(User, data);

            if (result)
            {
                return(StatusCodeResult(StatusCodes.Status201Created, null, InfoMessages.CommonInfoMessage));
            }

            return(BadRequest(ErrorMessages.CommonErrorMessage));
        }