Beispiel #1
0
        /// <summary>
        /// 执行授权
        /// </summary>
        /// <returns></returns>
        public bool Grant(bool takeAll, params GrantCodeRight[] rights)
        {
            OAuthApp app = OAuthAppCache.Instance.Find(it => it.APP_CODE.Equals(this._appCode));

            if (app == null)
            {
                Alert("未注册的应用");
                return(false);
            }
            GrantScope[] scope = ScopeCache.Instance.FindAll(this._scope);
            if (scope == null || scope.Length <= 0)
            {
                Alert("未定义的授权类型");
                return(false);
            }
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByCode(this._userCode);

            if (user == null)
            {
                Alert("用户信息加载失败");
                return(false);
            }
            if (CheckAlreadyAuth(app.APP_ID, user.UserId))
            {
                return(true);
            }
            if (takeAll && (rights == null || rights.Length <= 0))
            {
                var temp = ScopeRightProvider.GetScopeRights(this._scope);
                rights = new GrantCodeRight[temp.Count];
                for (int i = 0; i < rights.Length; i++)
                {
                    rights[i] = new GrantCodeRight
                    {
                        RightId   = temp[i].Right_Id,
                        RightType = temp[i].Right_Type
                    };
                }
            }
            this.Auth_Code = Guid.NewGuid().ToString("N");
            Tauth_Code daCode = new Tauth_Code();

            daCode.App_Id      = app.APP_ID;
            daCode.Expire_Time = DateTime.Now.AddMinutes(5);
            daCode.Grant_Code  = this.Auth_Code;
            daCode.Scope_Id    = scope.FirstOrDefault().SCOPE_ID;
            daCode.User_Id     = user.UserId;
            daCode.Device_Id   = this._device_id;
            if (rights != null && rights.Length > 0)
            {
                daCode.Right_Json = Javirs.Common.Json.JsonSerializer.JsonSerialize(rights);
            }
            if (!daCode.Insert())
            {
                Alert("授权失败,请重试!");
                return(false);
            }
            return(true);
        }
        public bool GetUserInfo()
        {
            int appid, userId;

            if (!xUtils.DecryptOpenId(this._open_id, out userId, out appid))
            {
                Alert((ResultType)ResponseCode.Token错误, "open_id无效");
                return(false);
            }
            UserToken token = UserToken.FromCipherToken(_access_token);

            if (token == null)
            {
                Alert("无效Token");
                return(false);
            }
            if (token.Expire_Time < DateTime.Now)
            {
                Alert((ResultType)ResponseCode.令牌已过期, "Token已过期");
                return(false);
            }
            var   fac      = UserModuleFactory.GetUserModuleInstance();
            IUser userInfo = fac?.GetUserByID(userId);

            if (userInfo == null)
            {
                Alert("用户已注销或不存在");
                return(false);
            }
            UserInfoDictionary.Add("UserName", userInfo.UserName);
            UserInfoDictionary.Add("Avatar", userInfo.Avatar);
            return(true);
        }
Beispiel #3
0
        public bool SendCode()
        {
            string smsAccount  = Winner.ConfigurationManager.ConfigurationProvider.GetString(SMS_ACCOUNT_SETTING_NAME);
            string smsPassword = Winner.ConfigurationManager.ConfigurationProvider.GetString(SMS_PWD_SETTING_NAME);
            var    fac         = UserModuleFactory.GetUserModuleInstance();

            this.User = fac?.GetUserByCode(this._userCode);
            if (_validationType == SmsValidateType.注册)
            {
                if (User != null)
                {
                    Alert("手机号已被注册");
                    return(false);
                }
            }
            else if (_validationType == SmsValidateType.重置支付密码 || _validationType == SmsValidateType.重置登录密码)
            {
                if (User == null)
                {
                    Alert("手机号未注册");
                    return(false);
                }
            }
            SmsServiceClient client = new SmsServiceClient(smsAccount, smsPassword);

            if (!client.SendValidateCode(this._userCode, GID, null))
            {
                Alert(client.Message);
                return(false);
            }
            return(true);
        }
        private static FuncResult <int?> GetIntroducerId(string refereeCode)
        {
            if (string.IsNullOrEmpty(refereeCode) && AppConfig.RegisterRefereeRequired)
            {
                return(FuncResult.FailResult <int?>("必须填写推荐人"));
            }

            if (string.IsNullOrEmpty(refereeCode))
            {
                return(FuncResult.SuccessResult(default(int?)));
            }
            var   fac         = UserModuleFactory.GetUserModuleInstance();
            IUser refereeUser = null;

            if (refereeCode.StartsWith("U"))
            {
                refereeUser = fac?.GetUserByCode(refereeCode);
            }
            else
            {
                int userid;
                if (!int.TryParse(refereeCode.Replace("U", ""), out userid))
                {
                    return(FuncResult.FailResult <int?>("无效的邀请码"));
                }
                refereeUser = fac?.GetUserByID(userid);
            }
            if (refereeUser == null)
            {
                return(FuncResult.FailResult <int?>("推荐人账号不存在"));
            }
            return(FuncResult.SuccessResult(refereeUser?.UserId));
        }
Beispiel #5
0
        public JsonResult GetIdentityDetails(int userId)
        {
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                return(FailResult("用户模块加载失败"));
            }
            IUser user = fac.GetUserByID(userId);

            if (user == null)
            {
                return(FailResult("找不到会员信息"));
            }
            Vnet_Identity daIdentity = new Vnet_Identity();

            if (!daIdentity.SelectByUser_Id(user.UserId))
            {
                return(FailResult("找不到认证信息"));
            }
            var data = new
            {
                User         = user,
                IdentityInfo = daIdentity.DataRow.Table.ToDynamic(forceToCollection: false, OnFieldGenerating: nvp =>
                {
                    if ("remarks".Equals(nvp.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        nvp.Value = xUtils.GetValidateRemarks(nvp.Value.ToString());
                    }
                    return(nvp);
                })
            };

            return(SuccessResult(data));
        }
