コード例 #1
0
        public void CreateApplicationData(CreateApplicationDataRequest createApplicationDataRequest)
        {
            var adminRole = new Role(Guid.Empty, "Admin");

            roleRepository.Add(adminRole);
            var userRole = new Role(Guid.Empty, "User");

            roleRepository.Add(userRole);

            var userSecurity = new UserSecurity(
                Guid.Empty,
                createApplicationDataRequest.Email,
                AuthProvider.Local,
                Guid.NewGuid().ToString(),
                Guid.NewGuid().ToString(),
                Guid.NewGuid().ToString(),
                string.Empty,
                createApplicationDataRequest.Password,
                "en",
                "admin",
                "admin",
                null,
                Gender.Male,
                false,
                true,
                new List <Role> {
                adminRole
            }
                );

            userSecurityRepository.Add(userSecurity);

            CreateMenus(adminRole, userRole);
        }
コード例 #2
0
        public void Add_ChildToRole1()
        {
            var newRole = new Role()
            {
                Name = "NewRole"
            };

            _recursiveRepo.Add("Role1", newRole);
            var result = _recursiveRepo.GetWithOffspring(x => x.Name == "Role1");

            Assert.Equal(8, result.Count());
        }
コード例 #3
0
        public async Task RoleRepository_Add_CanFindByName()
        {
            // Arrange
            await _roleRepository.Add(_role);

            await _roleRepository.UnitOfWork.Commit();

            // Act
            var fromRepo = await _roleRepository.FindByName(_role.Name);

            // Assert
            Assert.NotNull(fromRepo);
            Assert.Equal(_role.Name, fromRepo.Name);
        }
コード例 #4
0
 public ActionResult AddRole(Role role)
 {
     try
     {
         if (role != null)
         {
             Role addRole = RoleRepository.Add(role);
             if (addRole != null)
             {
                 return(Json(new
                 {
                     Success = true,
                     Msg = "角色添加成功。"
                 }));
             }
         }
         return(Json(new
         {
             Success = false,
             Msg = "添加失败,请重新提交。"
         }));
     }
     catch (Exception ex)
     {
         LogRepository.Add(new EventLog()
         {
             Name = Session["LoginedUser"].ToString(), Date = DateTime.Now.ToLocalTime(), Event = "新增角色失败" + ex.Message
         });
         return(Json(new
         {
             Success = false,
             Msg = "添加失败," + ex.Message
         }));
     }
 }
コード例 #5
0
        /// <summary>
        /// Creates a new role instance using the <paramref name="dto"/>.
        /// </summary>
        /// <param name="dto">The data required to create a new <see cref="Role"/>.</param>
        /// <returns>The id of the new <see cref="Role"/>.</returns>
        /// <exception cref="ArgumentNullException">Throws if <paramref name="dto"/> is null.</exception>
        /// <exception cref="ValidationException">Throws if any of the data is invalid, or if the role's name has already been taken.</exception>
        public async Task <string> CreateAsync(CreateRoleDto dto)
        {
            if (dto == null)
            {
                throw new ArgumentNullException(nameof(dto));
            }

            _logger.LogDebug("Creating a new role...");

            var role = Role.Create(dto);

            if (await _repository.ExistsWithNameAsync(role.Name))
            {
                _logger.LogDebug("Failed to create new role as the name '{0}' has already been taken.", role.Name);
                throw new ValidationException(ErrorMessages.RoleNameTaken);
            }

            _logger.LogDebug("Adding the new role to the repository...");

            _repository.Add(role);
            await _repository.SaveChangesAsync();

            _logger.LogDebug("Successfully created new role with id '{0}'", role.Id);

            return(role.Id);
        }
コード例 #6
0
        public VmGenericServiceResult Insert(VmRoleItem vmRoleItem)
        {
            VmGenericServiceResult result = new VmGenericServiceResult();

            try
            {
                Role r = new Role();

                Copy <VmRoleItem, Role>(vmRoleItem, r);

                if (r.CreatedBy.IsNullOrEmpty())
                {
                    r.CreatedBy = r.UpdatedBy = "System";
                }

                repo.Add(r);

                repo.Commit();

                result.IsSuccess = true;
            }
            catch (Exception e)
            {
                result.IsSuccess = false;
                result.Error     = e;
            }

            return(result);
        }
