/// <summary>
        ///
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task <ActionObjectResult <bool> > ValidSmsAsync(string phone, string code)
        {
            var uniqueKey = GetSmsKey(phone);
            var smsCache  = await _redisCache.GetAsync <SmsCache>(uniqueKey);

            if (smsCache == null)
            {
                return(ActionObject.Ok(false, -1, "未发送验证码或验证码已超时"));
            }

            if (smsCache.ValidateCount >= 3)  //0 1  2
            {
                return(ActionObject.Ok(false, -1, "输入错误的次数超过3次,请重新获取验证码"));
            }
            if (code == smsCache.Code)
            {
                await _redisCache.KeyDeleteAsync(uniqueKey);

                return(ActionObject.Ok(true));
            }

            var timeSpan = smsCache.StartTime.AddMinutes(smsCache.ExpiresMinute) - DateTime.Now;

            if (timeSpan.TotalSeconds <= 0)
            {
                return(ActionObject.Ok(false, -1, "未发送验证码或验证码已超时"));
            }
            smsCache.ValidateCount += 1;   //更新验证次数,不延长时间
            await _redisCache.AddAsync(uniqueKey, smsCache, timeSpan);

            return(ActionObject.Ok(false, -1, "输入验证码不正确"));
        }
        /// <summary>
        ///
        /// </summary>
        public async Task <ActionObjectResult <bool> > SendAsync(string phone, string smsCode, int appId, string content, ValidationType type, string ip, int expiresMinute = 5)
        {
            var uniqueKey = GetSmsKey(phone);

            if (!await CheckOverLimit(phone))
            {
                return(ActionObject.Ok(false, -1, "请求频率过高,请稍后再试"));
            }

            var smsLimit = new SmsCache {
                Code = smsCode, StartTime = DateTime.Now, ValidateCount = 0, ExpiresMinute = expiresMinute
            };

            await _redisCache.AddAsync(uniqueKey, smsLimit, new TimeSpan(0, 0, expiresMinute * 60));

            if (!_appSettings.DeveloperMode)
            {
                var(code, msg, msgId) = await _passportClient.SendSms(phone, content, _smsServerOptions.SignatureCode);

                _backgroundRunService.Transfer <IValidationComponent>(x =>
                                                                      x.SaveLog(appId, content, type, phone, ip, code == "0", smsCode, expiresMinute, msgId, msg));
            }

            return(ActionObject.Ok(true));
        }