Beispiel #6
0
        /// <summary>
        /// 支付vip订单   POST: /vip/orderpayment
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderPayment([Display(Name = "订单号"), Required(ErrorMessage = "{0}不能为空")] string OrderNo,
                                         [Display(Name = "支付密码"), Required] string PayPwd)
        {
            string plainPwd;

            if (!xUtils.RsaDecryptPayPwd(PayPwd, out plainPwd))
            {
                return(FailResult("密码解密失败", (int)ApiStatusCode.DECRYPT_PASSWORD_FAIL));
            }
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                return(FailResult("会员模块加载失败", (int)ApiStatusCode.MODULE_LOAD_FAIL));
            }
            IUser user = fac.GetUserByID(Package.UserId);

            if (user == null)
            {
                return(FailResult("会员信息加载失败,请重试", (int)ApiStatusCode.DATA_NOT_FOUND));
            }
            if (!user.CheckPayPassword(plainPwd))
            {
                return(FailResult(user.PromptInfo.Message));
            }

            OrderPaymentProvider paymentProvider = new OrderPaymentProvider(Package.UserId, OrderNo, Entities.PayType.金币支付, true);

            if (!paymentProvider.Pay())
            {
                return(FailResult(paymentProvider.PromptInfo.CustomMessage, (int)paymentProvider.PromptInfo.ResultType));
            }
            return(SuccessResult());
        }
Beispiel #7
0
        public ActionResult Register(string id)
        {
            int?refer_id = null;

            if (!string.IsNullOrEmpty(id))
            {
                string plainText = Encoding.UTF8.GetString(Base58.Decode(id));
                int    r_id;
                if (!int.TryParse(plainText, out r_id))
                {
                    return(RedirectToAction("result", new { errMessage = "链接已失效" }));
                }
                refer_id = r_id;
            }
            IUser referUser = null;

            ViewBag.Referee_Code = string.Empty;
            ViewBag.Referee_Name = string.Empty;
            if (refer_id.HasValue)
            {
                var fac = UserModuleFactory.GetUserModuleInstance();
                referUser = fac?.GetUserByID(refer_id.Value);
                if (referUser != null)
                {
                    ViewBag.Referee_Code = referUser.UserCode;
                    ViewBag.Referee_Name = referUser.UserName;
                }
            }
            return(View());
        }
Beispiel #8
0
        public void UserInfoPayPwdCheckTest()
        {
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac.GetUserByCode("18675534882");
            bool  res  = user.CheckPayPassword("123456");

            Assert.IsTrue(res);
        }
Beispiel #9
0
        public static IUser GetUserByCode(string code)
        {
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                return(null);
            }
            return(fac.GetUserByCode(code));
        }
        public ResponseResult <ThirdPartyLoginResult> Login(ThirdpartyLoginRequestDTO model)
        {
            var app = OAuthAppCache.Get(model.Appid);

            if (app == null)
            {
                return(Fail <ThirdPartyLoginResult>("无效的应用id", "0400"));
            }
            string plainText;

            if (!xUtils.RsaDecrypt(model.AuthCode, out plainText))
            {
                return(Fail <ThirdPartyLoginResult>("授权码解密失败"));
            }
            int pos = plainText.IndexOf('_');

            string[] array = new string[2];
            array[0] = plainText.Substring(0, pos);
            array[1] = plainText.Substring(pos + 1);
            long timestamp;

            if (!long.TryParse(array[0], out timestamp))
            {
                return(Fail <ThirdPartyLoginResult>("授权码明文格式不正确", "0400"));
            }
            long currentTime = xUtils.GetCurrentTimeStamp();

            if (currentTime - timestamp > 120)
            {
                return(Fail <ThirdPartyLoginResult>("请求已过期", "0403"));
            }
            string trueOpenID = array[1];
            var    fac        = UserModuleFactory.GetUserModuleInstance();
            IUser  user       = fac?.GetUserByVoucher(trueOpenID, (UserVoucherType)model.PlatformID);
            var    thirdLogin = new ThirdPartyLoginProvider(user);

            string csource = Request.Headers["clientsource"];

            int.TryParse(csource, out int clientSource);
            string clientSystem    = Request.Headers["clientsystem"];
            string device_id       = Request.Headers["device_id"];
            string userHostAddress = Request.Headers["X-FORWARD-FOR"];
            string sessionId       = Request.Headers["sessionId"];
            string clientVersion   = Request.Headers["clientversion"];
            //若登录失败,客户端需调用绑定手机号
            var result = thirdLogin.Login(clientSource, clientSystem, device_id, clientVersion, userHostAddress, sessionId, app.Id);

            if (!result.Success)
            {
                return(Fail <ThirdPartyLoginResult>("首次使用第三方登录,请先绑定账号!", "0202"));
            }
            return(Success(result.Content));
        }
Beispiel #11
0
        public FuncResult <ThirdPartyLoginResult> Login(Winner.WebApi.Contract.ApiPackage package, string ipAddress, string session_id, int appId)
        {
            //ThirdParty、OpenId
            bool           isExist = false;
            int            userId  = 0;
            Tnet_User_Auth daAuth  = new Tnet_User_Auth();

            if (!(isExist = daAuth.SelectByThirdparty_OpenId((int)this._thirdParty, this._openID)))
            {
                //if not exist
                //add one
                userId            = GetNewUserId();
                daAuth.Open_Id    = this._openID;
                daAuth.Status     = 1;
                daAuth.Thirdparty = (int)this._thirdParty;
                daAuth.User_Id    = userId;
                if (!daAuth.Insert())
                {
                    //Alert("登录失败,保存登录信息异常");
                    return(FuncResult.FailResult <ThirdPartyLoginResult>("登录失败,保存登录信息异常"));
                }
            }
            else
            {
                userId = daAuth.User_Id;
            }
            if (!isExist)
            {
                return(FuncResult.SuccessResult((ThirdPartyLoginResult)null));
            }
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac.GetUserByID(userId);

            if (user == null)
            {
                return(FuncResult.SuccessResult((ThirdPartyLoginResult)null));
            }
            LoginProvider localLogin = new LoginProvider(user.UserCode, null);

            localLogin.IgnorePassword = true;
            if (!localLogin.Login(package.ClientSource, package.ClientSystem, package.Device_Id, ipAddress, session_id, package.ClientVersion, appId))
            {
                return(FuncResult.FailResult <ThirdPartyLoginResult>(localLogin.PromptInfo.CustomMessage, (int)localLogin.PromptInfo.ResultType));
            }
            var data = new ThirdPartyLoginResult
            {
                Token    = localLogin.Token,
                UserCode = user.UserCode
            };

            return(FuncResult.SuccessResult(data));
        }
