public IHttpActionResult Post([FromBody] UserRole entity)
        {
            logger.Trace("Call UserRolesController Post");

            var record = UserRoleRepository.Create(entity);

            return(Created(record));
        }
        private void addManagerRole(User user)
        {
            Role     role     = _roleRepository.GetById(2);
            UserRole userRole = new UserRole();

            userRole.Role = role;
            userRole.User = user;
            _userRoleRepository.Create(userRole);
        }
Esempio n. 3
0
        public UserRole AddRole(int userId, int roleId)
        {
            var createdEnt = _userRoleRepository.Create(new UserRole
            {
                UserId = userId,
                RoleId = roleId
            });

            return(createdEnt);
        }
        public async Task <ActionResult> Create(CreateEmployeeVM model)
        {
            try
            {
                model = await AddSomePropertiesToEmployeeVM(model);

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

                var user = _mapper.Map <Employee>(model);
                user.MaNhanVienThemVaoHeThong = _userManager.GetUserAsync(HttpContext.User).Result.Id;
                user.UserName       = model.Email;
                user.Id             = Guid.NewGuid().ToString();
                user.ProfilePicture = UploadedProfilePicture(model);



                if (user.ProfilePicture == null)
                {
                    user.ProfilePicture = "ProfilePicture.webp";
                }



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

                if (result.Succeeded)
                {
                    var userRole = new IdentityUserRole <string>
                    {
                        UserId = user.Id,
                        RoleId = model.MaVaiTroTrenHeThong
                    };
                    var isSuccess = await userRoleRepository.Create(userRole);

                    //var roleName = userRoleRepository.findbyroleid
                    //_userManager.AddToRoleAsync(user, model.MaVaiTroTrenHeThong).Wait();
                }
                else
                {
                    ModelState.AddModelError("", "Something Went Wrong...");
                    return(View(model));
                }


                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "Something Went Wrong...");
                return(View());
            }
        }
Esempio n. 5
0
        public async Task <IActionResult> CreateUserRole(string projectId, [FromBody, BindRequired] UserRole userRole)
        {
            if (!await _permissionService.HasProjectPermission(HttpContext, Permission.DeleteEditSettingsAndUsers))
            {
                return(Forbid());
            }

            userRole.ProjectId = projectId;

            // Ensure project exists
            var proj = await _projRepo.GetProject(projectId);

            if (proj is null)
            {
                return(NotFound(projectId));
            }

            await _userRoleRepo.Create(userRole);

            return(Ok(userRole.Id));
        }
Esempio n. 6
0
 public StatusEnum.Status SaveUser(UserModel model)
 {
     StatusEnum.Status status = StatusEnum.Status.Success;
     try
     {
         _user                   = new PASCore_Users();
         _user.Id                = Guid.NewGuid();
         _user.UserName          = model.UserName;
         _user.TelMobile         = model.TelMobile;
         _user.TelMainTwo        = model.TelMainTwo;
         _user.TelMainOne        = model.TelMainOne;
         _user.Telex             = model.Telex;
         _user.Prefix            = model.Prefix;
         _user.Password          = model.Password;
         _user.OfficeId          = Guid.NewGuid();
         _user.ModifiedDateTime  = null;
         _user.MiddleName        = model.MiddleName;
         _user.LastName          = model.LastName;
         _user.LastLoginDateTime = null;
         _user.IsDeleted         = false;
         _user.IsActive          = true;
         _user.FirstName         = model.FirstName;
         _user.EntityId          = model.EntityId;
         _user.EmailAddress      = model.emailAddress;
         _user.DeletedDateTime   = null;
         _user.CreatedDateTime   = DateTime.UtcNow;
         _userRepository.Create(_user);
         _userRepository.SaveChanges();
         if (_user.Id != null)
         {
             if (model.UserRole.Length > 0)
             {
                 foreach (var roles in model.UserRole)
                 {
                     Guid roleId = new Guid(roles);
                     _userRoles = new PASCore_UserRoles()
                     {
                         RoleId = roleId,
                         UserId = _user.Id
                     };
                     _userRoleRepository.Create(_userRoles);
                 }
                 _userRoleRepository.SaveChanges();
             }
         }
     }
     catch (Exception)
     {
         status = StatusEnum.Status.Fail;
     }
     return(status);
 }
