Ejemplo n.º 1
0
        public ActionResult New(UsersCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var Context = new ProjectDBEntities())
                {
                    var UserStatus = Context.UserStatus.Where(usx => usx.UserStatusDetail == "Pending").FirstOrDefault <UserStatu>();

                    model.DateCreated   = DateTime.Now;
                    model.DateActivated = DateTime.Now;

                    Mapper.CreateMap <UsersCreateViewModel, SiteUser>();
                    SiteUser User = Mapper.Map <SiteUser>(model);


                    User.UserStatusID = UserStatus.UserStatusID;
                    User.UserPass     = Hashing.CreateHash(model.UserPass);

                    Context.SiteUsers.Add(User);

                    if (Context.SaveChanges() == 1)
                    {
                        ViewBag.Message = "User added successfully..";
                    }
                    else
                    {
                        ViewBag.Message = "User cannot be added at the moment..";
                    }
                }
            }
            return(View(new UsersCreateViewModel()));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Create(UsersCreateViewModel model)
        {
            if (GetCookie("LoggedIn") != "true")
            {
                return(Redirect("/"));
            }
            else
            {
                if (ModelState.IsValid)
                {
                    User user = new User
                    {
                        Username        = model.Username,
                        PasswordHash    = GetPasswordHash(model.Password),
                        FirstName       = model.FirstName,
                        MiddleName      = model.MiddleName,
                        LastName        = model.LastName,
                        PersonalID      = model.PersonalID,
                        PhoneNumber     = model.PhoneNumber,
                        Email           = model.Email,
                        DateAppointment = model.DateAppointment,
                        Active          = model.Active,
                        DateDismissal   = model.DateDismissal
                    };

                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }

                return(View(model));
            }
        }
Ejemplo n.º 3
0
        public ActionResult Create(UsersCreateViewModel model)
        {
            string           validationCode = HashUtils.CreateReferralCode();
            var              repository     = new UserRepository();
            SendConfirmEmail emailSender    = new SendConfirmEmail();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            User user = new User();

            user.ImgURL           = model.ImgURL;
            user.Email            = model.Email;
            user.Username         = model.Username;
            user.Password         = model.Password;
            user.FirstName        = model.FirstName;
            user.LastName         = model.LastName;
            user.IsAdmin          = model.IsAdmin;
            user.IsEmailConfirmed = false;
            user.ValidationCode   = validationCode;

            repository.Insert(user);

            sendConfirmEmail.SendConfirmationEmailAsync(user);

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 4
0
        public ActionResult Create(UsersCreateViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                var request = new CreateUserRequest
                {
                    User = new UserDto
                    {
                        UserName = model.Email,
                        FirstName = model.FirstName.Trim(),
                        LastName = model.LastName.Trim(),
                        Email = model.Email
                    }
                };

                var response = this.userService.CreateUser(request);

                if (response.Status == StatusCode.OK)
                {
                    this.TempData["SuccessMessage"] = string.Format("You have successfully added '{0} {1}'.", request.User.FirstName, request.User.LastName);
                    return this.RedirectToAction("Index");
                }
                else if (response.Status == StatusCode.BadRequest)
                {
                    this.ModelState.AddModelError(string.Empty, $"Your account was not created for the following reason: {this.GetErrorMessage(response.CreateAccountStatus)}");
                }
                else
                {
                    this.ModelState.AddModelError(string.Empty, Resources.ErrorMessages.InternalServerError);
                }
            }

            return View(model);
        }
Ejemplo n.º 5
0
 public ActionResult Create(UsersCreateViewModel createModel)
 {
     if (ModelState.IsValid)
     {
         ApplicationUser user = new ApplicationUser
         {
             UserName    = createModel.Username,
             Email       = createModel.Email,
             FirstName   = createModel.FirstName,
             LastName    = createModel.LastName,
             UCN         = createModel.UCN,
             Address     = createModel.Address,
             PhoneNumber = createModel.PhoneNumber
         };
         if (_userManager.FindByNameAsync(createModel.Username).Result != null)
         {
             return(RedirectToAction("Error", "Home", new { errorMessage = "Username already exists" }));
         }
         var createUser = _userManager.CreateAsync(user, createModel.Password).Result;
         if (createUser.Succeeded)
         {
             _userManager.AddToRoleAsync(user, "Employee").Wait();
         }
         _context.SaveChanges();
         return(RedirectToAction(nameof(List)));
     }
     return(View(createModel));
 }
Ejemplo n.º 6
0
        public IActionResult Create(UsersCreateViewModel vm)
        {
            var result = _usersRepository.Create(vm);

            TempData.AddResult(result);
            return(RedirectToAction("GetAll"));
        }