Beispiel #12
0
        public bool Login(int client_source, string client_system, string device_id, string ip_address, string session_id, string clientVersion, int appid)
        {
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                Alert("加载用户模块失败");
                return(false);
            }

            this.User = fac.GetUserByCode(_user_code);
            if (this.User == null)
            {
                Alert("用户未注册");
                return(false);
            }
            var lockResult = this.User.IsLocked(Winner.User.Interface.Lock.LockRight.登陆);

            if (lockResult.IsLocked)
            {
                Alert((ResultType)403, lockResult.Reason);
                return(false);
            }
            if (!IgnorePassword && !this.User.CheckLoginPassword(_password))
            {
                Alert(this.User.PromptInfo.Message);
                return(false);
            }
            this.Token = xUtils.EncryptAccessToken(this.User.UserId, this.User.UserCode, appid);
            Tauth_Session daSession = new Tauth_Session
            {
                Client_Source  = client_source,
                Client_System  = client_system,
                Device_Id      = device_id,
                Ip_Address     = ip_address,
                Session_Id     = session_id,
                Status         = 1,
                User_Id        = this.User.UserId,
                Token          = this.Token,
                Client_Version = clientVersion
            };

            if (!daSession.Insert())
            {
                Alert("保存登录会话失败");
                return(false);
            }
            Logined();
            return(true);
        }
Beispiel #13
0
 public ValidateCodeProvider(int userId, PasswordType codeType) : this()
 {
     this._codeType = codeType;
     try
     {
         var fac  = UserModuleFactory.GetUserModuleInstance();
         var user = fac.GetUserByID(userId);
         this._userCode = user.UserCode;
     }
     catch (Exception ex)
     {
         this._userCode = null;
     }
 }
Beispiel #14
0
        private void FillInviterInfo(int?refereeId, Dictionary <string, object> dictionary)
        {
            IUser refereeUser = null;

            if (refereeId.HasValue)
            {
                var fac = UserModuleFactory.GetUserModuleInstance();
                if (fac != null)
                {
                    refereeUser = fac.GetUserByID(refereeId.Value);
                }
            }
            dictionary.Add("RefereeCode", refereeUser == null ? "" : refereeUser.UserCode);
            dictionary.Add("RefereeName", refereeUser == null ? "" : refereeUser.UserName);
        }
        /// <summary>
        /// 获取自定义账号
        /// </summary>
        /// <returns></returns>
        private static string GetCustomeAccount()
        {
            var    daUser = DaoFactory.Tnet_User();
            string code   = daUser.GenerateCustomCode();

            string account = string.Concat(xUtils.CustomAccountPrefix, code.PadLeft(8, '0'));
            var    fac     = UserModuleFactory.GetUserModuleInstance();
            IUser  user    = fac.GetUserByVoucher(account, UserVoucherType.自定义号码);

            if (user != null)
            {
                return(GetCustomeAccount());
            }
            return(account);
        }
Beispiel #16
0
        protected virtual bool LoginByToken(string rsaToken, string device_id, string appVersion, out string message)
        {
            string com_token;

            if (!xUtils.RsaDecryptPayPwd(rsaToken, out com_token))
            {
                message = "无效的登录会话,请重新登录";
                return(false);
            }
            if (!com_token.Contains("_"))
            {
                message = "无效的请求";
                return(false);
            }
            string[] array            = com_token.Split('_');
            string   token            = array[1];
            long     requestTimestamp = Convert.ToInt64(array[0]);
            long     timestamp        = (long)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;

            if (timestamp - requestTimestamp > 120)//请求有效期2分钟
            {
                message = "会话超时,请重新登录";
                return(false);
            }
            Token.UserToken userToken = Token.UserToken.FromCipherToken(token);
            if (userToken == null)
            {
                message = "无效的登录会话,请重新登录";
                return(false);
            }
            if (userToken.Expire_Time < DateTime.Now)
            {
                message = "登录会话已失效,请重新登录";
                return(false);
            }

            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByCode(userToken.UserCode);

            if (user == null)
            {
                message = "账号未注册";
                return(false);
            }
            Session[OAuthContext._USER_LOGIN_SESSION_NAME] = user;
            message = null;
            return(true);
        }
Beispiel #17
0
        /// <summary>
        /// 修改推荐人
        /// </summary>
        /// <returns></returns>
        public bool ChangeReferee(int userId, string refereeCode, int op_user_id)
        {
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                Alert("系统错误");
                return(false);
            }
            IUser user = fac.GetUserByID(userId);

            if (user == null)
            {
                Alert("会员信息有误");
                return(false);
            }
            string value_before = user.Refer_ID.HasValue ? user.Refer_ID.Value.ToString() : null;
            IUser  refereeUser  = fac.GetUserByCode(refereeCode);

            if (refereeUser == null)
            {
                Alert("推荐人信息有误");
                return(false);
            }
            if (user.Refer_ID.HasValue && user.Refer_ID.Value == refereeUser.UserId)
            {
                return(true);
            }
            user.Refer_ID = refereeUser.UserId;
            var mgt = fac.GetProfileManager(user);

            if (!mgt.Update())
            {
                Alert("推荐人修改失败");
                return(false);
            }
            LogDetails refereeInfo = new LogDetails
            {
                DATA_FIELD   = "Refer_ID",
                VALUE_AFTER  = refereeUser.UserId.ToString(),
                VALUE_BEFORE = value_before
            };

            AdminDatabaseLog.PersistToDatabase(OperateType.UPDATE, op_user_id, "TNET_USER", user.UserId, "会员管理后台修改推荐人", null, refereeInfo);
            return(true);
        }
