Exemple #1
0
        /// <summary>
        /// 构造函数
        /// </summary>
        static AppDbContextBuilder()
        {
            // 判断是否是 Web 环境
            IsWebEnvironment = HttpContextUtility.GetCurrentHttpContext() != null;

            // 扫描程序集,获取数据库实体相关类型
            EntityCorrelationTypes = App.CanBeScanTypes.Where(t => (typeof(IPrivateEntity).IsAssignableFrom(t) || typeof(IPrivateModelBuilder).IsAssignableFrom(t)) &&
                                                              t.IsClass && !t.IsAbstract && !t.IsGenericType && !t.IsInterface && !t.IsDefined(typeof(NonAutomaticAttribute), true))
                                     .ToList();

            if (EntityCorrelationTypes.Count > 0)
            {
                DbContextLocatorCorrelationTypes = new ConcurrentDictionary <Type, DbContextCorrelationType>();

                // 获取模型构建器 Entity<T> 方法
                ModelBuildEntityMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(u => u.Name == nameof(ModelBuilder.Entity) && u.GetParameters().Length == 0);
            }

            // 查找所有数据库函数,必须是公开静态方法,且所在父类也必须是公开静态方法
            DbFunctionMethods = App.CanBeScanTypes
                                .Where(t => t.IsAbstract && t.IsSealed && t.IsClass && !t.IsDefined(typeof(NonAutomaticAttribute), true))
                                .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m => !m.IsDefined(typeof(SkipScanAttribute), false) && m.IsDefined(typeof(QueryableFunctionAttribute), true))).ToList();
        }
Exemple #2
0
 /// <summary>
 /// 默认获取Token的方法
 /// </summary>
 /// <returns></returns>
 protected virtual async Task <string> GetTokenDefaultFunc()
 {
     return(await HttpContextUtility.GetCurrentHttpContext().GetTokenAsync("access_token"));
 }
Exemple #3
0
        public async Task <AppSrvResult <UserValidateDto> > LoginAsync(UserLoginDto inputDto)
        {
            var user = await _userRepository.FetchAsync(x => new
            {
                x.Password
                ,
                x.Salt
                ,
                x.Status
                ,
                UserValidateInfo = new UserValidateDto
                {
                    Account = x.Account
                    ,
                    Email = x.Email
                    ,
                    Id = x.Id
                    ,
                    Name = x.Name
                    ,
                    RoleIds = x.RoleIds
                }
            }
                                                        , x => x.Account == inputDto.Account);

            if (user == null)
            {
                return(Problem(HttpStatusCode.NotFound, "用户名或密码错误"));
            }

            dynamic log = new ExpandoObject();

            log.Account    = inputDto.Account;
            log.CreateTime = DateTime.Now;
            var httpContext = HttpContextUtility.GetCurrentHttpContext();

            log.Device          = httpContext.Request.Headers["device"].FirstOrDefault() ?? "web";
            log.RemoteIpAddress = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            log.Succeed         = false;
            log.UserId          = user.UserValidateInfo.Id;
            log.UserName        = user.UserValidateInfo.Name;

            if (user.Status != 1)
            {
                var problem = Problem(HttpStatusCode.TooManyRequests, "账号已锁定");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status;
                _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                return(problem);
            }

            //var logins = await _loginLogRepository.SelectAsync(5, x => new { x.Id, x.Succeed,x.CreateTime }, x => x.UserId == user.Id, x => x.Id, false);
            //var failLoginCount = logins.Count(x => x.Succeed == false);

            var failLoginCount = 2;

            if (failLoginCount == 5)
            {
                var problem = Problem(HttpStatusCode.TooManyRequests, "连续登录失败次数超过5次,账号已锁定");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status;
                await _userRepository.UpdateAsync(new SysUser()
                {
                    Id = user.UserValidateInfo.Id, Status = 2
                }, UpdatingProps <SysUser>(x => x.Status));

                _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                return(problem);
            }

            if (HashHelper.GetHashedString(HashType.MD5, inputDto.Password, user.Salt) != user.Password)
            {
                var problem = Problem(HttpStatusCode.BadRequest, "用户名或密码错误");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status;
                _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                return(problem);
            }

            if (user.UserValidateInfo.RoleIds.IsNullOrEmpty())
            {
                var problem = Problem(HttpStatusCode.Forbidden, "未分配任务角色,请联系管理员");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status;
                _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                return(problem);
            }

            log.Message    = "登录成功";
            log.StatusCode = (int)HttpStatusCode.Created;
            log.Succeed    = true;
            _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);

            return(user.UserValidateInfo);
        }
