Ejemplo n.º 1
0
        public async Task LogoutAsync()
        {
            var userCode = _workContext.GetUserCode();

            if (userCode == Guid.Empty)
            {
                return;
            }

            var userAgent       = NetworkExtension.GetUserAgent(_httpContextAccessor.HttpContext.Request);
            var localIpAddress  = NetworkExtension.GetLocalIpAddress(_httpContextAccessor.HttpContext.Request).ToString();
            var remoteIpAddress = NetworkExtension.GetRemoteIpAddress(_httpContextAccessor.HttpContext.Request).ToString();

            var repoToken = _uow.GetRepository <ITokenRepository>();
            var token     = await repoToken.GetByUserAsync(userCode, userAgent, localIpAddress, remoteIpAddress);

            if (token == null)
            {
                return;
            }

            await _cache.RemoveAsync($"TokenInfos:{token.Id}");

            repoToken.Delete(token);
            await _uow.CommitAsync();
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> PostAsync([FromBody] RoleModel model)
        {
            var repoRole = _uow.GetRepository <IRoleRepository>();

            //Create role
            var idRole = Guid.NewGuid();
            await repoRole.InsertAsync(new Role
            {
                CreatedAt    = DateTime.Now,
                CreatedAtUtc = DateTime.UtcNow,
                CreatedBy    = _workContext.GetUserCode(),
                Id           = idRole,
                TenantCode   = await _workContext.GetTenantCodeAsync(),
                Name         = model.Name,
            });

            //Create claim
            var repoRoleClaim = _uow.GetRepository <IPermissionRepository>();
            await repoRoleClaim.InsertRoleClaimsAsync(model.Claims.Select(x => new IdentityRoleClaim <Guid>
            {
                RoleId = idRole,
                ClaimType = x.Key,
                ClaimValue = x.Value
            }).ToList());

            await _uow.CommitAsync();

            return(Ok());
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> UploadAsync(IFormFile formFile, [FromRoute] bool isInvoice)
        {
            if (formFile.Length <= 0)
            {
                throw new Exception("File không có dữ liệu");
            }

            var tenantCode = await _workContext.GetTenantCodeAsync();

            var repoTenantInfo = _uow.GetRepository <ITenantRepository>();
            var tenantInfo     = await repoTenantInfo.GetInfoByCodeAsync(tenantCode);

            var splited      = formFile.FileName.Split('.');
            var fileNamePhys = $"{tenantInfo.TaxCode}-{Guid.NewGuid()}.{splited.Last()}";

            fileNamePhys = await _fileService.UploadAsync(isInvoice, formFile, fileNamePhys);

            //lưu file vào db

            var repoFile = _uow.GetRepository <IFileRepository>();
            var file     = new Jarvis.Core.Database.Poco.File
            {
                ContentType  = formFile.ContentType,
                CreatedAt    = DateTime.Now,
                CreatedAtUtc = DateTime.UtcNow,
                CreatedBy    = _workContext.GetUserCode(),
                FileName     = formFile.FileName,
                Id           = Guid.NewGuid(),
                Name         = fileNamePhys,
                TenantCode   = await _workContext.GetTenantCodeAsync(),
                Length       = formFile.Length
            };

            await repoFile.InsertAsync(file);

            await _uow.CommitAsync();

            return(Ok(new
            {
                file.Id,
                FileNamePhys = file.Name
            }));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> PostAsync([FromBody] OrganizationUnitModel model)
        {
            var context = await _workcontext.GetContextAsync(nameof(CorePolicy.OrganizationPolicy.OrganizationUnit_Create));

            var repo = _uow.GetRepository <IOrganizationUnitRepository>();
            await repo.InsertAsync(new OrganizationUnit
            {
                Description  = model.Description,
                Code         = Guid.NewGuid(),
                TenantCode   = await _workcontext.GetTenantCodeAsync(),
                FullName     = model.Name,
                CreatedAt    = DateTime.Now,
                CreatedAtUtc = DateTime.UtcNow,
                CreatedBy    = _workcontext.GetUserCode()
            });

            await _uow.CommitAsync();

            return(Ok());
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> PostAsync([FromBody] LabelModel model)
        {
            var context = await _workcontext.GetContextAsync(nameof(CorePolicy.LabelPolicy.Label_Create));

            var repo = _uow.GetRepository <ILabelRepository>();
            await repo.InsertAsync(new Label
            {
                Color        = model.Color,
                Description  = model.Description,
                Icon         = model.Icon,
                Code         = Guid.NewGuid(),
                TenantCode   = await _workcontext.GetTenantCodeAsync(),
                Name         = model.Name,
                CreatedAt    = DateTime.Now,
                CreatedAtUtc = DateTime.UtcNow,
                CreatedBy    = _workcontext.GetUserCode()
            });

            await _uow.CommitAsync();

            return(Ok());
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> PostAsync([FromBody] CreateTenantCommand model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var currentUser   = _workContext.GetUserCode();
            var currentTenant = await _workContext.GetCurrentTenantAsync();

            var repoTenant = _uow.GetRepository <ITenantRepository>();

            if (await repoTenant.AnyByNameAsync(model.Info.TaxCode))
            {
                throw new Exception("Mã số thuế đã bị trùng");
            }

            if (await repoTenant.AnyByHostNameAsync(model.HostName))
            {
                throw new Exception("Tên miền đã bị trùng");
            }

            //check tên tk có bị trùng với tk root của chi nhánh không
            //(tk này đặc biệt không được gán nhóm quyền nào mà chỉ có quyền là adminTenant)
            var userRootTenant = "root";

            if (model.User.UserName.ToUpper() == userRootTenant.ToUpper())
            {
                throw new Exception("Tên đăng nhập không hợp lệ. Vui lòng nhập tên đăng nhập không phải là admin!");
            }

            //Nếu ko nhập pasword sẽ tự động random
            var isRandomPassword = false;

            if (string.IsNullOrEmpty(model.User.Password))
            {
                model.User.Password = RandomExtension.Random(10);
                isRandomPassword    = true;
            }

            //insert tenant, tenantInfo
            var tenantInfo = await InsertTenant(model, currentUser, currentTenant);

            //Insert user root của tenant
            var passwordRoot = RandomExtension.Random(10);
            var rootUser     = await InsertRootTenantUserAsync(model, userRootTenant, passwordRoot, currentUser, tenantInfo.Code);

            //insert quyền  mặc định
            var adminRole = await AddDefaultRolesAsync(tenantInfo, currentUser);

            //Insert user của chi nhánh mà nsd nhập và gán quyền admin mặc định
            var adminUser = await InsertAdminTenantUserAsync(model, currentUser, tenantInfo.Code, adminRole.Id);

            await _uow.CommitAsync();

            ////gửi mail thông báo tài khoản root mật khẩu
            //var db = _redis.GetDatabase();
            //await db.ListLeftPushAsync(KeyQueueBackground.SendMail, JsonConvert.SerializeObject(new
            //{
            //    Action = "SendAccountTenant",
            //    Datas = JsonConvert.SerializeObject(new
            //    {
            //        TenantCode = currentTenant.Code,
            //        IdUser = rootUser.Id,
            //        Password = passwordRoot,
            //    })
            //}));

            ////gửi mail thông báo tài khoản admin mật khẩu nếu là password tự động
            if (isRandomPassword)
            {
                //    await db.ListLeftPushAsync(KeyQueueBackground.SendMail, JsonConvert.SerializeObject(new
                //    {
                //        Action = "SendAccountTenant",
                //        Datas = JsonConvert.SerializeObject(new
                //        {
                //            TenantCode = currentTenant.Code,
                //            IdUser = adminUser.Id,
                //            Password = model.User.Password,
                //        })
                //    }));
            }

            return(Ok(new
            {
                TenantCode = tenantInfo.Code,
            }));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> PostAsync([FromRoute] string group, [FromBody] List <SettingModel> command)
        {
            var tenantCode = await _workContext.GetTenantCodeAsync();

            var usercode = _workContext.GetUserCode();

            //phân biệt ra sửa và thêm
            //Sửa
            var repo     = _uowCore.GetRepository <ISettingRepository>();
            var entities = await repo.GetByGroupAsync(tenantCode, group);

            var entityByKey = entities.GroupBy(x => x.Key, x => x)
                              .ToDictionary(x => x.Key, x => x.FirstOrDefault());

            var defaultSettings = _settingService.GetDefaultSettings();

            var inserts = new List <Setting>();
            var updates = new List <Setting>();

            foreach (var item in command)
            {
                if (entityByKey.ContainsKey(item.Key))
                {
                    //sửa
                    var setting = entityByKey[item.Key];

                    setting.Value        = item.Value;
                    setting.UpdatedAt    = DateTime.Now;
                    setting.UpdatedAtUtc = DateTime.UtcNow;
                    setting.UpdatedBy    = usercode;

                    updates.Add(setting);
                }
                else
                {
                    //thêm
                    //Setting ko có trong default => bỏ qua
                    var defaultSetting = defaultSettings.FirstOrDefault(x => x.Key == item.Key);
                    if (defaultSetting == null)
                    {
                        continue;
                    }

                    var setting = new Setting
                    {
                        Code         = Guid.NewGuid(),
                        Group        = group,
                        Key          = item.Key,
                        Name         = defaultSetting.Name,
                        Value        = item.Value,
                        Options      = defaultSetting.Options,
                        Type         = defaultSetting.Type,
                        CreatedAt    = DateTime.Now,
                        CreatedAtUtc = DateTime.UtcNow,
                        CreatedBy    = usercode,
                        Description  = defaultSetting.Description,
                        TenantCode   = tenantCode,
                    };
                    inserts.Add(setting);
                }
            }

            var hasChange = false;

            if (inserts.Count > 0)
            {
                await repo.InsertsAsync(inserts);

                hasChange = true;
            }

            if (updates.Count > 0)
            {
                repo.Updates(updates);
                hasChange = true;
            }

            if (hasChange)
            {
                await _uowCore.CommitAsync();
            }

            return(Ok());
        }