Beispiel #18
0
        public JsonResult GetUserInfo(int userId)
        {
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                return(FailResult("系统错误"));
            }
            IUser user = fac.GetUserByID(userId);

            if (user == null)
            {
                return(FailResult("找不到用户信息"));
            }
            IUser referUser = null;

            if (user.Refer_ID.HasValue)
            {
                referUser = fac.GetUserByID(user.Refer_ID.Value);
            }
            Vnet_Identity daIdentity = new Vnet_Identity();
            bool          isAuth     = daIdentity.SelectByUser_Id(userId) && daIdentity.Validate_Status == (int)ValidateStatus.审核通过;
            var           data       = new
            {
                user_id       = user.UserId,
                user_name     = user.UserName,
                user_code     = user.UserCode,
                email         = user.Email,
                auth_status   = user.Auth_Status,
                status        = user.Status,
                avatar        = user.Avatar,
                grade_level   = user.Grade.Level,
                grade_name    = user.Grade.Name,
                register_time = user.Register_Time,
                refer_id      = user.Refer_ID,
                refer_code    = referUser == null ? null : referUser.UserCode,
                refer_name    = referUser == null ? null : referUser.UserName,
                real_name     = isAuth ? daIdentity.User_Name : null,
                identity_no   = isAuth ? daIdentity.Identity_No : null,
                auth_time     = isAuth ? daIdentity.Create_Time : null,
                gender        = isAuth ? daIdentity.Gender : null,
                birthday      = isAuth ? daIdentity.Birthday : null
            };

            return(SuccessResult(data));
        }
        /// <summary>
        /// 获取关联的会员信息
        /// </summary>
        /// <returns></returns>
        public IUser GetAssociateUser()
        {
            if (_associateUser != null)
            {
                return(_associateUser);
            }
            if (string.IsNullOrEmpty(_refereeCode))
            {
                return(null);
            }
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                Log.Info("缺少用户模块");
                return(null);
            }
            if (_refereeCode.IsMobileNo())//手机号账号
            {
                _associateUser = fac.GetUserByMobileno(_refereeCode);
            }
            else if (_refereeCode.StartsWith("U"))//ID邀请码
            {
                int userid;
                if (!int.TryParse(_refereeCode.Replace("U", ""), out userid))
                {
                    return(null);
                }
                _associateUser = fac.GetUserByID(userid);
            }
            else if (_refereeCode.StartsWith(xUtils.CustomAccountPrefix))//自定义账号
            {
                _associateUser = fac.GetUserByCode(_refereeCode);
            }
            else
            {
                Log.Info("未识别的邀请码");
            }
            return(_associateUser);
        }
Beispiel #20
0
        /// <summary>
        /// 检查推荐人账号是否存在
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckUserCode()
        {
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByCode(Package.UserCode);

            if (user == null)
            {
                return(FailResult("推荐人账号未注册"));
            }
            else
            {
                string userName = string.Concat("*", user.UserName.Substring(1));
                if (Regex.IsMatch(user.UserName, "^\\d+$"))
                {
                    userName = Regex.Replace(user.UserName, "^(\\d{2})(\\d{5})(\\d{4})$", "$1*****$3");
                }
                var data = new
                {
                    UserName = userName
                };
                return(SuccessResult(data));
            }
        }
Beispiel #21
0
        private static FuncResult <int?> GetIntroducerId(string refereeCode)
        {
            var result = new FuncResult <int?>();

            if (string.IsNullOrEmpty(refereeCode))
            {
                result.Success = true;
                result.Content = null;
                return(result);
            }
            var   fac         = UserModuleFactory.GetUserModuleInstance();
            IUser refereeUser = fac?.GetUserByCode(refereeCode);
            int?  refereeId   = refereeUser?.UserId;

            if (!refereeId.HasValue)
            {
                result.Success = false;
                result.Message = "推荐人账号不存在";
                return(result);
            }
            result.Success = true;
            result.Content = refereeId;
            return(result);
        }
Beispiel #22
0
        public override Task <PasswordResetResponseDTO> Reset(PasswordResetRequestDTO request, ServerCallContext context)
        {
            return(Task.Run(() =>
            {
                PasswordResetResponseDTO response = new PasswordResetResponseDTO();
                var fac = UserModuleFactory.GetUserModuleInstance();
                if (fac == null)
                {
                    response.RetCode = "0500";
                    response.RetMsg = "系统错误";
                    return response;
                }
                string newPwd = request.NewPwd;
                string validateCode = request.ValidateCode;
                if (request.EncodeType.ToLower() == "base64")
                {
                    request.NewPwd = xUtils.Base64ToBase58(request.NewPwd);
                }
                if (!xUtils.RsaDecrypt(request.NewPwd, out newPwd))
                {
                    response.RetCode = "0400";
                    response.RetMsg = "新密码解密失败";
                    return response;
                }
                if (request.ValidateType == PasswordResetRequestDTO.Types.IdentityValidateType.OldPasswordValidation)
                {
                    if (request.EncodeType.ToLower() == "base64")
                    {
                        request.ValidateCode = xUtils.Base64ToBase58(request.ValidateCode);
                    }
                    if (!xUtils.RsaDecrypt(request.ValidateCode, out validateCode))
                    {
                        //return new ApiResult { retCode = "0400", retMsg = "旧密码解密失败" };
                        response.RetCode = "0400";
                        response.RetMsg = "旧密码解密失败";
                        return response;
                    }
                }
                IUser user = fac.GetUserByCode(request.UserCode);
                if (user == null)
                {
                    response.RetMsg = "用户账户[{request.UserCode}]未注册";
                    response.RetCode = "0400";
                    return response;
                }
                PasswordType passwordType = (PasswordType)request.PwdType;
                var validateType = (IdentityValidateType)request.ValidateType;
                IIdentityVerification verification = IdentityVerificationFactory.GetVerification(validateType, user, passwordType, validateCode);
                if (verification == null)
                {
                    response.RetCode = "0400";
                    response.RetMsg = "指定的身份验证方式不正确";
                    return response;
                }

                IPasswordManager pwdmgt = fac.GetPasswordManager();
                PasswordManagerArgs arg = new PasswordManagerArgs
                {
                    AlterSource = xUtils.GetClientSource(request.ClientSource),
                    NewPassword = newPwd,
                    PwdManager = pwdmgt,
                    PwdType = passwordType,
                    Remarks = string.Format("通过{0}修改", validateType.ToString()),
                    UserId = user.UserId,
                    Use_Place = request.ClientSystem,
                    Verification = verification
                };
                string datasource = string.Concat(xUtils.GetClientSource(request.ClientSource), "-", validateType, "-重置密码");
                UserPasswordManager manager = new UserPasswordManager(arg);
                if (!manager.Alter(datasource, datasource))
                {
                    response.RetMsg = manager.PromptInfo.CustomMessage;
                    response.RetCode = "0500";
                    return response;
                }
                response.RetCode = "0000";
                response.RetMsg = "ok";
                return response;
            }));
        }