コード例 #7
0
        public AjaxResult Save(Role old, Role role)
        {
            bool addFlag = role.ID < 1;

            var user = us.GetCurrent();

            role.CREATEBY   = user.ACCOUNT;
            role.CREATEDATE = DateTime.Now;
            role.UPDATEBY   = user.ACCOUNT;
            role.UPDATEDATE = DateTime.Now;
            role.ENABLED    = true;
            if (addFlag)
            {
                bool       flag = roleRep.Add(role);
                ActionType type = ActionType.SYS_ADD;
                string     msg  = WebConst.GetActionMsg(type, flag);
                ls.Append(msg).AddSystem(type);
                return(new AjaxResult(flag, msg));
            }
            else
            {
                ActionType type = ActionType.SYS_UPDATE;
                bool       flag = roleRep.Update(role, m => new { m.NAME, m.REMARK, m.SORTID, m.UPDATEBY, m.UPDATEDATE }, m => m.ID == role.ID);
                string     msg  = WebConst.GetActionMsg(type, flag);
                ls.AppendUpdate("角色名称", old.NAME, role.NAME);
                ls.AppendUpdate("角色描述", old.REMARK, role.REMARK);
                ls.AddSystem(type, role.ID);
                return(new AjaxResult(flag, msg));
            }
        }
コード例 #8
0
        private void RegisterAdministratorFor(
            Tenant tenant,
            FullName administorName,
            EmailAddress emailAddress,
            PostalAddress postalAddress,
            Telephone primaryTelephone,
            Telephone secondaryTelephone)
        {
            RegistrationInvitation invitation = tenant.OfferRegistrationInvitation("init").OpenEnded();
            string strongPassword             = new PasswordService().GenerateStrongPassword();

            // Publishes domain event UserRegistered.
            User admin = tenant.RegisterUser(
                invitation.InvitationId,
                "admin",
                strongPassword,
                Enablement.IndefiniteEnablement(),
                new Person(
                    tenant.TenantId,
                    administorName,
                    new ContactInformation(
                        emailAddress,
                        postalAddress,
                        primaryTelephone,
                        secondaryTelephone)));

            tenant.WithdrawInvitation(invitation.InvitationId);

            // Since this is a new entity, add it to
            // the collection-oriented repository.
            // Subsequent changes to the entity
            // are implicitly persisted.
            _userRepository.Add(admin);

            // Publishes domain event RoleProvisioned.
            Role adminRole = tenant.ProvisionRole(
                "Administrator",
                string.Format("Default {0} administrator.", tenant.Name));

            // Publishes domain event UserAssignedToRole,
            // but not GroupUserAdded because the group
            // reference held by the role is an "internal" group.
            adminRole.AssignUser(admin);

            // Since this is a new entity, add it to
            // the collection-oriented repository.
            // Subsequent changes to the entity
            // are implicitly persisted.
            _roleRepository.Add(adminRole);

            DomainEventPublisher
            .Instance
            .Publish(new TenantAdministratorRegistered(
                         tenant.TenantId,
                         tenant.Name,
                         administorName,
                         emailAddress,
                         admin.Username,
                         strongPassword));
        }
        public CreateResult <int> CreateRole(RoleDto roleDto)
        {
            var result = GetDefault <CreateResult <int> >();

            if (IsExisted(roleDto.Name))
            {
                result.Message = "ROLE_NAME_HAS_EXIST";
                return(result);
            }

            var role = new Role()
            {
                RoleName     = roleDto.Name,
                CreationTime = DateTime.Now
            };

            if (roleDto.Permissions != null && roleDto.Permissions.Any())
            {
                roleDto.Permissions.ForEach(p => role.RolePermissions.Add(new RolePermission()
                {
                    PermissionId = p.Id
                }));
            }

            _roleRepository.Add(role);
            _roleRepository.Commit();
            result.Id        = role.Id;
            result.IsCreated = true;
            return(result);
        }
