public ActionResult AddUser(AddUserVM vm)
        {
            var roleManager = new RoleManager <AppRole>(new RoleStore <AppRole>(new EntityRepo()));
            var userManager = new UserManager <AppUser>(new UserStore <AppUser>(new EntityRepo()));

            if (vm.Password != vm.ConfirmPassword)
            {
                ModelState.AddModelError("", "The password and confirm password fields do not match.");
            }


            if (!ModelState.IsValid)
            {
                vm.SetRoles(roleManager);
                return(View(vm));
            }
            else
            {
                var selectedRole = roleManager.FindById(vm.SelectedRoleId).Name;
                var user         = new AppUser
                {
                    FirstName = vm.FirstName,
                    LastName  = vm.LastName,
                    Email     = vm.Email,
                    UserName  = vm.Email
                };
                userManager.Create(user, vm.Password);
                userManager.AddToRole(user.Id, selectedRole);
                return(RedirectToAction("Users"));
            }
        }
Example #2
0
        public ActionResult Add(AddUserVM newUser)
        {
            IEnumerable <IdentityRole> roles = roleAppService.GetALL();

            newUser.AllRoles = roles;
            if (ModelState.IsValid == false)
            {
                return(View(newUser));
            }
            string         roleName = Request["Role"];
            IdentityResult result   = userAppService.AddUser(newUser);

            if (result.Succeeded)
            {
                ApplicationUserIdentity identityUser = userAppService.Find(newUser.UserName, newUser.PasswordHash);
                userAppService.AssignToRole(identityUser.Id, roleName);
                TempData["Msg"] = "New User Added Successfully";
                return(RedirectToAction("Index"));
            }
            else
            {
                ModelState.AddModelError("", result.Errors.FirstOrDefault());
                return(View(newUser));
            }
        }