Ejemplo n.º 7
0
        public ActionResult Create(UsersCreateViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                var request = new CreateUserRequest
                {
                    User = new UserDto
                    {
                        UserName  = model.Email,
                        FirstName = model.FirstName.Trim(),
                        LastName  = model.LastName.Trim(),
                        Email     = model.Email
                    }
                };

                var response = this.userService.CreateUser(request);

                if (response.Status == StatusCode.OK)
                {
                    this.TempData["SuccessMessage"] = string.Format("You have successfully added '{0} {1}'.", request.User.FirstName, request.User.LastName);
                    return(this.RedirectToAction("Index"));
                }
                //else if (response.Status == StatusCode.BadRequest)
                //{
                //    this.ModelState.AddModelError(string.Empty, $"Your account was not created for the following reason: {this.GetErrorMessage(response.CreateAccountStatus)}");
                //}
                else
                {
                    this.ModelState.AddModelError(string.Empty, response.Message);
                }
            }

            return(View(model));
        }
Ejemplo n.º 8
0
        public ServiceResult <int> Create(UsersCreateViewModel vm)
        {
            var entity = Mapper.Map <Users>(vm);

            _context.Users.Add(entity);
            _context.SaveChanges();
            return(ServiceResult <int> .Okay(data : entity.Id, message : "عملیات با موفقیت انجام شد."));
        }
Ejemplo n.º 9
0
        public IActionResult Create(UsersCreateViewModel createModel)
        {
            if (GlobalVar.LoggedOnUserRights != GlobalVar.UserRights.Admininstrator && context.Users.Where(x => x.IsActive).Count() != 0)
            {
                UsersLogInViewModel model1 = new UsersLogInViewModel();
                model1.Message = "Нямате право на това действие. Моля, влезте в акаунта си.";
                return(View("LogIn", model1));
            }

            createModel.Message = null;
            if (ModelState.IsValid)
            {
                if (!DoesPasswordsMatch(createModel.Password, createModel.ConfirmPassword))
                {
                    createModel.Message = "Двете пароли не съвпадат";
                    return(View(createModel));
                }

                try
                {
                    Validate(new Validation_User()
                    {
                        Username = createModel.Username,
                        UserId   = -1
                    });
                }
                catch (InvalidOperationException e)
                {
                    createModel.Message = e.Message;
                    return(View(createModel));
                }

                User user = new User
                {
                    Username        = createModel.Username,
                    Password        = createModel.Password,
                    FirstName       = createModel.FirstName,
                    MiddleName      = createModel.MiddleName,
                    LastName        = createModel.LastName,
                    EGN             = createModel.EGN,
                    Email           = createModel.Email,
                    TelephoneNumber = createModel.TelephoneNumber
                };

                context.Users.Add(user);
                context.SaveChanges();

                if (context.Users.Where(x => x.IsActive).Count() == 1)
                {
                    GlobalVar.LoggedOnUserId     = context.Users.Where(x => x.IsActive).First().Id;
                    GlobalVar.LoggedOnUserRights = GlobalVar.UserRights.Admininstrator;
                }

                return(RedirectToAction(nameof(Index)));
            }

            return(View(createModel));
        }
        public IActionResult Create(UsersCreateViewModel createModel)
        {
            if (GlobalVar.LoggedOnUserRights != GlobalVar.UserRights.Admininstrator && _context.Users.Where(x => x.IsActive).Count() != 0)
            {
                UsersLogInViewModel model1 = new UsersLogInViewModel();
                model1.Message = "You dont meet the required permission to do this. Please, log in into account with admin permissions";
                return(View("LogIn", model1));
            }

            createModel.Message = null;
            if (ModelState.IsValid)
            {
                if (!DoesPasswordsMatch(createModel.Password, createModel.ConfirmPassword))
                {
                    createModel.Message = "Password and confirm password should match";
                    return(View(createModel));
                }

                try
                {
                    Validate(new Validation_User()
                    {
                        Username = createModel.Username,
                        UserId   = -1
                    });
                }
                catch (InvalidOperationException e)
                {
                    createModel.Message = e.Message;
                    return(View(createModel));
                }

                User user = new User
                {
                    Username        = createModel.Username,
                    Password        = createModel.Password,
                    FirstName       = createModel.FirstName,
                    MiddleName      = createModel.MiddleName,
                    LastName        = createModel.LastName,
                    EGN             = createModel.EGN,
                    Email           = createModel.Email,
                    TelephoneNumber = createModel.TelephoneNumber
                };

                _context.Users.Add(user);
                _context.SaveChanges();

                if (_context.Users.Where(x => x.IsActive).Count() == 1)
                {
                    GlobalVar.LoggedOnUserId     = _context.Users.Where(x => x.IsActive).First().Id;
                    GlobalVar.LoggedOnUserRights = GlobalVar.UserRights.Admininstrator;
                }

                return(RedirectToAction(nameof(Index)));
            }

            return(View(createModel));
        }