Beispiel #23
0
        public bool OAuthAccess()
        {
            var app = OAuthAppCache.Instance.Find(it => it.APP_CODE.Equals(this._appid));

            if (app == null)
            {
                Alert("无效的应用编号");
                return(false);
            }
            Tauth_Code daCode = new Tauth_Code();

            if (!daCode.SelectByAppId_GrantCode(app.APP_ID, this._auth_code))
            {
                Alert("无效的授权码");
                return(false);
            }
            if (daCode.Status == 1)
            {
                Alert("该授权码已被使用,不能重复使用");
                return(false);
            }
            if (daCode.Expire_Time < DateTime.Now)
            {
                Alert("授权码已过期");
                return(false);
            }
            daCode.Status = 1;
            if (!daCode.Update())
            {
                Alert("授权码验证失败");
                return(false);
            }
            int   user_id = daCode.User_Id;
            var   fac     = UserModuleFactory.GetUserModuleInstance();
            IUser user    = fac?.GetUserByID(user_id);

            if (user == null)
            {
                Alert("用户不存在");
                return(false);
            }
            string open_id = xUtils.EncryptOpenId(app.APP_ID, user_id, app.UID_ENCRYPT_KEY);

            this.OAuthUser.Open_Id       = open_id;
            this.OAuthUser.Token         = xUtils.EncryptAccessToken(user_id, user.UserCode, app.APP_ID);
            this.OAuthUser.Refresh_Token = xUtils.EncryptAccessToken(user_id, user.UserCode, app.APP_ID, 2592000);
            BeginTransaction();
            Tauth_Token daToken = new Tauth_Token();

            daToken.ReferenceTransactionFrom(Transaction);
            bool exist = daToken.SelectByAppId_UserId(app.APP_ID, user_id);

            daToken.App_Id          = app.APP_ID;
            daToken.Expire_Time     = DateTime.Now.AddSeconds(this.OAuthUser.Expire_In);
            daToken.Refresh_Timeout = DateTime.Now.AddDays(this.OAuthUser.Refresh_Expire_In);
            daToken.Refresh_Token   = this.OAuthUser.Refresh_Token;
            daToken.Token_Code      = this.OAuthUser.Token;
            daToken.Scope_Id        = daCode.Scope_Id;
            daToken.User_Id         = user_id;
            daToken.Grant_Id        = daCode.Auth_Id;
            if (exist)
            {
                if (!daToken.Update())
                {
                    Rollback();
                    Alert("TOKEN生成失败");
                    return(false);
                }
            }
            else
            {
                if (!daToken.Insert())
                {
                    Rollback();
                    Alert("TOKEN生成失败");
                    return(false);
                }
            }
            if (!UpdateTokenRights(daToken.Token_Id, daToken.Refresh_Timeout, daCode.Right_Json))
            {
                Rollback();
                return(false);
            }
            Commit();
            return(true);
        }
Beispiel #24
0
        public bool Refresh()
        {
            var app = OAuthAppCache.Instance.Find(it => it.APP_CODE == this._appid);

            if (app == null)
            {
                Alert((ResultType)ResponseCode.应用ID无效, "未知的应用ID");
                return(false);
            }
            var DecryptRes = xUtils.DecryptAccessToken(this._refresh_token);

            if (!DecryptRes.Success)
            {
                Alert((ResultType)ResponseCode.无效操作, DecryptRes.Message);
                return(false);
            }
            UserToken token = DecryptRes.Content;

            if (token.Expire_Time < DateTime.Now)
            {
                Alert((ResultType)ResponseCode.令牌已过期, "令牌已过期,请重新发起用户授权");
                return(false);
            }
            Tauth_Token daToken = new Tauth_Token();

            if (!daToken.SelectByAppId_UserId(app.APP_ID, token.UserId))
            {
                Alert((ResultType)ResponseCode.Token错误, "未找到授权记录,无效的刷新令牌");
                return(false);
            }
            if (!daToken.Refresh_Token.Equals(this._refresh_token))
            {
                Alert((ResultType)ResponseCode.无效操作, "无效的刷新令牌");
                return(false);
            }
            if (daToken.Refresh_Timeout < DateTime.Now)
            {
                Alert((ResultType)ResponseCode.令牌已过期, "令牌已过期,请重新发起用户授权");
                return(false);
            }
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByID(daToken.User_Id);

            if (user == null)
            {
                Alert("用户不存在");
                return(false);
            }
            string newToken = xUtils.EncryptAccessToken(token.UserId, user.UserCode, app.APP_ID);

            daToken.Token_Code  = newToken;
            daToken.Expire_Time = DateTime.Now.AddSeconds(this.OAuthUser.Expire_In);
            if (!daToken.Update())
            {
                Alert((ResultType)ResponseCode.务器错误, "Token刷新失败,请重试");
                return(false);
            }
            this.OAuthUser.Open_Id           = xUtils.EncryptOpenId(app.APP_ID, token.UserId, app.UID_ENCRYPT_KEY);
            this.OAuthUser.Token             = newToken;
            this.OAuthUser.Refresh_Token     = this._refresh_token;
            this.OAuthUser.Refresh_Expire_In = (int)(daToken.Refresh_Timeout - DateTime.Now).TotalDays;
            return(true);
        }