Esempio n. 7
0
        private void AddRole(Guid id, Guid roleId)
        {
            if (null == _userRepository.Get(id))
            {
                throw new EntityValidationException("User does not exist.");
            }

            if (null == _roleRepository.Get(roleId))
            {
                throw new EntityValidationException("Role does not exist.");
            }

            _userRoleRepository.Create(id, roleId);
        }
Esempio n. 8
0
        private async Task AsociateExistingParentWithNewStudent(User parentUser, User studentUser)
        {
            var roles = parentUser.UserRoles.Select(ur => ur.RoleId);

            if (roles.All(r => r != (int)RoleTypes.Parent))
            {
                var userRole = new UserRole
                {
                    RoleId = (int)RoleTypes.Parent,
                    UserId = parentUser.Id
                };
                _userRoleRepository.Create(userRole);
            }

            var parentStudentsResult = await _parentStudentRepository.FindAll(ps => ps.ParentId == parentUser.Id);

            var students = parentStudentsResult.Select(ps => ps.StudentId);

            if (students.Any(s => s == studentUser.Id))
            {
                return;
            }

            var parentStudent = new ParentStudent
            {
                ParentId     = parentUser.Id,
                StudentId    = studentUser.Id,
                Relationship = ParentRelationship.Father
            };

            _parentStudentRepository.Create(parentStudent);

            await _parentStudentRepository.Save();

            await _mailService.SendEmailToExistingParentToValidateStudent(studentUser, parentUser);
        }
Esempio n. 9
0
        public async Task <IActionResult> CreateProject([FromBody, BindRequired] Project project)
        {
            await _projRepo.Create(project);

            // Get user.
            var currentUserId = _permissionService.GetUserId(HttpContext);
            var currentUser   = await _userRepo.GetUser(currentUserId);

            if (currentUser is null)
            {
                return(NotFound(currentUserId));
            }

            // Give Project admin privileges to user who creates a Project.
            var userRole = new UserRole
            {
                Permissions = new List <Permission>
                {
                    Permission.DeleteEditSettingsAndUsers,
                    Permission.ImportExport,
                    Permission.MergeAndCharSet,
                    Permission.Unused,
                    Permission.WordEntry
                },
                ProjectId = project.Id
            };

            userRole = await _userRoleRepo.Create(userRole);

            // Update user with userRole.
            // Generate the userRoles and update the user.
            currentUser.ProjectRoles.Add(project.Id, userRole.Id);
            await _userRepo.Update(currentUserId, currentUser);

            // Generate the JWT based on those new userRoles.
            var currentUpdatedUser = await _permissionService.MakeJwt(currentUser);

            if (currentUpdatedUser is null)
            {
                return(BadRequest("Invalid JWT Token supplied."));
            }

            await _userRepo.Update(currentUserId, currentUpdatedUser);

            return(Ok(new UserCreatedProject {
                Project = project, User = currentUpdatedUser
            }));
        }
Esempio n. 10
0
        public async Task <bool> RemoveTokenAndCreateUserRole(Project project, User user, EmailInvite emailInvite)
        {
            try
            {
                var userRole = new UserRole
                {
                    Permissions = new List <Permission>
                    {
                        Permission.MergeAndCharSet,
                        Permission.Unused,
                        Permission.WordEntry
                    },
                    ProjectId = project.Id
                };
                userRole = await _userRoleRepo.Create(userRole);

                // Generate the userRoles and update the user
                user.ProjectRoles.Add(project.Id, userRole.Id);
                await _userRepo.Update(user.Id, user);

                // Generate the JWT based on those new userRoles
                var updatedUser = await _permissionService.MakeJwt(user);

                if (updatedUser is null)
                {
                    throw new PermissionService.InvalidJwtTokenError(
                              "Unable to generate JWT.");
                }

                await _userRepo.Update(updatedUser.Id, updatedUser);

                // Removes token and updates user

                project.InviteTokens.Remove(emailInvite);
                await _projRepo.Update(project.Id, project);

                return(true);
            }
            catch (PermissionService.InvalidJwtTokenError)
            {
                return(false);
            }
        }
Esempio n. 11
0
        public async Task <User> Create(User newUser, string password)
        {
            ValidateEmail(newUser.Email);
            ValidatePassword(password);

            newUser.Salt           = GenerateSalt();
            newUser.HashedPassword = HashPassword(password, newUser.Salt);

            var createdUser = await _userRepo.Create(newUser);

            var CreatedUserRole = await _userRoleRepo.Create(createdUser.Id, Role.User.ID);

            createdUser.Roles = new List <Role>()
            {
                Role.User
            };

            return(createdUser);
        }