Ejemplo n.º 11
0
        public ViewResult Create()
        {
            var model = new UsersCreateViewModel
            {
                SaveUrl      = Url.RouteUrl("adminUsersCreate"),
                UsersListUrl = Url.RouteUrl("adminUsers")
            };

            return(View(model));
        }
Ejemplo n.º 12
0
        // GET: Users/Create
        public IActionResult Create()
        {
            if (GetCookie("LoggedIn") != "true")
            {
                return(Redirect("/"));
            }
            else
            {
                UsersCreateViewModel model = new UsersCreateViewModel();

                return(View(model));
            }
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Create(UsersCreateViewModel model)
        {
            if (GetCookie("LoggedIn") != "true")
            {
                return(Redirect("/"));
            }
            else
            {
                if (ModelState.IsValid)
                {
                    User user = new User
                    {
                        Username        = model.Username,
                        PasswordHash    = GetPasswordHash(model.Password),
                        FirstName       = model.FirstName,
                        MiddleName      = model.MiddleName,
                        LastName        = model.LastName,
                        PersonalID      = model.PersonalID,
                        PhoneNumber     = model.PhoneNumber,
                        Email           = model.Email,
                        DateAppointment = model.DateAppointment,
                        Active          = model.Active,
                        DateDismissal   = model.DateDismissal
                    };

                    if (user.DateDismissal != null && user.DateAppointment.CompareTo(user.DateDismissal) >= 0)
                    {
                        ModelState.AddModelError("DateDismissal", "The dismissal date cannot be before the date of appointment");
                        return(View(model));
                    }

                    if (_context.Users.ToArray().Select(u => u.Username).ToArray().Contains(user.Username))
                    {
                        ModelState.AddModelError("Username", "User with that username already exists");
                        return(View(model));
                    }


                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }

                return(View(model));
            }
        }
Ejemplo n.º 14
0
        public IActionResult Create()
        {
            var roles = _context.Roles.Select(r => new SelectListItem
            {
                Text     = r.Name,
                Value    = r.Name,
                Selected = false
            }).ToList();

            var response = new UsersCreateViewModel
            {
                Roles   = roles,
                IsAdmin = User.IsInRole("Admin")
            };

            return(View(response));
        }
        public ActionResult Create(UsersCreateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            User user = new User();

            user.Name     = model.Name;
            user.Email    = model.Email;
            user.Phone    = model.Phone;
            user.Password = model.Password;
            UsersRepository repository = new UsersRepository();

            repository.Insert(user);
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 16
0
        // GET: Users/Create
        public IActionResult Create()
        {
            if (GetCookie("LoggedIn") != "true")
            {
                return(Redirect("/"));
            }
            else
            {
                if (GetCookie("Username") != "HotelSysAdmin")
                {
                    return(Redirect("/Menu/User_Menu"));
                }

                UsersCreateViewModel model = new UsersCreateViewModel();

                return(View(model));
            }
        }
Ejemplo n.º 17
0
        public async Task <ActionResult> Register(UsersCreateViewModel model)
        {
            string      validationCode = HashUtils.CreateReferralCode();
            var         repository     = new UserRepository();
            List <User> users          = repository.GetAll();

            SendConfirmEmail emailSender = new SendConfirmEmail();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (users.Where(u => u.Email == model.Email).Any())
            {
                ModelState.AddModelError("error_email", "This email is already taken!");
                return(View());
                //return View("Error");
            }
            else if (users.Where(u => u.Username == model.Username).Any())
            {
                ModelState.AddModelError("error_msg", "This username is already taken!");
                return(View());
                // return View("Error");
            }
            else
            {
                User user = new User();
                user.ImgURL           = model.ImgURL;
                user.Email            = model.Email;
                user.Username         = model.Username;
                user.Password         = model.Password;
                user.FirstName        = model.FirstName;
                user.LastName         = model.LastName;
                user.IsAdmin          = model.IsAdmin;
                user.IsEmailConfirmed = false;
                user.ValidationCode   = validationCode;

                repository.Insert(user);

                sendConfirmEmail.SendConfirmationEmailAsync(user);
            }
            return(RedirectToAction("IndexPage", "Home"));
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> Create(UsersCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                User newUser = new User
                {
                    UserName       = model.UserName,
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    Email          = model.Email,
                    EmailConfirmed = true,
                    Password       = model.Password,
                    Role           = _roleManager.Roles.First(x => x.Name == model.Role),
                    Team           = _context.Teams.FirstOrDefault(x => x.TeamName == model.Team),
                    SecurityStamp  = Guid.NewGuid().ToString()
                };

                if (_context.Users.Any(x => x.Email == model.Email))
                {
                    ModelState.AddModelError("Email", "User with this email already exists.");
                    return(View(model));
                }

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

                if (result.Succeeded)
                {
                    var res2 = await _userManager.AddToRoleAsync(newUser, model.Role);

                    //newUser.Role.UsersInRole.Add(newUser);
                    //await _signInManager.SignInAsync(newUser, false);
                    return(RedirectToAction(nameof(Index)));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View(model));
        }
Ejemplo n.º 19
0
        public ActionResult Register(UsersCreateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            User user = new User();

            user.Name     = model.Name;
            user.Email    = model.Email;
            user.Password = model.Password;
            user.Phone    = model.Phone;
            user.IsAdmin  = model.IsAdmin;

            var repository = new UserRepository();

            repository.Insert(user);

            return(RedirectToAction("HomePage", "Home"));
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> Create(UsersCreateViewModel createModel)
        {
            if (ModelState.IsValid)
            {
                User user = new User
                {
                    UserName    = createModel.UserName,
                    Password    = createModel.Password,
                    Email       = createModel.Email,
                    FirstName   = createModel.FirstName,
                    LastName    = createModel.LastName,
                    EGN         = createModel.EGN,
                    Address     = createModel.Address,
                    PhoneNumber = createModel.PhoneNumber,
                    Role        = createModel.Role
                };
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(createModel));
        }
Ejemplo n.º 21
0
        public IActionResult Create(UserCreateSubmitModel submitModel)
        {
            var userId = _userService.Add(submitModel);

            if (_userService.IsError)
            {
                var model = new UsersCreateViewModel
                {
                    UserName  = submitModel.UserName,
                    Email     = submitModel.Email,
                    Firstname = submitModel.Firstname,
                    Lastname  = submitModel.Lastname,
                    IsActive  = submitModel.IsActive,

                    SaveUrl      = Url.RouteUrl("adminUsersCreate"),
                    UsersListUrl = Url.RouteUrl("adminUsers")
                };
                return(View(model));
            }
            else
            {
                return(RedirectToRoute("adminUsersEdit", new { id = userId }));
            }
        }
Ejemplo n.º 22
0
        public ActionResult Create()
        {
            UsersCreateViewModel model = new UsersCreateViewModel();

            return(View(model));
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> Create([Bind("Email,Password,ConfirmPassword,Role")] UserCreateViewModel user)
        {
            string role = "Lab";

            // Caso quem crie a conta seja administrador e o campo do Role tenha sido preenchido, deixa este escolher o role do novo user
            if (User.IsInRole("Admin") && !String.IsNullOrEmpty(user.Role))
            {
                role = user.Role;
            }

            if (ModelState.IsValid)
            {
                var newUser = new IdentityUser {
                    UserName = user.Email, Email = user.Email
                };
                var result = await _userManager.CreateAsync(newUser, user.Password);

                if (result.Succeeded)
                {
                    try
                    {
                        await _userManager.AddToRoleAsync(newUser, role);
                    }
                    catch (Exception)
                    {
                        // Ao chegar aqui é porque alguem alterou o html do select. Adiciona o utilizador como user normal
                        await _userManager.AddToRoleAsync(newUser, "Lab");
                    }

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

                    var callbackUrl = Url.Action("ConfirmEmail", "Users",
                                                 values: new { userId = newUser.Id, code = code },
                                                 protocol: Request.Scheme);

                    _email.Send(user.Email, "Confirme o seu e-mail",
                                $"Por favor confirme o seu e-mail: <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clique aqui</a>.");

                    // Feeback ao utilizador - Vai ser redirecionado para o Index
                    TempData["Feedback"] = "Utilizador criado com sucesso.";
                    TempData["Type"]     = "success";
                    return(RedirectToAction("Index"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            var roles = _context.Roles.Select(r => new SelectListItem
            {
                Text     = r.Name,
                Value    = r.Name,
                Selected = false
            }).ToList();

            var response = new UsersCreateViewModel
            {
                User    = user,
                Roles   = roles,
                IsAdmin = User.IsInRole("Admin")
            };

            // If we got this far, something failed, redisplay form
            return(View(response));
        }