Beispiel #25
0
        public bool Register()
        {
            string[] array = new string[2];
            string   plainText;

            if (!xUtils.RsaDecrypt(_model.AuthCode, out plainText))
            {
                Alert("OpenID解密失败");
                return(false);
            }
            int pos = plainText.IndexOf('_');

            array[0] = plainText.Substring(0, pos);
            array[1] = plainText.Substring(pos + 1);
            long timestamp;

            if (!long.TryParse(array[0], out timestamp))
            {
                Alert("OpenID解密失败");
                return(false);
            }
            long currentTime = xUtils.GetCurrentTimeStamp();

            if (currentTime - timestamp > 120)
            {
                Alert("请求已过期");
                return(false);
            }
            string openID = array[1];
            SmsValidateProvider smsValidate = new SmsValidateProvider(_model.MobileNo, SmsValidateType.绑定手机号);

            if (!smsValidate.ValidateCode(_model.ValidateCode))
            {
                Alert(smsValidate.PromptInfo);
                return(false);
            }
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                Alert("系统模块异常");
                return(false);
            }
            if (!Enum.TryParse(_model.Platform, true, out ThirdpartyLoginPlatform platform))
            {
                Alert($"无效的第三方登录平台[{_model.Platform}]");
                return(false);
            }
            UserVoucherType uvt            = (UserVoucherType)platform;
            IUser           thirdpartyUser = fac.GetUserByVoucher(openID, uvt);

            if (thirdpartyUser == null)
            {
                IUser user = fac.GetUserByMobileno(_model.MobileNo);
                if (user == null)
                {
                    var voucher = fac.GetVoucherObject();
                    voucher.AllowLogin  = true;
                    voucher.IsValid     = true;
                    voucher.Status      = 1;
                    voucher.UserCode    = _model.MobileNo;
                    voucher.VoucherType = UserVoucherType.手机号;
                    UserCreationProvider ucp = new UserCreationProvider(openID, null, _model.RefereeCode, uvt);
                    ucp.Vouchers.Add(voucher);
                    if (!ucp.AddUser(_model.NickName ?? xUtils.GetDefaultUserName(_model.MobileNo), _model.Avatar))
                    {
                        Alert(ucp.PromptInfo);
                        return(false);
                    }
                    user = ucp.User;
                }
                else
                {
                    var voucher = fac.GetVoucherObject();
                    voucher.AllowLogin  = true;
                    voucher.IsValid     = true;
                    voucher.Status      = 1;
                    voucher.UserCode    = openID;
                    voucher.VoucherType = uvt;
                    if (!voucher.Save(user.UserId))
                    {
                        Alert((ResultType)503, "已有账号绑定第三方登录失败");
                        return(false);
                    }
                    user.Refresh();
                }
                this.User = user;
            }
            else
            {
                var thirdpartyVoucher = thirdpartyUser.Vouchers?.Find(it => it.VoucherType == uvt);
                if (thirdpartyVoucher != null)
                {
                    Alert((ResultType)409, $"该账号[{_model.MobileNo}]已绑定{platform.GetDisplayText()}");
                    return(false);
                }
                var voucher = fac.GetVoucherObject();
                voucher.AllowLogin  = true;
                voucher.IsValid     = true;
                voucher.Status      = 1;
                voucher.UserCode    = _model.MobileNo;
                voucher.VoucherType = UserVoucherType.手机号;
                if (!voucher.Save(thirdpartyUser.UserId))
                {
                    Alert((ResultType)503, "已有账号绑定第三方登录失败");
                    return(false);
                }
                thirdpartyUser.Refresh();
                this.User = thirdpartyUser;
            }
            return(true);
        }
        public bool Refresh()
        {
            var app = OAuthAppCache.Get(this._appid);

            if (app == null)
            {
                Alert(ResultType.非法操作, "未知的应用ID");
                return(false);
            }
            var DecryptRes = UserTokenProvider.DecryptAccessToken(this._refresh_token);

            if (!DecryptRes.Success)
            {
                Alert(ResultType.非法操作, DecryptRes.Message);
                return(false);
            }
            UserToken token = DecryptRes.Content;

            if (token.Expire_Time < DateTime.Now)
            {
                Alert(ResultType.需要登陆, "令牌已过期,请重新发起用户授权");
                return(false);
            }
            //Tauth_Token daToken = new Tauth_Token();
            var daTokenCollection = DaoFactory.Tauth_TokenCollection();

            if (!daTokenCollection.ListByUserId_AppId(token.UserId, app.Id))
            {
                Alert(ResultType.无权限, "未找到授权记录,无效的刷新令牌");
                return(false);
            }
            ITauth_Token daToken = null;

            foreach (ITauth_Token item in daTokenCollection)
            {
                if (item.Refresh_Token.Equals(this._refresh_token))
                {
                    daToken = item;
                }
            }
            if (daToken == null)
            {
                Alert(ResultType.非法操作, "无效的刷新令牌");
                return(false);
            }
            if (daToken.Refresh_Timeout < DateTime.Now)
            {
                Alert(ResultType.无权限, "令牌已过期,请重新发起用户授权");
                return(false);
            }
            var   fac  = UserModuleFactory.GetUserModuleInstance();
            IUser user = fac?.GetUserByID(daToken.User_Id);

            if (user == null)
            {
                Alert("用户不存在");
                return(false);
            }
            string userCode = user.GetUserVoucher(UserVoucherType.自定义号码);
            string newToken = UserTokenProvider.EncryptAccessToken(token.UserId, userCode, app.Id);

            daToken.Token_Code  = newToken;
            daToken.Expire_Time = DateTime.Now.AddSeconds(this.OAuthUser.Expire_In);
            if (!daToken.Update())
            {
                Alert(ResultType.系统异常, "Token刷新失败,请重试");
                return(false);
            }
            this.OAuthUser.Open_Id           = UserTokenProvider.EncryptOpenId(app.Id, token.UserId, userCode, app.UidEncryptKey);
            this.OAuthUser.Token             = newToken;
            this.OAuthUser.Refresh_Token     = this._refresh_token;
            this.OAuthUser.Refresh_Expire_In = (int)(daToken.Refresh_Timeout - DateTime.Now).TotalDays;
            return(true);
        }