Esempio n. 12
0
        public JsonModel AddUserRole(UserRoleDTO userRoleDTO, TokenModel token)
        {
            JsonModel Result = new JsonModel()
            {
                data       = false,
                Message    = StatusMessage.Success,
                StatusCode = (int)HttpStatusCodes.OK
            };
            UserRoles userRolesEntity = null;
            DateTime  CurrentDate     = DateTime.UtcNow;


            userRolesEntity = _mapper.Map <UserRoles>(userRoleDTO);
            userRolesEntity.OrganizationID = 2; // token.OrganizationID;
            userRolesEntity.IsActive       = true;
            _userRoleRepository.Create(userRolesEntity);
            _userRoleRepository.SaveChanges();

            return(Result);
        }
Esempio n. 13
0
        public Guid Post(PostUserViewModel postUserViewModel)
        {
            if (string.IsNullOrEmpty(postUserViewModel.Name))
            {
                throw new Exception("Name não pode ser em branco");
            }

            if (string.IsNullOrEmpty(postUserViewModel.Email))
            {
                throw new Exception("E-mail não pode ser em branco");
            }

            if (string.IsNullOrEmpty(postUserViewModel.Password))
            {
                throw new Exception("Password não pode ser em branco");
            }

            if (this.userRepository.Find(x => x.Email == postUserViewModel.Email & !x.IsDeleted) != null)
            {
                throw new Exception("Já existe usuário cadastrado para esse email");
            }

            Guid response = userRepository.Create(new User
            {
                Id       = Guid.NewGuid(),
                Name     = postUserViewModel.Name,
                Email    = postUserViewModel.Email,
                Password = postUserViewModel.Password
            }).Id;

            userRoleRepository.Create(new UserRole
            {
                Id     = Guid.NewGuid(),
                UserId = response,
                RoleId = roleRepository.Find(x => x.Name == "User" & !x.IsDeleted).Id
            });

            return(response);
        }
Esempio n. 14
0
        public IActionResult CreateOrEdit([FromBody] JsonData jsonData)
        {
            JsonResultHelper  result = new JsonResultHelper();
            UserRoleViewModel model  = jsonData.model;

            UserRole data = null;

            if (model.Id > 0)
            {
                if (!_permissionUser.CheckAccess(PermissionsName.UserRoleEdit))
                {
                    return(AccessDeniedView());
                }

                //Edit Mode
                data = _mapper.Map <UserRoleViewModel, UserRole>(model, _userRoleRepository.GetById(model.Id));

                _userRoleRepository.Update(data);
            }
            else
            {
                if (!_permissionUser.CheckAccess(PermissionsName.UserRoleAdd))
                {
                    return(AccessDeniedView());
                }

                //Add Mode
                data = _mapper.Map <UserRoleViewModel, UserRole>(model);
                _userRoleRepository.Create(data);
            }
            //End result
            result.Access  = true;
            result.success = true;
            //result.data = Model;
            result.url = jsonData.continueEditing ? Url.Action("PrepareUserRole", "UserRole", new { id = data.Id }) : Url.Action("Index", "UserRole");
            return(Json(result));
        }
Esempio n. 15
0
 public void Create(UserRoleRequest request)
 {
     _userRoleRepository.Create(request);
 }
 public void AddUserRoleEntity(UserRoleEntity userRoleEntity)
 {
     _roleRepository.Create(userRoleEntity.ToDalUserRole());
     _uow.Commit();
 }
Esempio n. 17
0
 public void Create(UserRole userRole)
 {
     _repository.Create(_mapper.Map <UserRole, UserRoleEntity>(userRole));
 }
Esempio n. 18
0
 public void CreateUserRole(UserRole userRole)
 {
     _userRoleRepository.Create(userRole);
 }
        public void TestGetAllUserRoles()
        {
            _userRoleRepo.Create(RandomUserRole());
            _userRoleRepo.Create(RandomUserRole());
            _userRoleRepo.Create(RandomUserRole());

            var getResult = _userRoleController.GetProjectUserRoles(_projId).Result;

            Assert.IsInstanceOf <ObjectResult>(getResult);

            var roles = ((ObjectResult)getResult).Value as List <UserRole>;

            Assert.That(roles, Has.Count.EqualTo(3));
            _userRoleRepo.GetAllUserRoles(_projId).Result.ForEach(role => Assert.Contains(role, roles));
        }