コード例 #10
0
        public Guid SaveRole(RoleModel data, SaveMode saveMode)
        {
            var role = roleRepository.Get(data.Id);

            if (saveMode == SaveMode.CreateNew)
            {
                if (role != null)
                {
                    throw new DataValidationException(MessageResource.Error_InsertDuplicateKey);
                }
                role    = new Role();
                role.Id = Guid.NewGuid();
                roleRepository.Add(role);
            }
            else
            {
                if (role == null)
                {
                    throw new DataValidationException(string.Format(MessageResource.Error_DataNotFoundForUpdate, "Role"));
                }
            }
            var isdup = roleRepository.GetAll().Where(t => t.Id != role.Id && t.Name == data.Name).Any();

            if (isdup)
            {
                throw new DataValidationException(string.Format(MessageResource.Error_UpdateDuplicateUniqeField, "Name"));
            }
            role.Name        = data.Name;
            role.Description = data.Description;
            role.IsActive    = data.IsActive;
            unitOfWork.SaveChanges();
            return(role.Id);
        }
コード例 #11
0
        public IActionResult Create(RoleViewModel model)
        {
            if (ModelState.IsValid && Validate(model))
            {
                try
                {
                    _roleRepository.Add(new Role()
                    {
                        Id       = Guid.NewGuid().ToString(),
                        RoleCode = model.RoleCode,
                        RoleName = model.RoleName
                    });
                    _roleRepository.Save(RequestContext);
                    _userInfoCache.RemoveMenuCaches();
                    _logger.LogInformation("Create Role {0}", model.RoleName);
                    return(RedirectToAction("Index"));
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Update role {0} failed", model.RoleName);
                    return(View());

                    throw;
                }
            }
            return(View());
        }
コード例 #12
0
        public async Task <bool> Add(RoleDto model)
        {
            var artRole = _mapper.Map <Role>(model);

            _repoRole.Add(artRole);
            return(await _repoRole.SaveAll());
        }
コード例 #13
0
        public CreateRoleResponse CreateRole(CreateRoleRequest request)
        {
            CreateRoleResponse response = new CreateRoleResponse();
            Role role = new Role();

            role.RoleName    = request.RoleName;
            role.Description = request.Description;
            role.Permissions = request.Permissions.ConvertToPermissions();
            role.Users       = request.Users.ConvertToUsers();

            if (role.GetBrokenRules().Count() > 0)
            {
                response.Errors = role.GetBrokenRules().ToList();
            }
            else
            {
                try {
                    _roleRepository.Add(role);
                    _uow.Commit();
                    response.Errors = new List <BusinessRule>();
                } catch (Exception ex)
                {
                    List <BusinessRule> errors = new List <BusinessRule>();
                    do
                    {
                        errors.Add(new BusinessRule("DAL", "DAL_ERROR: " + ex.Message));
                        ex = ex.InnerException;
                    } while (ex != null);

                    response.Errors = errors;
                }
            }

            return(response);
        }
コード例 #14
0
ファイル: RoleService.cs プロジェクト: cadukich/SaaSPro
        public void AddRole(AddRoleRequest request)
        {
            var role = new Role(request.Customer, request.RolesUpdateModel.Name, userType: request.RolesUpdateModel.UserType);

            _roleRepository.Add(role);
            _unitOfWork.Commit();
        }
コード例 #15
0
        public RoleDTO Add(RoleDTO roleDTO)
        {
            var role = roleDTO.ToModel();

            role.Id      = IdentityGenerator.NewSequentialGuid();
            role.Created = DateTime.UtcNow;

            var group = _RoleGroupRepository.Get(roleDTO.RoleGroupId);

            if (group == null)
            {
                throw new DataExistsException(UserSystemResource.RoleGroup_NotExists);
            }
            role.RoleGroup = group;

            if (role.Name.IsNullOrBlank())
            {
                throw new DataExistsException(UserSystemResource.Common_Name_Empty);
            }

            if (_Repository.Exists(role))
            {
                throw new DataExistsException(UserSystemResource.Role_Exists);
            }

            _Repository.Add(role);

            //commit the unit of work
            _Repository.UnitOfWork.Commit();

            return(role.ToDto());
        }