Beispiel #27
0
        public JsonResult ResetPassword(PasswordResetModel model)
        {
            Log.Debug(model.ToLineText());
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                return(Json(FuncResult.FailResult("系统错误", 500)));
            }
            string newPwd       = model.New_Pwd;
            string validateCode = model.ValidateCode;

            if (model.PwdType == (int)PasswordType.支付密码)
            {
                if (!xUtils.RsaDecryptPayPwd(model.New_Pwd, out newPwd))
                {
                    return(Json(FuncResult.FailResult("新密码解密失败", (int)ApiStatusCode.DECRYPT_PASSWORD_FAIL)));
                }
                if (model.ValidateType == (int)IdentityValidateType.旧密码验证)
                {
                    if (!xUtils.RsaDecryptPayPwd(model.ValidateCode, out validateCode))
                    {
                        return(Json(FuncResult.FailResult("旧密码解密失败", (int)ApiStatusCode.DECRYPT_PASSWORD_FAIL)));
                    }
                }
            }
            IUser user = fac.GetUserByCode(Package.UserCode);

            if (user == null)
            {
                return(FailResult("用户账号[" + Package.UserCode + "]不存在"));
            }
            PasswordType          passwordType = (PasswordType)model.PwdType;
            var                   validateType = (IdentityValidateType)model.ValidateType;
            IIdentityVerification verification = IdentityVerificationFactory.GetVerification(validateType, user, passwordType, validateCode);

            if (verification == null)
            {
                return(Json(FuncResult.FailResult("指定的身份验证方式不正确", 409)));
            }

            IPasswordManager    pwdmgt = fac.GetPasswordManager(user);
            PasswordManagerArgs arg    = new PasswordManagerArgs
            {
                AlterSource  = xUtils.GetClientSource(this.Package.ClientSource),
                NewPassword  = newPwd,
                Pwd_Manager  = pwdmgt,
                Pwd_Type     = passwordType,
                Remarks      = string.Format("通过{0}修改", validateType.ToString()),
                UserId       = user.UserId,
                Use_Place    = this.Package.ClientSystem,
                Verification = verification
            };
            FuncResult          result  = new FuncResult();
            UserPasswordManager manager = new UserPasswordManager(arg);

            result.Success    = manager.Alter();
            result.Message    = result.Success ? null : manager.PromptInfo.CustomMessage;
            result.StatusCode = result.Success ? 1 : (int)manager.PromptInfo.ResultType;
            return(Json(result));
        }
Beispiel #28
0
 /// <summary>
 /// 生成用户授权访问令牌
 /// </summary>
 /// <returns></returns>
 public bool GenerateUserToken()
 {
     try
     {
         if (_app == null && !_appid.HasValue)
         {
             Alert(Winner.Framework.Utils.ResultType.无效数据类型, "无效的应用编号");
             return(false);
         }
         if (_app == null)
         {
             _app = OAuthAppCache.Get(_appid.Value);
         }
         this.OAuthUser.Expire_In         = _app.TokenExpireIn;
         this.OAuthUser.Refresh_Expire_In = 30;
         var   fac  = UserModuleFactory.GetUserModuleInstance();
         IUser user = fac?.GetUserByID(_userid);
         if (user == null)
         {
             Alert(Winner.Framework.Utils.ResultType.数据库查不到数据, "用户不存在");
             return(false);
         }
         if (_daCode == null)
         {
             //_daCode = new Tauth_Code();
             _daCode = DaoFactory.Tauth_Code();
             if (this._authid.HasValue)
             {
                 if (!_daCode.SelectByPk(this._authid.Value))
                 {
                     Alert(Winner.Framework.Utils.ResultType.无效数据类型, "无效的授权码");
                     return(false);
                 }
             }
             else
             {
                 _daCode.App_Id      = _app.Id;
                 _daCode.Expire_Time = DateTime.Now.AddMinutes(5);
                 _daCode.Grant_Code  = Guid.NewGuid().ToString("N").ToLower();
                 _daCode.Scope_Id    = ScopeCache.Get(this._scope).Id;
                 _daCode.User_Id     = user.UserId;
                 _daCode.Device_Id   = _deviceid;
                 _daCode.Remarks     = "客户端登录自动授权";
                 _daCode.Status      = 1;
                 if (!_daCode.Insert())
                 {
                     Alert(Winner.Framework.Utils.ResultType.非法操作, "登录授权失败");
                     return(false);
                 }
             }
         }
         int    refresh_token_expire_in = this.OAuthUser.Refresh_Expire_In * 86400;
         string userCode = user.GetUserVoucher(UserVoucherType.自定义号码);
         string open_id  = EncryptOpenId(_app.Id, user.UserId, userCode, _app.UidEncryptKey);
         this.OAuthUser.Open_Id       = open_id;
         this.OAuthUser.Token         = EncryptAccessToken(user.UserId, userCode, _app.Id, this.OAuthUser.Expire_In);
         this.OAuthUser.Refresh_Token = EncryptAccessToken(user.UserId, userCode, _app.Id, refresh_token_expire_in);
         BeginTransaction();
         //Tauth_Token daToken = new Tauth_Token();
         var daToken = DaoFactory.Tauth_Token();
         daToken.ReferenceTransactionFrom(Transaction);
         bool exist = daToken.SelectByAppId_UserId_DeviceId(_app.Id, this._userid, this._deviceid);
         daToken.App_Id          = _app.Id;
         daToken.Expire_Time     = DateTime.Now.AddSeconds(this.OAuthUser.Expire_In);
         daToken.Refresh_Timeout = DateTime.Now.AddDays(this.OAuthUser.Refresh_Expire_In);
         daToken.Refresh_Token   = this.OAuthUser.Refresh_Token;
         daToken.Token_Code      = this.OAuthUser.Token;
         daToken.Scope_Id        = _daCode.Scope_Id;
         daToken.User_Id         = _userid;
         daToken.Grant_Id        = _daCode.Auth_Id;
         daToken.Device_Id       = this._deviceid;
         if (exist)
         {
             daToken.Last_Access_Time = DateTime.Now;
             if (!daToken.Update())
             {
                 Rollback();
                 Alert(Winner.Framework.Utils.ResultType.数据库更新失败, "TOKEN生成失败");
                 return(false);
             }
         }
         else
         {
             if (!daToken.Insert())
             {
                 Rollback();
                 Alert(Winner.Framework.Utils.ResultType.数据库更新失败, "TOKEN生成失败");
                 return(false);
             }
         }
         this.TokenId = daToken.Token_Id;
         Commit();
         return(true);
     }
     catch (Exception ex)
     {
         Log.Error("生成token失败", ex);
         Alert(ResultType.系统异常, "生成token失败");
         return(false);
     }
 }