Exemple #4
0
        public async Task <AppSrvResult <UserValidateDto> > LoginAsync(UserLoginDto input)
        {
            var bloomFilterAccount = _bloomFilterFactory.GetBloomFilter(nameof(BloomFilterAccount));
            var exists             = await bloomFilterAccount.ExistsAsync(input.Account.ToLower());

            if (!exists)
            {
                return(Problem(HttpStatusCode.BadRequest, "用户名或密码错误"));
            }

            var user = await _userRepository.FetchAsync(x => new
            {
                x.Id,
                x.Account,
                x.Password,
                x.Salt,
                x.Status,
                x.Email,
                x.Name,
                x.RoleIds
            }, x => x.Account == input.Account);

            if (user == null)
            {
                return(Problem(HttpStatusCode.BadRequest, "用户名或密码错误"));
            }

            var httpContext   = HttpContextUtility.GetCurrentHttpContext();
            var channelWriter = ChannelHelper <LoginLog> .Instance.Writer;
            var log           = new LoginLog
            {
                Account         = input.Account,
                Succeed         = false,
                UserId          = user.Id,
                UserName        = user.Name,
                CreateTime      = DateTime.Now,
                Device          = httpContext.Request.Headers["device"].FirstOrDefault() ?? "web",
                RemoteIpAddress = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString()
            };

            if (user.Status != 1)
            {
                var problem = Problem(HttpStatusCode.TooManyRequests, "账号已锁定");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                return(problem);
            }

            //var logins = await _loginLogRepository.SelectAsync(5, x => new { x.Id, x.Succeed,x.CreateTime }, x => x.UserId == user.Id, x => x.Id, false);
            //var failLoginCount = logins.Count(x => x.Succeed == false);
            var failLoginCount = 2;

            if (failLoginCount == 5)
            {
                var problem = Problem(HttpStatusCode.TooManyRequests, "连续登录失败次数超过5次,账号已锁定");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                await _cacheService.RemoveCachesAsync(async (cancellToken) =>
                {
                    await _userRepository.UpdateAsync(new SysUser()
                    {
                        Id = user.Id, Status = 1
                    }, UpdatingProps <SysUser>(x => x.Status), cancellToken);
                }, _cacheService.ConcatCacheKey(CachingConsts.UserValidateInfoKeyPrefix, user.Id.ToString()));

                return(problem);
            }

            if (HashHelper.GetHashedString(HashType.MD5, input.Password, user.Salt) != user.Password)
            {
                var problem = Problem(HttpStatusCode.BadRequest, "用户名或密码错误");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                return(problem);
            }

            if (user.RoleIds.IsNullOrEmpty())
            {
                var problem = Problem(HttpStatusCode.Forbidden, "未分配任务角色,请联系管理员");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                return(problem);
            }

            log.Message    = "登录成功";
            log.StatusCode = (int)HttpStatusCode.Created;
            log.Succeed    = true;
            await channelWriter.WriteAsync(log);

            var userValidteInfo = new UserValidateDto
            {
                Id                = user.Id,
                Account           = user.Account,
                RoleIds           = user.RoleIds,
                Status            = user.Status,
                Name              = user.Name,
                ValidationVersion = HashHelper.GetHashedString(HashType.MD5, user.Account + user.Password)
            };

            return(userValidteInfo);
        }
Exemple #5
0
 /// <summary>
 /// 获取请求生命周期的服务
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static object GetRequiredService(Type type)
 {
     return(HttpContextUtility.GetCurrentHttpContext()?.RequestServices?.GetRequiredService(type));
 }
 /// <summary>
 /// 解析服务
 /// </summary>
 /// <typeparam name="TService"></typeparam>
 /// <returns></returns>
 public static TService GetRequiredServiceByObj <TService>(this object obj)
     where TService : class
 {
     return(HttpContextUtility.GetCurrentHttpContext()?.RequestServices?.GetRequiredService <TService>());
 }
Exemple #7
0
        public async Task <UserValidateDto> Login(UserValidateInputDto inputDto)
        {
            //var user4 = _userRepository.GetAll<SysMenu>().FirstOrDefault();
            //var user0 = _rsp.GetAll<SysUser>().FirstOrDefault();
            var user = await _userRepository.FetchAsync(x => new { x.Password, x.Salt, x.Name, x.Email, x.RoleId, x.Account, x.ID, x.Status }, x => x.Account == inputDto.Account);

            dynamic log = new ExpandoObject();

            log.ID         = IdGenerater.GetNextId(IdGenerater.DatacenterId, IdGenerater.WorkerId);
            log.Account    = inputDto.Account;
            log.CreateTime = DateTime.Now;
            var httpContext = HttpContextUtility.GetCurrentHttpContext();

            log.Device          = httpContext.Request.Headers["device"].ToString() ?? "web";
            log.RemoteIpAddress = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            log.Message         = string.Empty;
            log.Succeed         = false;
            log.UserId          = user?.ID;
            log.UserName        = user?.Name;

            if (user == null)
            {
                throw new BusinessException(new ErrorModel(HttpStatusCode.NotFound, "用户名或密码错误"));
            }
            else
            {
                if (user.Status != 1)
                {
                    var errorModel = new ErrorModel(HttpStatusCode.TooManyRequests, "账号已锁定");
                    log.Message = errorModel.ToString();
                    _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                    throw new BusinessException(errorModel);
                }

                //var logins = await _loginLogRepository.SelectAsync(5, x => new { x.ID, x.Succeed,x.CreateTime }, x => x.UserId == user.ID, x => x.ID, false);
                //var failLoginCount = logins.Count(x => x.Succeed == false);

                var failLoginCount = 2;

                if (failLoginCount == 5)
                {
                    var errorModel = new ErrorModel(HttpStatusCode.TooManyRequests, "连续登录失败次数超过5次,账号已锁定");
                    log.Message = errorModel.ToString();
                    await _userRepository.UpdateAsync(new SysUser()
                    {
                        ID = user.ID, Status = 2
                    }, x => x.Status);

                    _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                    throw new BusinessException(errorModel);
                }

                if (HashHelper.GetHashedString(HashType.MD5, inputDto.Password, user.Salt) != user.Password)
                {
                    var errorModel = new ErrorModel(HttpStatusCode.NotFound, "用户名或密码错误");
                    log.Message = errorModel.ToString();
                    _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                    throw new BusinessException(errorModel);
                }

                if (user.RoleId.IsNullOrEmpty())
                {
                    var errorModel = new ErrorModel(HttpStatusCode.Forbidden, "未分配任务角色,请联系管理员");
                    log.Message = errorModel.ToString();
                    _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
                    throw new BusinessException(errorModel);
                }
            }

            log.Message = "登录成功";
            log.Succeed = true;
            _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log);
            return(_mapper.Map <UserValidateDto>(user));
        }