Пример #1
0
        public async Task <IActionResult> PutAsync([FromBody] TenantInfoModel command)
        {
            var idTenant = await _workContext.GetTenantCodeAsync();

            var repoTenant = _uow.GetRepository <ITenantRepository>();
            var info       = await repoTenant.GetInfoByCodeAsync(idTenant);

            info.City         = command.City;
            info.District     = command.District;
            info.LegalName    = command.LegalName;
            info.Fax          = command.Fax;
            info.Emails       = command.Emails;
            info.BusinessType = command.BusinessType;

            if (command.Metadata != null && command.Metadata.Count != 0)
            {
                info.Metadata = JsonConvert.SerializeObject(command.Metadata);
            }

            repoTenant.UpdateInfo(info);
            await _uow.CommitAsync();

            return(Ok());
        }
Пример #2
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,
            }));
        }
Пример #3
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());
        }
Пример #4
0
        public async Task <TokenModel> LoginAsync(Guid tenantCode, LoginModel model)
        {
            model.UserName = model.UserName.ToUpper();

            var repoUser = _uow.GetRepository <IUserRepository>();
            var user     = await repoUser.FindUserByUsernameAsync(tenantCode, model.UserName);

            if (user == null)
            {
                throw new Exception("Tài khoản hoặc mật khẩu không đúng");
            }

            var account = await _userManager.FindByIdAsync(user.Id.ToString());

            var result = await _signInManager.CheckPasswordSignInAsync(account, model.Password, true);

            if (result.IsLockedOut)
            {
                throw new Exception("Tài khoản bị khóa");
            }

            if (!result.Succeeded)
            {
                throw new Exception("Tài khoản hoặc mật khẩu không đúng");
            }

            //TODO: Xóa các Token đã hết hạn => Đưa vào BackgroundJob
            //var expired = tokenInfos.Where(x => x.ExpireAtUtc <= DateTime.UtcNow);
            //if (expired.Any())
            //{
            //    repoToken.DeleteRange(expired);
            //    _uowCore.SaveChanges();
            //}

            SessionModel session;
            var          token = await GetTokenAsync(user.Id);

            if (token != null)
            {
                session = JsonConvert.DeserializeObject <SessionModel>(token.Metadata);
            }
            else
            {
                var expireIn    = TimeSpan.FromDays(1);
                var tokenCode   = Guid.NewGuid();
                var expireAt    = DateTime.Now.Add(expireIn);
                var expireAtUtc = DateTime.UtcNow.Add(expireIn);
                var claims      = new List <Claim>();
                claims.Add(new Claim(JwtRegisteredClaimNames.Jti, tokenCode.ToString()));
                claims.Add(new Claim(ClaimTypes.Sid, user.Id.ToString()));
                claims.Add(new Claim(ClaimTypes.GroupSid, tenantCode.ToString()));

                var jwt = new JwtSecurityToken(
                    claims: claims,
                    expires: expireAt,
                    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_options.SecretKey)), SecurityAlgorithms.HmacSha256));

                var accessToken = new JwtSecurityTokenHandler().WriteToken(jwt);

                session = new SessionModel
                {
                    IdUser      = user.Id,
                    UserName    = user.UserName,
                    PhoneNumber = user.PhoneNumber,
                    Email       = user.Email,
                    CreatedAt   = user.CreatedAt,
                    UserInfo    = await GetInfoAsync(user.Id),
                    TenantInfo  = await GetTenantInfoAsync(user.TenantCode),
                    Claims      = await GetClaimsAsync(user.Id)
                };

                token = new TokenInfo
                {
                    AccessToken     = accessToken,
                    CreatedAt       = DateTime.Now,
                    CreatedAtUtc    = DateTime.UtcNow,
                    ExpireAt        = expireAt,
                    ExpireAtUtc     = expireAtUtc,
                    Code            = tokenCode,
                    IdUser          = user.Id,
                    LocalIpAddress  = NetworkExtension.GetLocalIpAddress(_httpContextAccessor.HttpContext.Request).ToString(),
                    PublicIpAddress = NetworkExtension.GetRemoteIpAddress(_httpContextAccessor.HttpContext.Request).ToString(),
                    Metadata        = JsonConvert.SerializeObject(session),
                    RefreshToken    = null,
                    Source          = "Application",
                    TimeToLife      = expireIn.TotalMinutes,
                    UserAgent       = NetworkExtension.GetUserAgent(_httpContextAccessor.HttpContext.Request),
                    TenantCode      = tenantCode
                };

                var repoToken = _uow.GetRepository <ITokenRepository>();
                await repoToken.InsertAsync(token);

                await _uow.CommitAsync();
            }

            return(new TokenModel
            {
                AccessToken = token.AccessToken,
                ExpireIn = (token.ExpireAt - DateTime.Now).TotalMinutes,
                ExpireAt = token.ExpireAt,
                Timezone = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).TotalHours,
                //RefreshToken = account.SecurityStamp,
            });
        }
Пример #5
0
        public async Task <Guid> SaveFileXmlAsync(Guid CreatedBy, Guid tenantCode, string xml, bool isDefault, string sellerTaxCode, string templateNo, string serialNo, int number)
        {
            var folderPath = await GetFilePath(isDefault, DateTime.UtcNow);

            var fileNamePhys = $"{sellerTaxCode}_{templateNo}_{serialNo}_{number}_{DateTime.Now.Ticks}.xml".Replace("/", "-");
            var filePath     = Path.Combine(folderPath, fileNamePhys);

            //Nếu đã có file trùng tên thì đổi tên file hiện tại
            if (File.Exists(filePath))
            {
                var matches = Regex.Matches(fileNamePhys, @"\((\d+)\)");
                if (matches.Count == 0) //Trùng lần đầu tiên
                {
                    //Thêm (x) ở đuôi file
                    var splited   = fileNamePhys.Split('.');
                    var extension = splited[splited.Length - 1];
                    fileNamePhys = $"{string.Join(".", splited.Take(splited.Length - 1))}_(1).{extension}";
                }
                else //Đã bị đổi tên
                {
                    //Match cuối là thứ tự file bị trùng
                    var match = matches[matches.Count - 1];

                    //Lấy số thứ tự
                    var str   = match.Value.Substring(1, match.Value.Length - 2);
                    var index = int.Parse(str);
                    index++;
                    fileNamePhys = fileNamePhys.Remove(match.Index, match.Length).Insert(match.Index, $"({index})");
                }
            }

            //Upload file với tên mới
            filePath = Path.Combine(folderPath, fileNamePhys);

            var bytes = Encoding.UTF8.GetBytes(xml);

            if (bytes.Length > 0)
            {
                File.WriteAllBytes(filePath, bytes);
            }

            //lưu vào db
            var repoFile = _uowCore.GetRepository <IFileRepository>();
            var idFile   = Guid.NewGuid();

            await repoFile.InsertAsync(new Database.Poco.File
            {
                ContentType  = ContentType.Xml,
                CreatedAt    = DateTime.Now,
                CreatedAtUtc = DateTime.UtcNow,
                FileName     = fileNamePhys,
                Id           = idFile,
                Length       = bytes.Length,
                Name         = fileNamePhys,
                TenantCode   = tenantCode,
                CreatedBy    = CreatedBy
            });

            await _uowCore.CommitAsync();

            return(idFile);
        }