Example #3
0
        public static void Add(AddUserVM model, int newRole, List <int> newCompanys)
        {
            using (SqlConnection connection = new SqlConnection(Helpers.Helpers.GetAppConnectionString()))
            {
                try
                {
                    // Create the user record.
                    SqlCommand cmd = new SqlCommand("", connection);
                    connection.Open();

                    SqlParameter IDParameter = new SqlParameter("@UserID", SqlDbType.SmallInt);
                    IDParameter.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(IDParameter);

                    cmd.CommandText  = "insert into cUser(UserName, FirstName, LastName, Password, CellPhone, HomePhone, EmailAddress, Address, City, State, Zip, WebUrl, SSN, StatusID) ";
                    cmd.CommandText += " values ('" + model.UserName + "', '" + model.FirstName + "', '" + model.LastName + "', '" + model.Password + "','" + model.CellPhone + "', '" + model.HomePhone + "', '";
                    cmd.CommandText += model.EmailAddress + "', '" + model.Address + "', '" + model.City + "', '" + model.State + "', '" + model.Zip + "', '" + model.WebUrl + "', '" + model.SSN + "', 1) SET @UserID=SCOPE_IDENTITY();";
                    cmd.ExecuteNonQuery();
                    model.UserID = (short)IDParameter.Value;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }

            //add in all roles and reports
            InsertUserCompany(model.UserID, newCompanys, newRole);
        }
        public ActionResult AddUser()
        {
            AddUserVM data = new AddUserVM();

            data.Roles = _repo.AdminGetRoles();
            data.User  = new AppUser();
            return(View(data));
        }
Example #5
0
 public ActionResult Strict(AddUserVM model)
 {
     if (!ModelState.IsValid)
     {
         return(RedirectToAction("Strict"));
     }
     return(RedirectToAction("Index"));
 }
Example #6
0
        public ActionResult Add()
        {
            IEnumerable <IdentityRole> roles = roleAppService.GetALL();
            AddUserVM addUserVM = new AddUserVM();

            addUserVM.AllRoles = roles;
            return(View(addUserVM));
        }
        public IdentityResult AddUser(AddUserVM newUser)
        {
            ApplicationUserIdentity identityUser = Mapper.Map <ApplicationUserIdentity>(newUser);

            identityUser.Cart     = new Cart();
            identityUser.WishList = new Wishlist();
            return(TheUnitOfWork.User.Register(identityUser));
        }
 public ActionResult Add(AddUserVM vm)
 {
     if (!ModelState.IsValid)
     {
         return(View(vm));
     }
     return(RedirectToAction("Index"));
 }
Example #9
0
        public async Task <IActionResult> Add(AddUserDto model)
        {
            var vm = new AddUserVM {
                Cities = await _unitOfWork.UserRepo.GetCities(), User = model
            };

            return(View(vm));
        }
        public ActionResult AddUser()
        {
            var vm          = new AddUserVM();
            var roleManager = new RoleManager <AppRole>(new RoleStore <AppRole>(new EntityRepo()));

            vm.SetRoles(roleManager);
            return(View(vm));
        }
Example #11
0
        public ActionResult AddUser(AddUserVM data)
        {
            data.User.Profile.UserName = data.User.UserName;
            var roleName = _repo.AdminFindRoleById(data.RoleId).Name;

            _repo.AdminAddUser(data.User, data.Password, roleName);
            return(RedirectToAction("Users"));
        }
Example #12
0
        public ActionResult Normal(AddUserVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            return(RedirectToAction("Index"));
        }
Example #13
0
 public ActionResult Add(AddUserVM model)
 {
     if (model.FirstName == model.LastName)
     {
         ModelState.AddModelError("LastName", "The last name cannot be the same as the first name.");
     }
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     return(RedirectToAction("Index"));
 }
        public async Task <IActionResult> AddUser(AddUserVM vm)
        {
            if (!ModelState.IsValid)
            {
                return(View(vm));
            }

            string password = await lists.AddUser(vm.Name);

            Message("New user {0} created with password {1}", vm.Name, password);
            return(RedirectToRoute(Names.AdminIndex));
        }
Example #15
0
        public ActionResult Add(AddUserVM model)
        {
            if (Session["UserName"] == null)
            {
                return(RedirectToAction("Index", "Account"));
            }
            ViewBag.ReportTitle = "Add User";

            var selectedRoles     = model.Roles.Where(x => x.IsChecked).Select(x => x.ID).ToList();
            var selectedCompanies = model.Companies.Where(x => x.IsChecked).Select(x => x.ID).ToList();

            UserManager.Add(model, selectedRoles[0], selectedCompanies);
            return(RedirectToAction("Index"));
        }
Example #16
0
 public void CreateUser(AddUserVM addUserVM)
 {
     using (var db = new TagsDataModel())
     {
         TAGS_LOGIN newUser = new TAGS_LOGIN();
         newUser.FIRST_NAME = addUserVM.FIRST_NAME;
         newUser.LAST_NAME  = addUserVM.LAST_NAME;
         newUser.PASSWORD   = addUserVM.PASSWORD;
         newUser.USER_ROLE  = addUserVM.USER_ROLE;
         //don't know what this is for. Is it is logged in?
         newUser.IS_LOGGED_ID = 0;
         db.TAGS_LOGIN.Add(newUser);
         db.SaveChanges();
     }
 }
        public async Task <IActionResult> AddUser(AddUserVM model)
        {
            var user   = _imapper.Map <AddUserVM, User>(model);
            var result = await _userManager.CreateAsync(user, model.UserPass);

            if (result.Succeeded)
            {
                return(RedirectToAction("UserList"));
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(model));
        }
Example #18
0
        public ActionResult Add()
        {
            // add new user
            if (Session["UserName"] == null)
            {
                return(RedirectToAction("Index", "Account"));
            }
            ViewBag.ReportTitle = "Create new user";

            AddUserVM model = new AddUserVM();

            model.AllStatus = GetSelectListItems((short)Helpers.Helpers.ListType.allStatus);

            var allRoles = UserManager.GetAllRoles(UserManager.GetUserMostRightRole((int)Session["UserID"]));

            model.AllStatus = GetSelectListItems((short)Helpers.Helpers.ListType.allStatus);
            var checkBoxListItems = new List <CheckBoxListItem>();

            foreach (var genre in allRoles)
            {
                checkBoxListItems.Add(new CheckBoxListItem()
                {
                    ID      = genre.ID,
                    Display = genre.Display
                });
            }
            model.Roles = checkBoxListItems;

            var allReports = GetCheckBoxList((short)Helpers.Helpers.ListType.company);
            var reportcheckBoxListItems = new List <CheckBoxListItem>();

            foreach (var genre in allReports)
            {
                reportcheckBoxListItems.Add(new CheckBoxListItem()
                {
                    ID      = genre.ID,
                    Display = genre.Display
                });
            }
            model.Companies = reportcheckBoxListItems;
            return(View(model));
        }
Example #19
0
        public async Task <IActionResult> DoAdd(AddUserVM addUser)
        {
            if (ModelState.IsValid)
            {
                var user = Mapper.Map <UserSM>(addUser);
                await _authService.AddUser(user, addUser.Password);

                await _authService.UpdateRole(user.Email, addUser.Role);

                if (_authService.BusinessErrors.Any())
                {
                    MergeBusinessErrors(_authService.BusinessErrors);
                    return(GetAddView(addUser));
                }
                SetControllerMessage(ControllerMessageType.Success, "Added");
                return(RedirectToAction("Index"));
            }

            return(GetAddView(addUser));
        }
Example #20
0
 //Create add user view model
 public AddUserVM CreateAddUserVM(AddUserVM model = null)
 {
     if (model == null)
     {
         model = new AddUserVM();
     }
     if (HttpContext.Current.User.IsInRole(Key.ROLE_ADMIN) ||
         HttpContext.Current.User.IsInRole(Key.ROLE_STAFF))
     {
         model.ApplicationList = _selectRepo.GetApplicationListByClient(null);
     }
     else
     {
         string userID            = HttpContext.Current.User.Identity.GetUserId();
         string clientReferenceID = _context.UserDetail.Where(u => u.UserID == userID).SingleOrDefault().Client.ReferenceID;
         model.ClientReferenceID = clientReferenceID;
         model.ApplicationList   = _selectRepo.GetApplicationListByClient(clientReferenceID);
     }
     model.StatusList = _selectRepo.GetStatusList(Key.STATUS_TYPE_USER);
     model.ClientList = _selectRepo.GetUserClientList();
     model.RolesList  = _selectRepo.GetRolesList();
     return(model);
 }
Example #21
0
        public async Task <ActionResult> Create(AddUserVM model)
        {
            // If success then proceed
            if (ModelState.IsValid)
            {
                // If the method returns true from user repo, do this
                if (_userRepo.AddUser(model, out string msg, out string userId))
                {
                    // Generate the email confirmation code for the user being generated
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(userId);

                    // Generating the call back url which will be sent to the user for confirmation
                    var callbackUrl = Url.Action("ConfirmEmail", "User", new { userId = userId, code = code }, protocol: Request.Url.Scheme);

                    // This is the content for the body of confirmation email message
                    string body = "Welcome to Notification Portal. In order to get started, you need to confirm your email address.";

                    // Send the confirmation email with TemplateService -> AccountEmail method
                    await UserManager.SendEmailAsync(userId, "Confirm your account", TemplateService.AccountEmail(callbackUrl, body, "Confirm Email"));

                    TempData["SuccessMsg"] = msg;
                    return(RedirectToAction("Index"));
                }
                TempData["ErrorMsg"] = msg;
            }

            // Load the dropdown / selectlistrepo values if adding the user fails
            model = _userRepo.CreateAddUserVM(model);
            // if model returns null, redirect to index
            if (model == null)
            {
                TempData["ErrorMsg"] = "Cannot create new user at the moment";
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Example #22
0
 private IActionResult GetAddView(AddUserVM model)
 {
     model.Roles = CreateRolesList();
     return(View(model));
 }
Example #23
0
 public AddUserPopup()
 {
     InitializeComponent();
     BindingContext = new AddUserVM();
 }
Example #24
0
        // User Controller Add Page
        public bool AddUser(AddUserVM model, out string msg, out string userId)
        {
            // Get the user manager
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(_context));

            // Check if the user exists in the database
            ApplicationUser checkUser = userManager.Users.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());

            try
            {
                // if user does not exist then ONLY proceed
                if (checkUser == null)
                {
                    // create a new AspNetUser
                    var user = new ApplicationUser()
                    {
                        UserName = model.Email,
                        Email    = model.Email
                    };

                    // find the client id with the reference id passed with the viewmodel and add the new client to that
                    int?clientId = model.ClientReferenceID == null ? null : (int?)_context.Client.Where(c => c.ReferenceID == model.ClientReferenceID)
                                   .Select(client => client.ClientID).FirstOrDefault();

                    // get default send method (Email)
                    int defaultSendMethodID = _context.SendMethod.Where(s => s.SendMethodName == Key.SEND_METHOD_EMAIL)
                                              .Select(s => s.SendMethodID).FirstOrDefault();

                    // duplicate the user from aspnetuser to userdetail
                    UserDetail details = new UserDetail()
                    {
                        UserID        = user.Id,
                        ReferenceID   = Guid.NewGuid().ToString(),
                        BusinessTitle = model.BusinessTitle,
                        FirstName     = model.FirstName,
                        LastName      = model.LastName,
                        StatusID      = model.StatusID,
                        SendMethodID  = defaultSendMethodID
                    };

                    // check what role the user is adding otherwise throw error
                    // staff can only add client and user roles not admin and other staff
                    if (HttpContext.Current.User.IsInRole(Key.ROLE_STAFF))
                    {
                        if (model.RoleName == Key.ROLE_ADMIN || model.RoleName == Key.ROLE_STAFF)
                        {
                            msg    = "Something went wrong, try again";
                            userId = "";

                            return(false);
                        }
                    }

                    // clients can only add other users, if false throw error
                    if (HttpContext.Current.User.IsInRole(Key.ROLE_CLIENT))
                    {
                        if (model.RoleName == Key.ROLE_ADMIN || model.RoleName == Key.ROLE_STAFF || model.RoleName == Key.ROLE_CLIENT)
                        {
                            msg    = "Something went wrong, try again";
                            userId = "";

                            return(false);
                        }
                    }

                    // get the application reference ids from the multiselect
                    if (model.ApplicationReferenceIDs == null)
                    {
                        model.ApplicationReferenceIDs = new string[0];
                    }

                    // add the applications selected to user details application table
                    var apps = _context.Application.Where(a => model.ApplicationReferenceIDs.Contains(a.ReferenceID));

                    if (model.RoleName == Key.ROLE_CLIENT || model.RoleName == Key.ROLE_USER)
                    {
                        details.ClientID     = clientId;
                        details.Applications = apps.ToList();
                    }

                    // make the user at this point
                    userManager.Create(user);

                    // pass the userId to controller to send the email
                    userId = user.Id;
                    // add the user details to the database
                    _context.UserDetail.Add(details);
                    _context.SaveChanges();

                    // verify which role the user needs to be added
                    userManager.AddToRole(user.Id, model.RoleName);

                    // if the client was added successfully pass this msg out
                    msg = "User added successfully";
                    return(true);
                }
                else
                {
                    // if error show this msg
                    msg    = "The email address is already in use";
                    userId = "";
                    return(false);
                }
            }
            catch (Exception e)
            {
                if (e is SqlException)
                {
                }

                // if something breaks show this message or exception is caught
                msg    = "Failed to add the user";
                userId = "";
                return(false);
            }
        }
        public ActionResult Add()
        {
            AddUserVM ad = new AddUserVM();

            return(View(ad));
        }
Example #26
0
        public ActionResult AddUser(AddUserVM vm)
        {
            string input = vm.UserName;

            var user = Context.Users.FirstOrDefault(g => g.UserName == vm.UserName || g.Mail == vm.UserName);

            //Return a list with possible users if the username is not found.
            if (user == null)
            {
                if (MailHelpers.CheckIfValidEmail(vm.UserName))
                {
                    string key     = Guid.NewGuid().ToString();
                    string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                    string link    = baseUrl + "Account/Register?key=" + key;
                    Context.NewRegisters.Add(new NewRegister
                    {
                        Key     = key,
                        Email   = vm.UserName,
                        GroupId = vm.GroupId
                    });
                    Context.SaveChanges();
                    MailService ms = new MailService();
                    ms.SendRegisterMail(vm.UserName, link);

                    return(View(new AddUserVM {
                        GroupId = vm.GroupId, Message = "An email has been sent to the given email."
                    }));
                }

                var possibleUsers = Context.Users.Select(g => new Web.Models.Group.UserVM
                {
                    Id        = g.Id,
                    UserName  = g.UserName,
                    FirstName = g.FirstName,
                    LastName  = g.LastName
                }).Where(g => g.UserName.Contains(vm.UserName)).ToList();

                if (possibleUsers != null && possibleUsers.Count > 0)
                {
                    return(View(new AddUserVM {
                        GroupId = vm.GroupId, PossibleUsers = possibleUsers
                    }));
                }
                else
                {
                    return(RedirectToAction("Details", new { id = vm.Id, state = "No user" }));
                }
            }
            else
            {
                var group = Context.Groups.GetById(vm.Id);
                if (!group.Archived)
                {
                    if (group.Users == null)
                    {
                        group.Users = new List <User>();
                    }
                    group.Users.Add(user);

                    user.Notifications.Add(new Notification
                    {
                        Title   = "Added to group: " + group.GroupName,
                        Content = $"You've been added to the group '{group.GroupName}' " +
                                  $"and can now rate yourself for the associated skills through the following link: " +
                                  Url.Action("RateUser", "Group", new { userId = user.Id }, this.Request.Url.Scheme),
                        Date   = DateTime.Now,
                        IsRead = false
                    });

                    Context.SaveChanges();

                    return(RedirectToAction("Details", new { id = vm.Id, state = "success" }));
                }
                else
                {
                    var message = "Target group is archived";
                    return(RedirectToAction("Index", message));
                }
            }
        }
Example #27
0
        public ActionResult Normal()
        {
            AddUserVM model = new AddUserVM();

            return(View(model));
        }
Example #28
0
        public ActionResult Strict()
        {
            AddUserVM model = new AddUserVM();

            return(View(model));
        }
Example #29
0
 public AddUser(HomeVM home)
 {
     InitializeComponent();
     DataContext = new AddUserVM(this, home);
 }
Example #30
0
 public AddUserCmd(AddUserVM vm)
 {
     addUserVM = vm;
 }