コード例 #16
0
 public async Task <DefaultEventHandlerResponse> InitRoleBasedAccessControler(EventHandleRequest <LoginSuccessDto> input)
 {
     return(await new DefaultEventHandlerResponse().RunAsync(nameof(InitRoleBasedAccessControler), input.GetDataJson(), async() =>
     {
         InitUserOauthDto.Github data = default;
         if (!string.IsNullOrEmpty(input.GetData().Token))
         {
             data = System.Text.Json.JsonSerializer.Deserialize <InitUserOauthDto.Github>(input.GetData().Token);
         }
         var role = new Role();
         role.SetRole("超级管理员", true);
         roleRepository.Add(role);
         var admin = new Account();
         var defpwd = "x1234567";
         admin.CreateAccount(data?.login ?? "eshopadmin", data?.name ?? "商城管理员", defpwd, Common.GetMD5SaltCode);
         if (data != null)
         {
             admin.User.CreateOrUpdateUser(data?.name ?? "商城管理员", data?.avatar_url ?? "", "", "", UserGender.Male, Convert.ToDateTime("1980-01-01"));
         }
         admin.SetRoles(new List <Guid>()
         {
             role.Id
         });
         var defbuyer = new Account();
         defbuyer.CreateAccount("eshopuser", "白云苍狗", defpwd, Common.GetMD5SaltCode);
         defbuyer.User.CreateOrUpdateUser("张老三", "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.huabanimg.com%2F0830450561b24f4573bed70d7f74bd43f39302e11bee-s2tj6i_fw658&refer=http%3A%2F%2Fhbimg.huabanimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1618110799&t=b215598f3b458ad7c08aee2b4614622b", "北京市海淀区太平路1号", "13000000000", UserGender.Male, Convert.ToDateTime("1980-01-01"));
         accountRepository.Add(admin);
         accountRepository.Add(defbuyer);
         if (await new UniqueSuperRoleSpecification(roleRepository).IsSatisfiedBy(role))
         {
             await unitofWork.CommitAsync();
         }
         await stateManager.SetState(new RoleBaseInitCheckCache(true));
     }));
コード例 #17
0
 protected override async Task Handle(CreateRoleCommand request, CancellationToken cancellationToken)
 {
     var role = new Core.Models.Role {
         Name = request.Name
     };
     await _roleRepository.Add(role, cancellationToken);
 }
コード例 #18
0
        public override async Task <int> HandleCommand(AddCommand request, CancellationToken cancellationToken)
        {
            if (request.Role == null || string.IsNullOrEmpty(request.Role.Name))
            {
                throw new BusinessException("Common.WrongInput");
            }

            var checkingRole = await roleQueries.GetByName(request.Role.Name);

            if (checkingRole != null)
            {
                throw new BusinessException("User.ExistedRole");
            }

            var roleId = -1;

            using (var conn = DalHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        roleRepository.JoinTransaction(conn, trans);
                        rolePermissionRepository.JoinTransaction(conn, trans);

                        request.Role.IsExternalRole = false;
                        request.Role = CreateBuild(request.Role, request.LoginSession);
                        roleId       = await roleRepository.Add(request.Role);

                        foreach (var item in request.Role.RolePermissions)
                        {
                            item.RoleId = roleId;
                            await rolePermissionRepository.AddOrUpdate(item);
                        }
                    }
                    finally
                    {
                        if (roleId > 0)
                        {
                            trans.Commit();
                        }
                        else
                        {
                            try
                            {
                                trans.Rollback();
                            }
                            catch (Exception ex)
                            {
                                LogHelper.GetLogger().Error(ex);
                            }
                        }
                    }
                }
            }

            return(roleId);
        }
コード例 #19
0
        public ServiceResult <string> AddRole(RoleServiceModel role)
        {
            var addResult = roleRepository.Add(role.ConvertToModel());

            return(addResult.IsSuccess ? ServiceResult <string> .Success("success - add", "cs1") : ServiceResult <string> .Failed(string.Empty, "cs2"));

            //ServiceResult<string>(addResult.IsSuccess, addResult.IsSuccess ? string.Empty : "Error during adding a role.");
        }
コード例 #20
0
        public async Task <bool> Handle(RoleInsertCommand roleInsertCommand, CancellationToken cancellationToken)
        {
            var role = Role.Create(roleInsertCommand.Description);

            _roleRepository.Add(role);

            return(await _roleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken));
        }
コード例 #21
0
        public void ProvisionRole(ProvisionRoleCommand command)
        {
            var tenantId = new TenantId(command.TenantId);
            var tenant   = _tenantRepository.Get(tenantId);
            var role     = tenant.ProvisionRole(command.RoleName, command.Description, command.SupportsNesting);

            _roleRepository.Add(role);
        }
