Exemplo n.º 1
0
        public virtual async Task <IdentityUserDto> RegisterAsync(RegisterDto input)
        {
            await CheckSelfRegistrationAsync();

            await IdentityOptions.SetAsync();

            var user = new IdentityUser(GuidGenerator.Create(), input.UserName, input.EmailAddress, CurrentTenant.Id);

            input.MapExtraPropertiesTo(user);

            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();

            await UserManager.SetEmailAsync(user, input.EmailAddress);

            await UserManager.AddDefaultRolesAsync(user);

            return(ObjectMapper.Map <IdentityUser, IdentityUserDto>(user));
        }
Exemplo n.º 2
0
        public virtual async Task <IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
        {
            var user = new IdentityUser(
                GuidGenerator.Create(),
                input.UserName,
                input.PhoneNumber,
                CurrentTenant.Id
                );

            input.MapExtraPropertiesTo(user);

            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();
            await UpdateUserByInput(user, input);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <IdentityUser, IdentityUserDto> (user));
        }
Exemplo n.º 3
0
        protected virtual void CheckAndSetId(EntityEntry entry)
        {
            //Set GUID Ids
            var entity = entry.Entity as IEntity <Guid>;

            if (entity != null && entity.Id == Guid.Empty)
            {
                var dbGeneratedAttr = ReflectionHelper
                                      .GetSingleAttributeOrDefault <DatabaseGeneratedAttribute>(
                    entry.Property("Id").Metadata.PropertyInfo
                    );

                if (dbGeneratedAttr == null || dbGeneratedAttr.DatabaseGeneratedOption == DatabaseGeneratedOption.None)
                {
                    entity.Id = GuidGenerator.Create();
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 新增一条用户
        /// </summary>
        public async Task AddUserInfer(UserAllInput input)
        {
            var UserDetail = ObjectMapper.Map <UserAllInput, UserSession>(input);

            UserDetail.Id = GuidGenerator.Create();

            var UserInfo = ObjectMapper.Map <Userins, UserInfer>(input.userins);

            UserInfo.Id = GuidGenerator.Create();
            await _userInfoRepository.InsertAsync(UserInfo);

            var Dangan = ObjectMapper.Map <Danganins, DanganInfer>(input.danganins);

            Dangan.Id = GuidGenerator.Create();
            await _danganRepository.InsertAsync(Dangan);

            await _userRepository.InsertAsync(UserDetail);
        }
        public async Task <DictionaryDto> Create(CreateOrUpdateDictionaryDto input)
        {
            var exist = await _repository.FirstOrDefaultAsync(_ => _.Name == input.Name);

            if (exist != null)
            {
                throw new BusinessException("名称:" + input.Name + "字典已存在");
            }

            var dic = new DataDictionary(
                GuidGenerator.Create(),
                input.Name,
                input.Description);

            var result = await _repository.InsertAsync(dic);

            return(ObjectMapper.Map <DataDictionary, DictionaryDto>(result));
        }
Exemplo n.º 6
0
        public virtual async Task <MenuDto> CreateAsync(MenuCreateDto input)
        {
            var layout = await LayoutRepository.GetAsync(input.LayoutId);

            var data = await DataRepository.GetAsync(layout.DataId);

            var menu = await MenuManager.CreateAsync(
                layout,
                GuidGenerator.Create(),
                input.Path,
                input.Name,
                input.Component,
                input.DisplayName,
                input.Redirect,
                input.Description,
                input.ParentId,
                CurrentTenant.Id,
                input.IsPublic);

            // 利用布局约定的数据字典来校验必须的路由元数据,元数据的加入是为了适配多端路由
            foreach (var dataItem in data.Items)
            {
                if (!input.Meta.TryGetValue(dataItem.Name, out object meta))
                {
                    if (!dataItem.AllowBeNull)
                    {
                        throw new BusinessException(PlatformErrorCodes.MenuMissingMetadata)
                              .WithData("Name", dataItem.DisplayName)
                              .WithData("DataName", data.DisplayName);
                    }
                    // 是否需要设定默认值
                    menu.SetProperty(dataItem.Name, dataItem.DefaultValue);
                }
                else
                {
                    // 需要检查参数是否有效
                    menu.SetProperty(dataItem.Name, DataItemMapping.MapToString(dataItem.ValueType, meta));
                }
            }

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <Menu, MenuDto>(menu));
        }
    protected virtual async Task <FlashSalePlan> CreateFlashSalePlanAsync(bool useSku2 = false, CreateTimeRange timeRange = CreateTimeRange.Starting, bool isPublished = true)
    {
        DateTime beginTime;
        DateTime endTime;

        switch (timeRange)
        {
        case CreateTimeRange.Starting:
            beginTime = Clock.Now;
            endTime   = beginTime.AddMinutes(30);
            break;

        case CreateTimeRange.NotStart:
            beginTime = Clock.Now.AddMinutes(10);
            endTime   = beginTime.AddMinutes(30);
            break;

        case CreateTimeRange.Expired:
            beginTime = Clock.Now.AddDays(-1);
            endTime   = beginTime.AddMinutes(30);
            break;

        case CreateTimeRange.WillBeExpired:
            beginTime = Clock.Now.AddDays(-30);
            endTime   = Clock.Now.AddSeconds(1);
            break;

        default:
            throw new AbpException();
        }

        var flashSalePlan = new FlashSalePlan(
            GuidGenerator.Create(),
            CurrentTenant.Id,
            FlashSalesTestData.Store1Id,
            beginTime,
            endTime,
            FlashSalesTestData.Product1Id,
            useSku2 ? FlashSalesTestData.ProductSku2Id : FlashSalesTestData.ProductSku1Id,
            isPublished
            );

        return(await WithUnitOfWorkAsync(async() => await FlashSalePlanRepository.InsertAsync(flashSalePlan, autoSave: true)));
    }
Exemplo n.º 8
0
        public virtual async Task RegisterAsync(WeChatRegisterDto input)
        {
            ThowIfInvalidEmailAddress(input.EmailAddress);

            await CheckSelfRegistrationAsync();

            await IdentityOptions.SetAsync();

            var options = await MiniProgramOptionsFactory.CreateAsync();

            var wehchatOpenId = await WeChatOpenIdFinder.FindAsync(input.Code, options.AppId, options.AppSecret);

            var user = await UserManager.FindByLoginAsync(AbpWeChatMiniProgramConsts.ProviderKey, wehchatOpenId.OpenId);

            if (user != null)
            {
                // 应该要抛出微信号已注册异常,而不是直接返回注册用户数据,否则造成用户信息泄露
                throw new UserFriendlyException(L["DuplicateWeChat"]);
            }
            var userName = input.UserName;

            if (userName.IsNullOrWhiteSpace())
            {
                userName = "******" + wehchatOpenId.OpenId.ToMd5().ToLower();
            }

            var userEmail = input.EmailAddress;//如果邮件地址不验证,随意写入一个

            if (userEmail.IsNullOrWhiteSpace())
            {
                userEmail = $"{userName}@{CurrentTenant.Name ?? "default"}.io";
            }

            user = new IdentityUser(GuidGenerator.Create(), userName, userEmail, CurrentTenant.Id);
            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();

            (await UserManager.AddDefaultRolesAsync(user)).CheckErrors();

            var userLogin = new UserLoginInfo(AbpWeChatMiniProgramConsts.ProviderKey, wehchatOpenId.OpenId, AbpWeChatGlobalConsts.DisplayName);

            (await UserManager.AddLoginAsync(user, userLogin)).CheckErrors();

            await CurrentUnitOfWork.SaveChangesAsync();
        }
        public async Task CreateAsync(WorkflowDefinitionCreateDto input)
        {
            var workflow = new WorkflowDefinitionVersion(
                GuidGenerator.Create().ToString(),
                input.Name,
                input.Description,
                input.IsSingleton,
                input.IsDisabled);

            workflow.Activities = input.Activities
                                  .Select(x => new ActivityDefinition(x.Id, x.Type,
                                                                      x.State,
                                                                      x.Left, x.Top))
                                  .ToList();
            workflow.Connections = input.Connections.Select(
                x => new ConnectionDefinition(GuidGenerator.Create().ToString(), x.SourceActivityId, x.DestinationActivityId, x.Outcome)).ToList();
            workflow.IsLatest = true;
            await _workflowDefinitionVersionRepository.InsertAsync(workflow);
        }
Exemplo n.º 10
0
    public virtual async Task <IdentityUser> CreateUserAsync(string userName, string providerName)
    {
        await IdentityOptions.SetAsync();

        var externalUser = await GetUserInfoAsync(userName);

        NormalizeExternalLoginUserInfo(externalUser, userName);

        var user = new IdentityUser(
            GuidGenerator.Create(),
            userName,
            externalUser.Email,
            tenantId: CurrentTenant.Id
            );

        user.Name    = externalUser.Name;
        user.Surname = externalUser.Surname;

        user.IsExternal = true;

        user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false);
        user.SetPhoneNumber(externalUser.PhoneNumber, externalUser.PhoneNumberConfirmed ?? false);

        (await UserManager.CreateAsync(user)).CheckErrors();

        if (externalUser.TwoFactorEnabled != null)
        {
            (await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors();
        }

        (await UserManager.AddDefaultRolesAsync(user)).CheckErrors();
        (await UserManager.AddLoginAsync(
             user,
             new UserLoginInfo(
                 providerName,
                 externalUser.ProviderKey,
                 providerName
                 )
             )
        ).CheckErrors();

        return(user);
    }
Exemplo n.º 11
0
        public virtual async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data)
        {
            Check.NotNull(deviceCode, nameof(deviceCode));
            Check.NotNull(userCode, nameof(userCode));
            Check.NotNull(data, nameof(data));

            await DeviceFlowCodesRepository
            .InsertAsync(
                new DeviceFlowCodes (GuidGenerator.Create()) {
                DeviceCode   = deviceCode,
                UserCode     = userCode,
                ClientId     = data.ClientId,
                SubjectId    = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value,
                CreationTime = data.CreationTime,
                Expiration   = data.CreationTime.AddSeconds(data.Lifetime),
                Data         = Serialize(data)
            }
                );
        }
Exemplo n.º 12
0
        public async Task <List <Tag> > GetAndCreateTagsAsync(List <string> names, CancellationToken cancellationToken = default)
        {
            var tags = await GetByNamesAsync(names, cancellationToken);

            if (tags.Count != names.Count)
            {
                foreach (var name in names)
                {
                    if (!tags.Exists(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
                    {
                        var tag = await InsertAsync(new Tag(GuidGenerator.Create(), name, 0), cancellationToken : cancellationToken);

                        tags.Add(tag);
                    }
                }
            }

            return(tags);
        }
Exemplo n.º 13
0
        public virtual async Task <OrganizationUnitDto> CreateAsync(OrganizationUnitCreateDto input)
        {
            var ou = new OrganizationUnit(
                GuidGenerator.Create(),
                input.DisplayName,
                input.ParentId,
                CurrentTenant.Id
                )
            {
            };

            input.MapExtraPropertiesTo(ou);

            await UnitManager.CreateAsync(ou);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <OrganizationUnit, OrganizationUnitDto>(ou));
        }
Exemplo n.º 14
0
        //[Authorize(ProductPermissions.Products.Create)]
        public async Task <ServiceDto> CreateAsync(CreateProductDto input)
        {
            var service = await _serviceRepository.InsertAsync(
                new Service(
                    GuidGenerator.Create(),
                    input.Code,
                    input.Name,
                    input.Type,
                    input.Category,
                    input.Description,
                    input.LiveMode,
                    input.Metadata,
                    input.ProductImage

                    )
                );

            return(ObjectMapper.Map <Service, ServiceDto>(service));
        }
Exemplo n.º 15
0
    public virtual async Task <IdentityRoleDto> CreateAsync(IdentityRoleCreateDto input)
    {
        var role = new IdentityRole(
            GuidGenerator.Create(),
            input.Name,
            CurrentTenant.Id
            )
        {
            IsDefault = input.IsDefault,
            IsPublic  = input.IsPublic
        };

        input.MapExtraPropertiesTo(role);

        (await RoleManager.CreateAsync(role)).CheckErrors();
        await CurrentUnitOfWork.SaveChangesAsync();

        return(ObjectMapper.Map <IdentityRole, IdentityRoleDto>(role));
    }
        public virtual async Task SeedUserMenuAsync(
            Guid userId,
            Menu menu,
            Guid?tenantId = null,
            CancellationToken cancellationToken = default)
        {
            if (!await UserMenuRepository.UserHasInMenuAsync(userId, menu.Name, cancellationToken))
            {
                var userMenu = new UserMenu(GuidGenerator.Create(), menu.Id, userId, tenantId);
                await UserMenuRepository.InsertAsync(userMenu);

                var childrens = await MenuRepository.GetChildrenAsync(menu.Id);

                foreach (var children in childrens)
                {
                    await SeedUserMenuAsync(userId, children, tenantId, cancellationToken);
                }
            }
        }
Exemplo n.º 17
0
        protected virtual async Task GrantAsync(string name, string providerKey)
        {
            var permissionGrant = await PermissionGrantRepository.FindAsync(name, Name, providerKey);

            if (permissionGrant != null)
            {
                return;
            }

            await PermissionGrantRepository.InsertAsync(
                new PermissionGrant(
                    GuidGenerator.Create(),
                    name,
                    Name,
                    providerKey,
                    CurrentTenant.Id
                    )
                );
        }
Exemplo n.º 18
0
        public async override Task <UserAdvertisingDto> CreateAsync(UserAdvertisingCreateUpdateDto input)
        {
            var adItem = await _advertisingItemRepository.GetAsync(input.AdvertisingItemId);

            if (!adItem.IsOnSale)
            {
                throw new UserFriendlyException(L["AdPositonHasBeenSoldOut"]);
            }

            var userAd = new UserAdvertising(GuidGenerator.Create(), CurrentUser.TenantId, CurrentUser.GetId(), input.AdvertisingItem.AdvertisingItemId, Clock.Now);

            userAd = await _repository.InsertAsync(userAd);

            var result = ObjectMapper.Map <UserAdvertising, UserAdvertisingDto>(userAd);

            result.AdvertisingItem = ObjectMapper.Map <AdvertisingItem, AdvertisingItemDto>(adItem);

            return(result);
        }
Exemplo n.º 19
0
        public async Task <TaskDto> CreateAsync(CreateUpdateTaskDto input)
        {
            var task = new Task(
                id: GuidGenerator.Create(),
                title: input.Title,
                Remark: input.Remark
                )
            {
                StartTime = input.StartTime, EndTime = input.EndTime, Priority = input.Priority, Status = 0, TaskType = input.TaskType
            };

            task.TenantId     = CurrentTenant.Id;
            task.CreateUserId = CurrentUser.Id ?? Guid.Empty;
            //todo:CurrentUser.Id;

            await _taskRepository.InsertAsync(task);

            return(ObjectMapper.Map <Task, TaskDto>(task));
        }
Exemplo n.º 20
0
        public async Task <Author> CreateAsync(
            [NotNull] string name,
            DateTime birthDate,
            [CanBeNull] string shortBio = null)
        {
            Check.NotNullOrWhiteSpace(name, nameof(name));
            var existingAuthor = await _authorRepository.FindByNameAsync(name);

            if (existingAuthor != null)
            {
                throw new AuthorAlreadyExistsException(name);
            }
            return(new Author(
                       GuidGenerator.Create(),
                       name,
                       birthDate,
                       shortBio
                       ));
        }
Exemplo n.º 21
0
        public override async Task <DictionaryDto> CreateAsync(CreateDataDictionaryDto input)
        {
            if ((await Repository.FindAsync(d => d.Name == input.Name)) != null)
            {
                throw new UserFriendlyException(L["HasCreatedMessage", input.Name],
                                                AbpDataDictionaryErrorCodes.DictionaryIsExist);
            }

            var dic = new DataDictionary(
                GuidGenerator.Create(),
                input.Name,
                input.Description,
                input.Sort,
                CurrentTenant.Id
                );
            var result = await Repository.InsertAsync(dic, true);

            return(MapDataDictionaryToDto(result));
        }
Exemplo n.º 22
0
    protected async Task <bool> AddToInboxAsync(
        string messageId,
        string eventName,
        Type eventType,
        byte[] eventBytes)
    {
        if (AbpDistributedEventBusOptions.Inboxes.Count <= 0)
        {
            return(false);
        }

        using (var scope = ServiceScopeFactory.CreateScope())
        {
            foreach (var inboxConfig in AbpDistributedEventBusOptions.Inboxes.Values.OrderBy(x => x.EventSelector is null))
            {
                if (inboxConfig.EventSelector == null || inboxConfig.EventSelector(eventType))
                {
                    var eventInbox =
                        (IEventInbox)scope.ServiceProvider.GetRequiredService(inboxConfig.ImplementationType);

                    if (!messageId.IsNullOrEmpty())
                    {
                        if (await eventInbox.ExistsByMessageIdAsync(messageId))
                        {
                            continue;
                        }
                    }

                    await eventInbox.EnqueueAsync(
                        new IncomingEventInfo(
                            GuidGenerator.Create(),
                            messageId,
                            eventName,
                            eventBytes,
                            Clock.Now
                            )
                        );
                }
            }
        }

        return(true);
    }
Exemplo n.º 23
0
        protected virtual async Task GrantAsync(Guid menuId, string providerKey)
        {
            var menuGrant = await MenuGrantRepository.FindAsync(menuId, Name, providerKey);

            if (menuGrant != null)
            {
                return;
            }

            await MenuGrantRepository.InsertAsync(
                new MenuGrant(
                    GuidGenerator.Create(),
                    menuId,
                    Name,
                    providerKey,
                    CurrentTenant.Id
                    )
                );
        }
Exemplo n.º 24
0
        public virtual async Task <MediaDescriptorDto> CreateAsync(CreateMediaInputStream inputStream)
        {
            var definition = await MediaDescriptorDefinitionStore.GetDefinitionAsync(inputStream.EntityType);

            await CheckAnyOfPoliciesAsync(definition.CreatePolicies);

            var newId = GuidGenerator.Create();

            using (var stream = inputStream.GetStream())
            {
                var newEntity = await MediaDescriptorManager.CreateAsync(inputStream.EntityType, inputStream.Name, inputStream.ContentType, inputStream.ContentLength ?? 0);

                await MediaContainer.SaveAsync(newId.ToString(), stream);

                await MediaDescriptorRepository.InsertAsync(newEntity);

                return(ObjectMapper.Map <MediaDescriptor, MediaDescriptorDto>(newEntity));
            }
        }
Exemplo n.º 25
0
        public override async Task <MessageDto> UpdateAsync(Guid id, MessageCreateUpdateDto input)
        {
            var message = await _repository.GetAsync(id);

            message.Update(input.TypeName, input.Title, input.Body);
            await _repository.UpdateAsync(message);

            // 用户消息
            var userMessages = new List <UserMessage>();

            foreach (var user in input.Users)
            {
                userMessages.Add(new UserMessage(GuidGenerator.Create(), message.Id, user.TenantId, user.UserId));
            }

            await _userMessageRepository.InsertManyAsync(userMessages);

            return(ObjectMapper.Map <Message, MessageDto>(message));
        }
        public async Task <ApiResourceDto> CreateAsync(CreateApiResourceInputDto input)
        {
            var nameExist = await _repository.CheckNameExistAsync(input.Name);

            if (nameExist)
            {
                throw new ApiResourceNameNowAllowedDuplicateException(input.Name);
            }

            var apiResource = new ApiResource(GuidGenerator.Create(), input.Name, input.DisplayName, input.Description);

            // 新建时不创建scope
            apiResource.RemoveAllScopes();

            input.UserClaims.ForEach(x => apiResource.AddUserClaim(x));
            apiResource = await _repository.InsertAsync(apiResource);

            return(MapToGetOutputDto(apiResource));
        }
        public virtual async Task SeedRoleMenuAsync(
            string roleName,
            Menu menu,
            Guid?tenantId = null,
            CancellationToken cancellationToken = default)
        {
            if (!await RoleMenuRepository.RoleHasInMenuAsync(roleName, menu.Name, cancellationToken))
            {
                var roleMenu = new RoleMenu(GuidGenerator.Create(), menu.Id, roleName, tenantId);
                await RoleMenuRepository.InsertAsync(roleMenu);

                var childrens = await MenuRepository.GetChildrenAsync(menu.Id);

                foreach (var children in childrens)
                {
                    await SeedRoleMenuAsync(roleName, children, tenantId, cancellationToken);
                }
            }
        }
Exemplo n.º 28
0
        public async Task <DataDictionaryDto> CreateAsync(DataDictionaryCreateDto input)
        {
            var newDict = new DataDictionary(GuidGenerator.Create(),
                                             CurrentTenant.Id,
                                             input.Code,
                                             input.DisplayText,
                                             input.Description,
                                             new List <DataDictionaryItem>(),
                                             input.IsStatic);

            foreach (var itemDto in input.Items)
            {
                newDict.AddOrUpdateItem(itemDto.Code, itemDto.DisplayText, itemDto.Description);
            }

            await _dataDictionaryManager.CreateAsync(newDict);

            return(ObjectMapper.Map <DataDictionary, DataDictionaryDto>(newDict));
        }
Exemplo n.º 29
0
        public async Task <TenantDto> CreateTenant(string name)
        {
            using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: true))
            {
                var tenant = await _tenantManager.CreateAsync(name);

                await _abpTenantRepository.InsertAsync(tenant);

                var qaTenant = new QaTenant(GuidGenerator.Create(), name)
                {
                    AbpTenantId = tenant.Id
                };
                await _qaTenantRepository.InsertAsync(qaTenant);

                await uow.CompleteAsync();

                return(ObjectMapper.Map <Tenant, TenantDto>(tenant));
            }
        }
Exemplo n.º 30
0
        public virtual async Task <MenuItemDto> CreateAsync(MenuItemCreateInput input)
        {
            var menuItem = new MenuItem(
                GuidGenerator.Create(),
                input.DisplayName,
                input.Url.IsNullOrEmpty() ? "#" : input.Url,
                input.IsActive,
                input.ParentId,
                input.Icon,
                input.Order,
                input.Target,
                input.ElementId,
                input.CssClass
                );

            await MenuItemRepository.InsertAsync(menuItem);

            return(ObjectMapper.Map <MenuItem, MenuItemDto>(menuItem));
        }