Ejemplo n.º 1
0
        public Task <(ClaimsPrincipal, JwtSecurityToken)> DecodeJwtToken(string token, CancellationToken cancellationToken = default)
        {
            CheckValue.NotNullOrWhiteSpace(token, "Invalid token");

            var principal = new JwtSecurityTokenHandler()
                            .ValidateToken(token,
                                           new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidIssuer              = _jwtOptions.Issuer,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(_jwtOptions.SecurityKey),
                ValidAudience            = _jwtOptions.Audience,
                ValidAlgorithms          = new List <string>()
                {
                    _jwtOptions.Algorithm
                },
                ValidateAudience = true,
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.FromMinutes(1)
            },
                                           out var validatedToken);

            return(Task.FromResult((principal, validatedToken as JwtSecurityToken)));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 设置token信息
        /// </summary>
        public void SetToken(string tokenInfo, DateTime tokenExpire)
        {
            CheckValue.NotNullOrWhiteSpace(tokenInfo, nameof(tokenInfo));

            TokenInfo       = tokenInfo;
            TokenExpireTime = tokenExpire;
        }
Ejemplo n.º 3
0
        public RefreshToken(string subjectId, ClaimsPrincipal subject)
        {
            CheckValue.NotNullOrWhiteSpace(subjectId, nameof(subjectId));

            SubjectId = subjectId;
            Subject   = subject;
        }
Ejemplo n.º 4
0
        public UserRole(Guid userId, string roleName)
        {
            CheckValue.NotNull(userId, nameof(userId));
            CheckValue.NotNullOrWhiteSpace(roleName, nameof(roleName));

            UserId   = userId;
            RoleName = roleName;
        }
Ejemplo n.º 5
0
        public StepFlyHistory(string userKey, int stepNum)
        {
            CheckValue.NotNullOrWhiteSpace(userKey, nameof(userKey));

            UserKeyInfo = userKey;
            StepNum     = stepNum;
            Source      = (int)StepFlyProviderType.XiaoMi;
        }
Ejemplo n.º 6
0
        public Task <List <FeedBack> > GetUserTodayFeedbacks(string userKey, CancellationToken cancellationToken = default)
        {
            CheckValue.NotNullOrWhiteSpace(userKey, nameof(userKey));
            var nowDate     = DateTime.Now;
            var currentDate = new DateTime(nowDate.Year, nowDate.Month, nowDate.Day);

            return(Task.FromResult(DbSet.Where(s => s.UserKey.Equals(userKey) && (s.CreationTime <= currentDate.AddDays(1) && s.CreationTime >= currentDate)).ToList()));
        }
Ejemplo n.º 7
0
        public async Task <OperateResult> UpdateStepAsync(int stepNum, UpdateStepUser userInfo, CancellationToken cancellationToken = default)
        {
            try
            {
                CheckValue.NotNullOrWhiteSpace(userInfo.UserKeyInfo, "userInfo.UserKeyInfo");

                var user = await _userRepo.FindByUserKeyInfoAsync(userInfo.UserKeyInfo, StepFlyProviderType.XiaoMi) ??
                           throw new SoftlyMiCakeException("在修改步数的时候没有找到对应的用户信息");

                // 刷新Token
                await TryRelogin(user, cancellationToken);

                var httpClient = _httpClientFactory.CreateClient();
                var url        = XiaoMiConfig.GetChangeStepUrl();

                var jsonOptions = new JsonSerializerOptions()
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };
                var content = new StringContent(XiaoMiConfig.GetChangeStepRequestBody(user.UserSystemId, stepNum.ToString()), Encoding.UTF8, "application/x-www-form-urlencoded");
                content.Headers.Add("apptoken", user.TokenInfo);

                using var response = await httpClient.PostAsync(url, content, cancellationToken);

                var responseContent = await response.Content.ReadAsStringAsync();

                _logger.LogInformation(await content.ReadAsStringAsync());
                _logger.LogInformation(responseContent);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "修改步数失败", responseContent));
                }

                using var jsonDoc = JsonDocument.Parse(responseContent);
                var successCode = jsonDoc.RootElement.GetProperty("code").GetRawText();
                if (successCode.Equals("1"))
                {
                    return(OperateResult.Success(HttpStatusCode.OK.ToString(), "修改步数成功", responseContent));
                }

                if (successCode.Equals("0"))
                {
                    return(OperateResult.Failed(null, HttpStatusCode.Unauthorized.ToString(), "修改步数失败,登录信息已经过期"));
                }

                return(OperateResult.Success(HttpStatusCode.OK.ToString(), "修改步数失败", responseContent));
            }
            catch (Exception ex)
            {
                return(OperateResult.Failed(ex, "尝试修改步数时产生错误", ex.Message));
            }
        }
Ejemplo n.º 8
0
        public static StepFlyUser Create(string userKeyInfo, string password, string userSystemId)
        {
            CheckValue.NotNullOrWhiteSpace(userKeyInfo, nameof(userKeyInfo));

            return(new StepFlyUser()
            {
                UserKeyInfo = userKeyInfo,
                Password = password,
                UserSystemId = userSystemId,
                LoginTime = DateTime.Now
            });
        }