Beispiel #29
0
        public bool Login(int client_source, string client_system, string device_id, string ip_address, string session_id, string clientVersion, int appid)
        {
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                Alert(ResultType.系统异常, "加载用户模块失败");
                return(false);
            }
            try
            {
                UserVoucherType uvt = xUtils.GetVoucherType(this._user_code);
                this.User = fac.GetUserByVoucher(this._user_code, uvt);
            }
            catch (ApplicationException ex)
            {
                Alert(ResultType.非法操作, "无效的登录账号");
                Log.Error($"无效的登录账号[{this._user_code}]", ex);
                return(false);
            }
            catch (Exception exp)
            {
                Log.Error("登录异常", exp);
                Alert(ResultType.系统异常, "系统异常");
                return(false);
            }
            if (this.User == null)
            {
                Alert(ResultType.无效数据类型, "用户未注册");
                return(false);
            }
            if (this.User.Status != UserStatus.已激活)
            {
                Alert(ResultType.非法操作, $"账户{this.User.Status.ToString()}");
                return(false);
            }
            var lockResult = this.User.IsLocked(Winner.User.Interface.Lock.LockRight.登录);

            if (lockResult.IsLocked)
            {
                Alert(ResultType.非法操作, lockResult.Reason);
                return(false);
            }
            if (loginType == LoginType.LOGIN_BY_PASSWORD || loginType == LoginType.密码登录)
            {
                if (!IgnorePassword && !this.User.CheckLoginPassword(_password))
                {
                    Alert(ResultType.非法操作, this.User.ErrorInfo.Message);
                    return(false);
                }
            }
            else if (loginType == LoginType.短信验证码登录)
            {
                SmsValidateProvider smsValid = new SmsValidateProvider(this.User.MobileNo, SmsValidateType.登录验证码);
                if (!smsValid.ValidateCode(_password))
                {
                    Alert(ResultType.非法操作, smsValid.PromptInfo);
                    return(false);
                }
            }
            else
            {
                Alert(ResultType.无效数据类型, "无效的登录方式");
                return(false);
            }
            SaveUserDevice(this.User.UserId, device_id, client_system, client_source);
            //this.Token = xUtils.EncryptAccessToken(this.User.UserId, this.User.UserCode, appid);

            UserTokenProvider utp = new UserTokenProvider(appid, this.User.UserId, null, device_id, this._scope);

            if (!utp.GenerateUserToken())
            {
                Alert(utp.PromptInfo);
                return(false);
            }
            this.OAuthUser = utp.OAuthUser;
            this.Token     = utp.OAuthUser.Token;


            //Tauth_Session daSession = new Tauth_Session
            var daSession = DaoFactory.Tauth_Session();

            daSession.Client_Source  = client_source;
            daSession.Client_System  = client_system;
            daSession.Device_Id      = device_id;
            daSession.Ip_Address     = ip_address;
            daSession.Session_Id     = session_id;
            daSession.Status         = 1;
            daSession.User_Id        = this.User.UserId;
            daSession.Token          = this.Token;
            daSession.Client_Version = clientVersion;

            if (!daSession.Insert())
            {
                Alert(ResultType.系统异常, "保存登录会话失败");
                return(false);
            }
            Logined();
            return(true);
        }
Beispiel #30
0
        public bool ModifyUserProfile(Entities.ViewModels.UserModifyModel model)
        {
            if (!model.City_Id.HasValue && string.IsNullOrEmpty(model.Avatar) && !model.Org_Id.HasValue &&
                string.IsNullOrEmpty(model.Industry))
            {
                return(true);
            }
            var fac = UserModuleFactory.GetUserModuleInstance();

            if (fac == null)
            {
                Alert((ResultType)500, "系统错误");
                return(false);
            }
            IUser user = fac.GetUserByCode(model.UserCode);

            if (user == null)
            {
                Alert((ResultType)404, "找不到用户信息");
                return(false);
            }
            if (!model.City_Id.HasValue && string.IsNullOrEmpty(model.Avatar) && !model.Org_Id.HasValue &&
                !string.IsNullOrEmpty(user.Avatar) && user.Avatar.Equals(model.Avatar, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            BeginTransaction();
            Tnet_User_Profile daProfile = new Tnet_User_Profile();

            daProfile.ReferenceTransactionFrom(Transaction);
            bool isExist = daProfile.SelectByPk(user.UserId);

            if (model.City_Id.HasValue)
            {
                daProfile.City_Id = model.City_Id.Value;
            }
            if (!string.IsNullOrEmpty(model.Industry))
            {
                daProfile.Industry = model.Industry;
            }
            if (model.Org_Id.HasValue)
            {
                daProfile.Org_Id = model.Org_Id.Value;
            }
            if (!isExist)
            {
                daProfile.User_Id = user.UserId;
                if (!daProfile.Insert())
                {
                    Rollback();
                    Alert((ResultType)541, "用户资料更新失败");
                    return(false);
                }
            }
            else
            {
                if (!daProfile.Update())
                {
                    Rollback();
                    Alert((ResultType)542, "用户资料更新失败");
                    return(false);
                }
            }
            if (!string.IsNullOrEmpty(model.Avatar))
            {
                user.Avatar = model.Avatar;
                var manager = fac.GetProfileManager(user);
                if (!manager.Update())
                {
                    Rollback();
                    Alert((ResultType)540, "头像上传失败");
                    return(false);
                }
            }

            Commit();
            return(true);
        }