Beispiel #3
0
        /// <summary>
        /// 账号密码登录
        /// </summary>
        public async Task <ActionObjectResult <UserEntity> > LoginByPasswordAsync(string phone, string cipherPass)
        {
            var password = _encryptService.DecryptRsa(cipherPass);

            if (string.IsNullOrEmpty(password))
            {
                return(ActionObject.Ok <UserEntity>(-1, "密码格式不正确"));
            }

            var userEntity = await GetUserByPhoneAsync(phone);

            if (userEntity == null)
            {
                return(ActionObject.Ok <UserEntity>(-1, "用户名或密码不正确"));
            }

            if (userEntity.Enabled == false)
            {
                return(ActionObject.Ok <UserEntity>(-1, "您的账号已被禁用"));
            }

            var lastTypeLoginTime = userEntity.LastTryLoginTime ?? DateTime.Now;

            if (userEntity.Locked && lastTypeLoginTime.AddHours(3) > DateTime.Now)
            {
                return(ActionObject.Ok <UserEntity>(-1, "登录密码出错已达上限将锁定密码3小时,请找回密码后登录,或使用短信登录。"));
            }

            if (_encryptService.EncryptAes(password) != userEntity.Password)
            {
                await SaveErrorLoginInfo(userEntity.Id);

                if (userEntity.LoginErrorCount < 2)
                {
                    return(ActionObject.Ok <UserEntity>(-1, "用户名或密码不正确"));
                }

                var count = 5 - userEntity.LoginErrorCount;
                count = count < 0 ? 0 : count;
                var msg = $"用户名或密码不正确,还有{count}次机会。您还可以:重置登录密码";
                if (count <= 0)
                {
                    msg = "登录密码出错已达上限将锁定密码3小时,请找回密码后登录,或使用短信登录。";
                }
                return(ActionObject.Ok <UserEntity>(-1, msg));
            }

            return(ActionObject.Ok(userEntity));
        }
        /// <summary>
        /// 绑定第三方账号
        /// </summary>
        public async Task <ActionObjectResult> BindExternalUser(int clientId, string userId, string providerKey, string loginProvider, string nickname)
        {
            var externalUsers = await GetExternalUsers(clientId, userId);

            var externalUser = externalUsers.FirstOrDefault(c => c.LoginProvider == loginProvider && c.ClientId == clientId);

            if (externalUser != null)
            {
                return(ActionObject.Ok(20026, "通行证账号已绑定过该类型账号"));
            }

            externalUser = await GetExternalUser(clientId, providerKey);

            if (!string.IsNullOrEmpty(externalUser?.UserId))
            {
                return(ActionObject.Ok(20027, "此用户已绑定过通行证账号"));
            }

            var externalUserEntity = new ExternalUserEntity()
            {
                UserId        = userId,
                ProviderKey   = providerKey,
                LoginProvider = loginProvider,
                Nickname      = nickname,
                ClientId      = clientId,
                CreateDate    = DateTime.Now,
            };

            await _externalUserRepository.InsertAsync(externalUserEntity);

            await _unitOfWork.SaveChangesAsync();

            await _redisCache.KeyDeleteAsync(GetExternalUsersRedisKey(clientId, userId));

            await _redisCache.KeyDeleteAsync(GetExternalUserRedisKey(clientId, providerKey));

            return(ActionObject.Ok());
        }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        public async Task <ActionObjectResult <GrantInfoModel> > GetGrantInfo(string method, string authorization)
        {
            using (var httpRequest = new HttpRequestMessage(HttpMethod.Get, $"/api/apiauth/grantinfo/{_options.ClientId}/{method}"))
            {
                httpRequest.Headers.Add("Authorization", authorization);
                using (var responseMessage = await Client.SendAsync(httpRequest))
                {
                    responseMessage.EnsureSuccessStatusCode();

                    var msg = await responseMessage.Content.ReadAsStringAsync();

                    try
                    {
                        var data = JsonConvert.DeserializeObject <ActionObjectResult <GrantInfoModel> >(msg);
                        return(data);
                    }
                    catch (JsonSerializationException ex)
                    {
                        return(ActionObject.Ok <GrantInfoModel>(-1, ex.Message));
                    }
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// 修改手机号
        /// </summary>
        public async Task <ActionObjectResult> ChangePhoneAsync(string phone, string newPhone)
        {
            if (await ExistPhoneAsync(newPhone))
            {
                return(ActionObject.Ok(20015, "该手机号已经被使用"));
            }

            if (!await ExistPhoneAsync(phone))
            {
                return(ActionObject.Ok(20041, "该用户不存在"));
            }

            await _redisCache.ObjectKeyDeleteAsync(new UserEntity { Phone = phone });

            var userEntity = await _userRepository.Table.FirstOrDefaultAsync(x => x.Phone == phone);

            userEntity.Phone           = newPhone;
            userEntity.LoginErrorCount = 0;
            await _unitOfWork.SaveChangesAsync();

            await _redisCache.ObjectAddAsync(userEntity, TimeSpan.FromDays(15));

            return(ActionObject.Ok());
        }
Beispiel #7
0
 public static OkObjectResult Ok <T>(T data, Pagination pagination, int code = 0, string message = "ok", MessageType messageType = MessageType.Success)
 {
     return(new OkObjectResult(ActionObject.Ok(data, pagination, code, message, messageType)));
 }
Beispiel #8
0
 public static OkObjectResult Ok <T>(T data, int code = 0, string message = "ok", MessageType messageType = MessageType.Success)
 {
     return(data.GetType().Name == typeof(ActionObjectResult <T>).Name ? new OkObjectResult(data) : new OkObjectResult(ActionObject.Ok(data, code, message, messageType)));
 }
Beispiel #9
0
 public static OkObjectResult Ok(int code = 0, string message = "ok")
 {
     return(new OkObjectResult(ActionObject.Ok(code, message)));
 }
Beispiel #10
0
 public static OkObjectResult Ok(string message)
 {
     return(new OkObjectResult(ActionObject.Ok(0, message)));
 }
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            if (!context.HttpContext.User.Identity.IsAuthenticated || !context.Filters.ExistsAuthorizeAttribute())
            {
                await next();

                return;
            }

            var method        = context.GetMethod();
            var authorization = context.GetAuthorization();

            var onClientValidate = _options.OnClientValidate;

            var clientValidate = ClientValidate.None;

            if (context.Filters.OfType <BasicAuthorizeAttribute>().Any())
            {
                clientValidate = context.Filters.OfType <BasicAuthorizeAttribute>().First().ClientValidate;
            }

            if (clientValidate != ClientValidate.None)
            {
                onClientValidate = (clientValidate == ClientValidate.On);
            }

            if (onClientValidate)
            {
                var clientId = context.HttpContext.User.GetClientId();
                if (_options.ClientId != clientId)
                {
                    if (string.IsNullOrWhiteSpace(_options.Authority))
                    {
                        throw new ArgumentNullException(nameof(_options.Authority));
                    }

                    var grantInfoResponse = await _serviceAuthorizeHttpClient.GetGrantInfo(
                        method, authorization);

                    if (grantInfoResponse.Code != 0)
                    {
                        context.Result = new BadRequestObjectResult(ActionObject.Ok(grantInfoResponse.Code, grantInfoResponse.Message));
                        return;
                    }

                    var grantInfo = grantInfoResponse.Data;
                    if (grantInfo == null)
                    {
                        context.Result = new BadRequestObjectResult(ActionObject.Ok(-1, "获取授权信息失败"));
                        return;
                    }

                    if (!grantInfo.Granted)
                    {
                        context.Result = new ObjectResult(ActionObject.Ok(-1, "该资源需要appid拥有授权"))
                        {
                            StatusCode = 403
                        };
                        return;
                    }
                }
            }

            await next();
        }