コード例 #22
0
 public object AddRole()
 {
     _role.Add(new Role()
     {
         Name = "role"
     });
     return(null);
 }
コード例 #23
0
        public async Task <RoleResponse> Add(RoleRequest roleRequest)
        {
            Role role = Role.Create(roleRequest.Name);

            _roleRepository.Add(role);

            return(await Task.FromResult(_mapper.Map <Role, RoleResponse>(role)));
        }
コード例 #24
0
        /// <summary>
        /// Create a new role
        /// </summary>
        /// <param name="roleName">name of the role</param>
        public override void CreateRole(string roleName)
        {
            var role = new Role {
                Name = roleName, Description = String.Empty, DateCreated = DateTime.Now
            };

            _roleRepository.Add(role);
        }
コード例 #25
0
        public async Task AddRole(string roleName)
        {
            var role = new IdentityRole(roleName)
            {
                NormalizedName = RoleHelper.Normalize(roleName)
            };

            _roleRepo.Add(role);
            await _unitOfWork.Save();
        }
コード例 #26
0
ファイル: RoleStore.cs プロジェクト: shakermegahed/CoreCrud
        public async Task <IdentityResult> CreateAsync(Entities.Identity.ApplicationRole role, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            role.RoleId = Guid.NewGuid();

            await _roleRepository.Add(role);

            return(IdentityResult.Success);
        }
コード例 #27
0
        public RoleModel Add(AppRole entity)
        {
            var product = _repository.Add(entity);

            return(new RoleModel
            {
                Id = product.Id,
                Name = product.Name,
            });
        }
コード例 #28
0
ファイル: RoleService.cs プロジェクト: Dmitriy2Belikov/Auth
        public Role Add(string name, IEnumerable <Guid> systemModuleIds)
        {
            var role = _roleFactory.Create(name);

            _roleRepository.Add(role);

            AssignSystemModules(role.Id, systemModuleIds);

            return(role);
        }
コード例 #29
0
        public void CreateRole(IdentityRole role)
        {
            role.Id = Guid.NewGuid().ToString("D");

            using (var dbContextScope = DbContextScopeFactory.Create())
            {
                _roleRepository.Add(role);
                dbContextScope.SaveChanges();
            }
        }
コード例 #30
0
ファイル: RoleStoreService.cs プロジェクト: cong1389/KuteShop
        public Task CreateAsync(IdentityRole role)
        {
            if (role == null)
            {
                throw new ArgumentNullException("role");
            }
            var role1 = GetRole(role);

            _roleRepository.Add(role1);
            return(_unitOfWork.CommitAsync());
        }
コード例 #31
0
        protected override void CreateInitialData()
        {
            _userRepository = Locator.GetService<IUserRepository>();
            var passwordSalt = PasswordMethods.CreateSalt();
            var users = new[]
                           {
                               new User
                                   {
                                       Login = "******",
                                       Email = "*****@*****.**",
                                       CreatedDate = DateTime.Now,
                                       PasswordSalt = passwordSalt,
                                       Password = PasswordMethods.CreatePasswordHash("testtest", passwordSalt),
                                       IsActivated = true,
                                       IsLockedOut = false,
                                       LastLockedOutDate = null,
                                       LastLoginDate = null,
                                   },
                               new User
                                   {
                                       Login = "******",
                                       Email = "*****@*****.**",
                                       CreatedDate = DateTime.Now,
                                       PasswordSalt = passwordSalt,
                                       Password = PasswordMethods.CreatePasswordHash("testtest", passwordSalt),
                                       IsActivated = true,
                                       IsLockedOut = false,
                                       LastLockedOutDate = null,
                                       LastLoginDate = null,
                                   }
                           };
            foreach (var obj in users)
            {
                _userRepository.Add(obj);
            }
            _roleRepository = Locator.GetService<IRoleRepository>();
            var roles = new[]
                            {
                                new Role
                                    {
                                        RoleName = "admin"
                                    },
                                new Role
                                    {
                                        RoleName = "user"
                                    }
                            };

            foreach (var obj in roles)
            {
                _roleRepository.Add(obj);
            }
        }