Ejemplo n.º 9
0
        public async Task <OperateResult> UpdateStepAsync(int stepNum, UpdateStepUser userInfo, CancellationToken cancellationToken = default)
        {
            try
            {
                CheckValue.NotNullOrWhiteSpace(userInfo.UserKeyInfo, "userInfo.UserKeyInfo");

                var user = await _userRepo.FindByUserKeyInfoAsync(userInfo.UserKeyInfo) ??
                           throw new SoftlyMiCakeException("在修改步数的时候没有找到对应的用户信息");

                var httpClient = _httpClientFactory.CreateClient();
                var url        = GetUpdateStepUrl();

                var jsonOptions = new JsonSerializerOptions()
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };
                var content = new StringContent(JsonSerializer.Serialize(GetUpdateStepModel(stepNum, user), jsonOptions), Encoding.UTF8, "application/json");
                content.Headers.Add("Cookie", user.TokenInfo);

                using var response = await httpClient.PostAsync(url, content, cancellationToken);

                response.EnsureSuccessStatusCode();

                var responseContent = await response.Content.ReadAsStringAsync();

                _logger.LogInformation(await content.ReadAsStringAsync());
                _logger.LogInformation(responseContent);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "修改步数失败", responseContent));
                }

                var lexinResponse = JsonSerializer.Deserialize <LeXinHttpResponse>(responseContent, new JsonSerializerOptions()
                {
                    PropertyNameCaseInsensitive = true
                });
                if (lexinResponse.Code != 200)
                {
                    return(OperateResult.Failed(null, lexinResponse.Code.ToString(), "修改步数失败", lexinResponse.Msg));
                }

                return(OperateResult.Success(HttpStatusCode.OK.ToString(), "修改步数成功", responseContent));
            }
            catch (Exception ex)
            {
                return(OperateResult.Failed(ex, "尝试修改步数时产生错误", ex.Message));
            }
        }
        public async Task <RegisterResultDto> RegisterUser(RegisterWeChatUserDto userDto)
        {
            CheckValue.NotNullOrWhiteSpace(userDto.SessionKey, "SessionKey");

            var weChatSessionInfo = await _weChatSessionStore.GetSessionInfo(userDto.SessionKey) ?? throw new ArgumentException("没有找到匹配的微信密匙信息");

            var newUser = MiCakeApp.User.Create(userDto.Phone, "abc12345", userDto.Name, userDto.Age);

            //可能你还有其它的验证逻辑,比如包括该手机号码是否已经被使用等等。
            //这些领域逻辑可能会被移动至单独的领域服务来处理.

            await _userRepository.AddAsync(newUser);

            await _wechatRepository.AddAsync(new UserWithWechat(newUser.Id, weChatSessionInfo.OpenId));

            return(RegisterResultDto.RegisterSuccess(newUser.Id));
        }
        public async Task <WeChatLoginDto> Login(string key)
        {
            CheckValue.NotNullOrWhiteSpace(key, nameof(key));

            var weChatSessionInfo = await _weChatSessionStore.GetSessionInfo(key) ?? throw new ArgumentException("没有找到匹配的微信密匙信息");

            var anyUser = await _wechatRepository.GetUserIdWithOpenId(weChatSessionInfo.OpenId);

            if (anyUser == default)
            {
                return(WeChatLoginDto.NoUser(key));
            }

            var user = await _userRepository.FindAsync(anyUser);

            var token = _jwtSupporter.CreateToken(user);

            return(new WeChatLoginDto()
            {
                AccessToken = token, HasUser = true, UserInfo = user.Adapt <UserDto>()
            });
        }
Ejemplo n.º 12
0
        public void SetDeviceId(string deviceId)
        {
            CheckValue.NotNullOrWhiteSpace(deviceId, "deviceId");

            DeviceId = deviceId;
        }
Ejemplo n.º 13
0
        public void SetId(string id)
        {
            CheckValue.NotNullOrWhiteSpace(id, "id");

            Id = id;
        }
Ejemplo n.º 14
0
        public void SetUserId(string userId)
        {
            CheckValue.NotNullOrWhiteSpace(userId, "userId");

            UserId = userId;
        }
