Exemplo n.º 1
0
        /// <summary>
        /// Delete address
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <ResultModel> DeleteAddressAsync(Guid?id)
        {
            var resultModel = new ResultModel();

            if (!id.HasValue)
            {
                return(new InvalidParametersResultModel <object>().ToBase());
            }

            var currentAddress = await _context.Addresses.FindAsync(id.Value);

            if (currentAddress == null)
            {
                resultModel.Errors.Add(new ErrorModel(string.Empty, "Address not found"));
                return(resultModel);
            }
            _context.Addresses.Remove(currentAddress);
            var dbResult = await _context.PushAsync();

            return(dbResult);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Add new country
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual async Task <ResultModel> AddNewCountryAsync(AddCountryViewModel model)
        {
            if (model == null)
            {
                return(new InvalidParametersResultModel());
            }
            await _context.Countries.AddAsync(model.Adapt <Country>());

            return(await _context.PushAsync());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Install gear settings
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual async Task <ResultModel> InstallAsync(SetupModel model)
        {
            var response = new ResultModel();
            var settings = GearWebApplication.Settings(_hostingEnvironment);

            TableQueryBuilder instance = null;

            switch (model.DataBaseType)
            {
            case DbProviderType.MsSqlServer:
                instance = new MsSqlTableQueryBuilder();
                settings.ConnectionStrings.Provider = DbProvider.SqlServer;
                break;

            case DbProviderType.PostgreSql:
                instance = new NpgTableQueryBuilder();
                settings.ConnectionStrings.Provider = DbProvider.PostgreSQL;
                break;
            }

            if (instance == null)
            {
                response.Errors.Add(new ErrorModel(string.Empty, "No provider registered"));
                return(response);
            }

            var(isConnected, error) = instance.IsSqlServerConnected(model.DatabaseConnectionString);
            if (!isConnected)
            {
                response.Errors.Add(new ErrorModel(string.Empty, error));
                return(response);
            }

            settings.ConnectionStrings.ConnectionString = model.DatabaseConnectionString;

            var tenantMachineName = TenantUtils.GetTenantMachineName(model.Organization.Name);

            if (string.IsNullOrEmpty(tenantMachineName))
            {
                response.Errors.Add(new ErrorModel(string.Empty, "Invalid name for organization"));
                return(response);
            }
            settings.IsConfigured = true;
            settings.SystemConfig.MachineIdentifier = $"_{tenantMachineName}_";
            var result = JsonConvert.SerializeObject(settings, Formatting.Indented);

            GearWebApplication.InitModulesMigrations();
            await System.IO.File.WriteAllTextAsync(ResourceProvider.AppSettingsFilepath(_hostingEnvironment), result);

            await _permissionService.SetOrResetPermissionsOnCacheAsync();

            var tenant =
                await _applicationDbContext.Tenants.FirstOrDefaultAsync(x => x.MachineName == tenantMachineName || x.Id == GearSettings.TenantId);

            if (tenant == null)
            {
                response.Errors.Add(new ErrorModel(string.Empty, "Something went wrong"));
                return(response);
            }

            tenant.Name    = model.Organization.Name;
            tenant.SiteWeb = model.Organization.SiteWeb;
            _applicationDbContext.Tenants.Update(tenant);

            //Set user settings
            var superUser = await _signInManager.UserManager.Users.FirstOrDefaultAsync();

            if (superUser != null)
            {
                superUser.UserName      = model.SysAdminProfile.UserName;
                superUser.Email         = model.SysAdminProfile.Email;
                superUser.UserFirstName = model.SysAdminProfile.FirstName;
                superUser.UserLastName  = model.SysAdminProfile.LastName;

                var hasher         = new PasswordHasher <GearUser>();
                var hashedPassword = hasher.HashPassword(superUser, model.SysAdminProfile.Password);
                superUser.PasswordHash = hashedPassword;
                await _signInManager.UserManager.UpdateAsync(superUser);
            }

            var contextRequest = await _applicationDbContext.PushAsync();

            if (!contextRequest.IsSuccess)
            {
                return(contextRequest);
            }

            GearApplication.BackgroundTaskQueue.PushBackgroundWorkItemInQueue(async x =>
            {
                var service = x.InjectService <IDynamicService>();
                //Register in memory types
                await service.RegisterInMemoryDynamicTypesAsync();
            });

            //Send welcome message to user
            await _notify.SendNotificationAsync(new List <Guid>
            {
                superUser?.Id.ToGuid() ?? Guid.Empty
            },
                                                new Notification
            {
                Subject            = $"Welcome to Gear App {model.SysAdminProfile.FirstName} {model.SysAdminProfile.LastName}",
                Content            = "The GEAR app is an integration system with your company's business, it has the skills to develop new applications, and allows you to create from the visual environment.",
                NotificationTypeId = NotificationType.Info
            });

            //sign in user
            await _signInManager.PasswordSignInAsync(superUser, model.SysAdminProfile.Password, true, false);

            response.IsSuccess = true;
            GearApplication.AppState.InstallOnProgress = false;
            GearApplication.AppState.Installed         = true;
            GearApplication.BackgroundTaskQueue.AddToExecutePendingBackgroundWorkItems();
            return(response);
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Create(CreateUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Roles = await GetRoleSelectListItemAsync();

                model.Tenants = await GetTenantsSelectListItemAsync();

                return(View(model));
            }

            var user = new GearUser
            {
                UserName            = model.UserName,
                Email               = model.Email,
                Created             = DateTime.Now,
                Changed             = DateTime.Now,
                IsDeleted           = model.IsDeleted,
                Author              = User.Identity.Name,
                AuthenticationType  = model.AuthenticationType,
                IsEditable          = true,
                TenantId            = model.TenantId,
                LastPasswordChanged = DateTime.Now,
                FirstName           = model.FirstName,
                LastName            = model.LastName,
                Birthday            = model.Birthday ?? DateTime.MinValue,
                AboutMe             = model.AboutMe,
            };

            if (model.UserPhoto != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await model.UserPhoto.CopyToAsync(memoryStream);

                    user.UserPhoto = memoryStream.ToArray();
                }
            }

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

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }

                model.Roles = await GetRoleSelectListItemAsync();

                model.Tenants = await GetTenantsSelectListItemAsync();

                return(View(model));
            }

            Logger.LogInformation("User {0} created successfully", user.UserName);

            if (model.SelectedRoleId != null && model.SelectedRoleId.Any())
            {
                var rolesNameList = await _roleManager.Roles.Where(x => model.SelectedRoleId.Contains(x.Id))
                                    .Select(x => x.Name).ToListAsync();

                var roleAddResult = await _userManager.AddToRolesAsync(user, rolesNameList);

                if (!roleAddResult.Succeeded)
                {
                    foreach (var error in roleAddResult.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }

                    model.Roles = await GetRoleSelectListItemAsync();

                    model.Tenants = await GetTenantsSelectListItemAsync();

                    return(View(model));
                }
            }

            var dbResult = await _identityContext.PushAsync();

            if (!dbResult.IsSuccess)
            {
                ModelState.AppendResultModelErrors(dbResult.Errors);
                model.Roles = await GetRoleSelectListItemAsync();

                model.Tenants = await GetTenantsSelectListItemAsync();

                return(View(model));
            }

            IdentityEvents.Users.UserCreated(new UserCreatedEventArgs
            {
                Email    = user.Email,
                UserName = user.UserName,
                UserId   = user.Id
            });

            return(RedirectToAction(nameof(Index), "Users"));
        }