Ejemplo n.º 15
0
        private async Task <OperateResult> Login(XiaoMiLoginModel loginInfo, StepFlyUser user, CancellationToken cancellationToken)
        {
            try
            {
                CheckValue.NotNullOrWhiteSpace(loginInfo.UserPhone, nameof(loginInfo.UserPhone));
                CheckValue.NotNullOrWhiteSpace(loginInfo.Password, nameof(loginInfo.Password));

                var httpClient = _httpClientFactory.CreateClient("noRedirect");

                //Step one : Get AccessToken
                var accessUrl = XiaoMiConfig.GetAccessUrl(loginInfo.UserPhone);

                var content = new StringContent(XiaoMiConfig.GetAccessRequestBody(loginInfo.UserPhone, loginInfo.Password), Encoding.UTF8, "application/x-www-form-urlencoded");
                //add important headers
                content.Headers.Add("hm-privacy-diagnostics", "false");
                content.Headers.Add("app_name", "com.xiaomi.hm.health");
                content.Headers.Add("hm-privacy-ceip", "true");
                content.Headers.Add("X-Request-Id", Guid.NewGuid().ToString());

                using var response = await httpClient.PostAsync(accessUrl, content, cancellationToken);

                if (response.StatusCode != HttpStatusCode.RedirectMethod)
                {
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "登录失败", "尝试获取AccessToken时失败"));
                }

                var parms = HttpUtility.ParseQueryString(response.Headers.Location.Query);

                var accessToken = parms["access"];

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "登录失败", "尝试获取AccessToken时失败"));
                }

                //Step two : Login to system
                string deviceId     = user?.DeviceId ?? IdentityHelper.GetRandomDeviceId();
                var    loginContent = new StringContent(XiaoMiConfig.GetLoginRequestBody(accessToken, HttpUtility.UrlEncode(deviceId, Encoding.UTF8)), Encoding.UTF8, "application/x-www-form-urlencoded");

                using var loginResponse = await httpClient.PostAsync(XiaoMiConfig.LoginUrl, loginContent, cancellationToken);

                loginResponse.EnsureSuccessStatusCode();

                var responseContent = await loginResponse.Content.ReadAsStringAsync();

                _logger.LogInformation(await loginContent.ReadAsStringAsync());
                _logger.LogInformation(responseContent);

                if (loginResponse.StatusCode != HttpStatusCode.OK)
                {
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "登录失败", responseContent));
                }

                //得到当前登录成功的用户信息
                var successModel = JsonSerializer.Deserialize <XiaoMiLoginSuccessModel>(responseContent, new JsonSerializerOptions()
                {
                    IgnoreNullValues = true
                });

                XiaoMiLoginAPISuccessModel result = new XiaoMiLoginAPISuccessModel()
                {
                    AlreadyHasUser  = user != null,
                    APIResponseData = responseContent,
                    DeviceId        = deviceId,
                    LoginToken      = successModel.token_info.login_token,
                    Token           = successModel.token_info.app_token,
                    UserId          = successModel.token_info.user_id,
                };

                return(OperateResult.Success(HttpStatusCode.OK.ToString(), "登录成功", result));
            }
            catch (Exception ex)
            {
                return(OperateResult.Failed(ex, "尝试登录时发生错误", ex.Message));
            }
        }
Ejemplo n.º 16
0
        // 通过验证码登录
        private async Task <OperateResult> LoginWithAuthCode(LeXinAuthCodeLoginModel loginInfo, StepFlyUser existUser, CancellationToken cancellationToken = default)
        {
            try
            {
                CheckValue.NotNullOrWhiteSpace(loginInfo.LoginName, nameof(loginInfo.LoginName));
                CheckValue.NotNullOrWhiteSpace(loginInfo.AuthCode, nameof(loginInfo.AuthCode));

                var httpClient = _httpClientFactory.CreateClient();

                var clientId = GetClientId(existUser);
                var url      = GetAuthCodeLoginUrl(clientId);
                loginInfo.SetClientId(clientId);

                var jsonOptions = new JsonSerializerOptions()
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };
                var content = new StringContent(JsonSerializer.Serialize(loginInfo, jsonOptions), Encoding.UTF8, "application/json");

                using var response = await httpClient.PostAsync(url, content, cancellationToken);

                response.EnsureSuccessStatusCode();

                var responseContent = await response.Content.ReadAsStringAsync();

                _logger.LogInformation(await content.ReadAsStringAsync());
                _logger.LogInformation(responseContent);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "登录失败", responseContent));
                }

                if (!response.Headers.TryGetValues("Set-Cookie", out var cookies))
                {
                    var apiResult = JsonSerializer.Deserialize <LeXinHttpResponse>(responseContent, new JsonSerializerOptions()
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    if (apiResult.Code != 200)
                    {
                        return(OperateResult.Failed(null, apiResult.Code.ToString(), apiResult.Msg));
                    }

                    _logger.LogInformation($"登录返回成功,但是并没有获取到Cookie & Code:{response.StatusCode} & ResponseContent:{responseContent}");
                    return(OperateResult.Failed(null, response.StatusCode.ToString(), "登录返回成功,但是并没有获取到Cookie", responseContent));
                }

                var currentCookie = string.Join("", cookies.Select(s => s.Split(";")[0]).ToArray());
                //得到当前登录成功的用户信息
                using var jsonDoc = JsonDocument.Parse(responseContent);
                var element = jsonDoc.RootElement.GetProperty("data");

                LeXinLoginAPISuccessModel result = new LeXinLoginAPISuccessModel()
                {
                    AlreadyHasUser  = existUser != null,
                    APIResponseData = element.GetRawText(),
                    ClientInfo      = clientId,
                    Cookie          = currentCookie
                };

                return(OperateResult.Success(HttpStatusCode.OK.ToString(), "登录成功", result));
            }
            catch (Exception ex)
            {
                return(OperateResult.Failed(ex, "尝试登录时发生错误", ex.Message));
            }
        }