예제 #1
0
 /// <summary>
 /// 获取登录用户信息
 /// </summary>
 /// <returns>返回登陆用户信息,未登录用户返回null</returns>
 public void GetLoginedUserInfo()
 {
     /*if (HasLogined() != 1)
         return null;
     Result result = new Result();
     Entity user = new Entity();
     string getData = WebConnection.GetCommand(@"http://douban.fm/");
     MatchCollection mc = Regex.Matches(getData, @"<span id=""user_name"">([^{].*?)\s");
     user.Name = mc[0].Groups[1].Value;
     Match match = Regex.Match(getData, @"累积收听<span id=""rec_played"">(\d+)</span>首");
     user.Record.Played = Int32.Parse(match.Groups[1].Value);
     match = Regex.Match(getData, @"加红心<span id=""rec_liked"">(\d+)</span>首");
     user.Record.Liked = Int32.Parse(match.Groups[1].Value);
     match = Regex.Match(getData, @"<span id=""rec_banned"">(\d+)</span>首不再播放");
     user.Record.Banned = Int32.Parse(match.Groups[1].Value);
     match = Regex.Match(getData, @"http://www.douban.com/accounts/logout?.*?ck=(.*?)&amp");
     user.CK = match.Groups[1].Value;
     return result;*/
     string userInfoString;
     using (StreamReader reader = new StreamReader(DataFolder))
     {
         userInfoString = reader.ReadToEnd();
     }
     result = LoginResult.Json2Object(userInfoString);
     isLoginCompleted = true;
 }
	void OnLoginCallback(LoginResult result) 
	{
		Debug.Log(string.Format("Login Successful. Welcome Player:{0}!", result.PlayFabId));
		Debug.Log(string.Format("Your session ticket is: {0}", result.SessionTicket));
		GetInventory();
		UnlockUI();
	}
예제 #3
0
		public void ConnectToService()
		{
			try
			{
				Client = new SforceService();
                SforceService t = new SforceService();
                

                Client.Url = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.URL;

				_loginResult = Client.login(UserName, Password);
			}
			catch (SoapException ex)
			{
				UnityResolver.UnityContainer.Resolve<ILogger>().LogEvent(() =>
					Config.AppEvents.GainWinServicesExactTarget.ExactTargetInformation,
					"SalesForce SoapException");

				throw new ApiException("SalesForce SoapException", ex);
			}
			catch (Exception ex)
			{
				UnityResolver.UnityContainer.Resolve<ILogger>().LogEvent(() =>
					Config.AppEvents.GainWinServicesExactTarget.ExactTargetInformation,
					"SalesForce Exception");

				throw new ApiException("SalesForce Exception", ex);
			}
		}
예제 #4
0
        public bool Authenticate()
        {
            binding = new SforceService();
            LoginResult LResult = new LoginResult();
            try
            {
                LResult = binding.login(UserName, Password + SecurityToken);
            }
            catch (SoapException ex)
            {
                logger.Log(NLog.LogLevel.Error, ex.Message);
                return false;
            }
            if (LResult.passwordExpired)
            {
                return false;
            }

            //Change the binding to the new endpoint
            binding.Url = LResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            binding.SessionHeaderValue = new SessionHeader();
            binding.SessionHeaderValue.sessionId = LResult.sessionId;
            GetUserInfoResult userInfo = LResult.userInfo;

            return true;
        }
예제 #5
0
        public static void LoginWCF(string userName, string userPWD)
        {
            //登陆wcf
            using (WcfTcpClient<IMemberRetister> client = factory.CreateClient<IMemberRetister>())
            {
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.UserName = userName;
                loginInfo.UserPWD = "123456";

                LoginResult result = new LoginResult();
                loginInfo.IP = "192.168.1.1";
                loginInfo.Url = "";
                if (loginInfo.Url.Length > 300)
                {
                    loginInfo.Url = loginInfo.Url.Substring(0, 250);
                }
                if (string.IsNullOrEmpty(loginInfo.SubUserName))
                {
                    result = client.Channel.Login(loginInfo);
                }
                else
                {
                    result = client.Channel.Login(loginInfo, true);
                }
            }
        }
예제 #6
0
파일: FBAdapter.cs 프로젝트: mvladk/dp2012
        /// <summary>
        /// Logges in to facebook API
        /// </summary>
        public void Login()
        {
            this.m_loginResult = FacebookService.Login(
                "229916837130733",
                "user_about_me",
                "friends_about_me",
                "publish_stream",
                "user_events",
                "read_stream",
                "user_status", // this is instead of the 'user_checkins' permission, as desricbed here: http://developers.facebook.com/bugs/170251059758531
                "user_photo_video_tags",
                "friends_photo_video_tags",
                "user_photos",
                "friends_photos",
                "user_videos",
                "friends_videos",
                "offline_access");

            //// this.m_loginResult = FBAdapter.Connect(@"AAADRG69nse0BADt5k0PRb8IxIEQRLZBVk1hro195rbpT5U8HyOkt2Y0sd9WUwIjZATbwzO8uUpfmUueLiSci0qCKXGi4ySGy1k1PLxcwZDZD");

            if (string.IsNullOrEmpty(this.m_loginResult.ErrorMessage))
            {
                this.m_loggedInUser = this.m_loginResult.LoggedInUser;
                FacebookService.s_CollectionLimit = 100;
            }
            else
            {
                throw new Exception(this.m_loginResult.ErrorMessage);
            }
        }
예제 #7
0
    private void FixedUpdate()
    {
        // Unity cannot handle access from other thread
        // Easey fix by putting output in update
        // SO that it will be called on main unity thread

        if (_result == LoginResult.UPnPFailed)
        {
            _result = LoginResult.None;
            _errorOutput.ShowError("Failed to load UPnP, this must be enabled on the router to play.", 0.5f, 10f);
        }
        else if (_result == LoginResult.UPnPLoaded)
        {
            _result = LoginResult.None;
            BeginConnect();
        }
        else if (_result == LoginResult.ConnectionFailed)
        {
            _result = LoginResult.None;
            _errorOutput.ShowError("Failed to connect.");
            _reconnectTimer = -1f;
        }
        else if (_result == LoginResult.Connected)
        {
            _result = LoginResult.None;
            _errorOutput.ShowError("Securing connection...");
        }
        else if (_result == LoginResult.ConnectionSecured)
        {
            _result = LoginResult.None;
            _errorOutput.ShowError("Connection established.");
        }
        else if (_result == LoginResult.FailedToLogin)
        {
            _result = LoginResult.None;
            _errorOutput.ShowError("Invalid credentials.");
        }
        else if (_result == LoginResult.LogedIn)
        {
            _result = LoginResult.None;
            _errorOutput.ShowError("Welcome " + _session.ServerConnection.UserName);
            _mainMenu.Show(this);
        }

        if (!_session.ServerConnection.IsConnected && _reconnectTimer < _reconnectInterval)
        {
            _reconnectTimer += Time.deltaTime;
            int currentCountDown = (int)Mathf.Floor(_reconnectInterval - _reconnectTimer);

            if (_reconnectTimer >= _reconnectInterval)
            {
                BeginConnect();
            }
            else if (currentCountDown != _reconnectCountdown && currentCountDown < _reconnectInterval)
            {
                _reconnectCountdown = currentCountDown;
                _errorOutput.ShowError("Connecting in " + _reconnectCountdown.ToString(), 0.4f, 0.4f);
            }
        }
    }
예제 #8
0
파일: MainForm.cs 프로젝트: hugebdu/dp_ex2
 public MainForm(LoginResult i_LoginResult)
 {
     m_User = i_LoginResult.LoggedInUser;
     InitializeComponent();
     initializeTimer();
     initializeFavoritesManager();
 }
        public static bool TryToLogIn()
        {
            s_LoginResult = FacebookService.Login("909882489077378", "user_birthday", "email", "user_hometown", "user_about_me", "user_photos", "publish_actions", "user_status", "user_tagged_places", "read_stream", "user_groups", "user_friends");//, "user_about_me", "user_friends", "publish_actions", "user_events", "user_posts", "user_photos", "user_birthday",
                                                                                                                                                                                                                                                      // "user_status", "read_stream", "user_posts", "user_birthday", "email", "user_hometown", "user_about_me", "user_photos", "publish_actions", "user_status", "user_tagged_places", "read_stream", "user_groups", "user_friends");

            return IsConnected;
        }
 private void loginUser(LoginResult loginResult)
 {
     if (string.IsNullOrEmpty(loginResult.ErrorMessage))
     {
         LoggedInUser = loginResult.LoggedInUser;
     }
 }
 private void logAndGoToMainView(LoginResult result)
 {
     m_LoggedInUser = result.LoggedInUser;
     FacebookSingleton.Instance.LoginUser = m_LoggedInUser;
     m_MainView = new MainView();
     m_MainView.Show();
     this.Close();
 }
 /// ------------------------------------------------------------------------------------------------------------------------    
 /// <summary>
 /// Führt ein Login durch und öffnet je nach ergebnis den Checkdialog
 /// </summary>
 /// <returns>DialogResult basierend auf dem Ergebnis des Logins</returns>
 public DialogResult ShowCheckDialog()
 {
     loginrslt = Database.DatabaseLogin();
     if (loginrslt == LoginResult.Successfull)
         return DialogResult.OK;
     CheckRequirements();
     return ShowDialog();
 }
 private void btnStart_Click(object sender, EventArgs e)
 {
     loginrslt = Database.DatabaseLogin();
     if (loginrslt.Equals(LoginResult.Successfull))
         DialogResult = DialogResult.OK;
     else
         CheckRequirements();
 }
예제 #14
0
        public static DogBuffer WriteLoginResult(LoginResult loginResult)
        {
            var writer = new PacketWriter();
            writer.SetNetCode((ushort)OpCode.LoginResult);
            writer.Write((int)loginResult);

            return writer.GetBuffer();
        }
예제 #15
0
 public LoginResult Post([FromBody] Models.User user)
 {
     LoginResult result = new LoginResult();
     if (!string.IsNullOrEmpty(user.UserID) && !string.IsNullOrEmpty(user.UserPass)) {
         result.code = 1;
         result.msg = "登录成功";
     }
     else {
         result.msg = "用户名和密码不能为空";
     }
     return result;
 }
예제 #16
0
파일: Send.cs 프로젝트: aura-project/aura
		/// <summary>
		/// Sends (negative) LoginR to client.
		/// </summary>
		/// <param name="client"></param>
		/// <param name="result"></param>
		public static void LoginR_Fail(LoginClient client, LoginResult result)
		{
			var packet = new Packet(Op.LoginR, MabiId.Login);
			packet.PutByte((byte)result);
			if (result == LoginResult.SecondaryFail)
			{
				packet.PutInt(12);
				packet.PutByte(1); // TODO: Number of fail attempts
			}

			client.Send(packet);
		}
예제 #17
0
 public void callback(LoginResult result)
 {
     if (result.code == 0)
     {
         tips.text = "登录成功!";
         Instantiate(Resources.Load("prefabs/Scene"));
         Destroy(gameObject);
     }
     else
     {
         tips.text = "登录失败!" + result.code;
     }
 }
 private void OnLoginSuccess(LoginResult result)
 {
     string advertisingIdType, advertisingIdValue;
     bool disableAdvertising = false;
     PlayFabClientAPI.GetAdvertisingId(out advertisingIdType, out advertisingIdValue, ref disableAdvertising);
     callStatus = string.Format("PlayFab Authentication Successful!\n"
         + "Player ID: " + result.PlayFabId) + "\n"
         + "advertisingIdType: " + advertisingIdType + "\n"
         + "advertisingIdValue: " + advertisingIdValue + "\n"
         + "disableAdvertising: " + disableAdvertising + "\n"
         + "from: " + result.CustomData;
     Debug.Log(callStatus);
 }
예제 #19
0
        public void Login()
        {
            lock (sr_Lock)//singelton
            {
                m_LoginResult = FacebookService.Login("1450160541956417",
                "user_about_me", "user_friends", "publish_actions", "user_events", "user_posts", "user_photos",
                "user_status", "publish_pages");
            }

            if (IsLoggedIn())
            {
                m_LoggedInUser = m_LoginResult.LoggedInUser;
            }
        }
예제 #20
0
		public static void LoginR(MsgrClient client, LoginResult result)
		{
			var packet = new Packet(Op.Msgr.LoginR, 0);
			packet.PutInt((int)result);
			if (result == LoginResult.Okay)
			{
				packet.PutInt(client.User.Id);
				packet.PutString(client.User.FullName);
				packet.PutString(client.User.Nickname);
				packet.PutUInt((uint)client.User.ChatOptions);
				packet.PutByte((byte)client.User.Status);
			}

			client.Send(packet);
		}
예제 #21
0
		public static void LoginR(MsgrClient client, LoginResult result)
		{
			var packet = new Packet(Op.Msgr.LoginR, 0);
			packet.PutInt((int)result);
			if (result == LoginResult.Okay)
			{
				packet.PutInt(client.Contact.Id);
				packet.PutString(client.Contact.FullName);
				packet.PutString("");
				packet.PutUInt(0x80000000);
				packet.PutByte(0x10);
			}

			client.Send(packet);
		}
예제 #22
0
        public void start(LoginResult login, string DbServer, DeviceType devType)
        {
            int discId;
            if (login.discussion != null)
                discId = login.discussion.Id;
            else
                discId = -1;

            var actorName = login.person != null ? login.person.Name : "moderator";
            var actorDbId = login.person != null ? login.person.Id : 0;

            clienRt = new ClientRT(discId,
                                   DbServer,
                                   actorName,
                                   actorDbId,
                                   devType);

            rtTimer = new DispatcherTimer();
            rtTimer.Tick += OnRtServiceTick;
            rtTimer.Interval = TimeSpan.FromMilliseconds(5);
            rtTimer.Start();
        }
예제 #23
0
        /// <summary>
        /// Busca un usuario con autenticacion 
        /// Returna como parametro el resultado de loging
        /// </summary>
        /// <param name="userName">nombre de loging de usuario</param>
        /// <param name="password">password</param>
        /// <param name="loginResult">resultado de loging</param>
        /// <returns>DirectoryEntry</returns>
        DirectoryEntry User_Get(string userName, string password,out LoginResult loginResult)
        {

            DirectoryEntry searchRoot_DE = GetImpersonate_SearchRoot_DE();

            DirectoryEntry userDirectoryEntry = null;
            loginResult = LoginResult.LOGIN_OK;
            SearchResult result = ADHelper.User_Get_Result(userName, searchRoot_DE);

            //Si esl resultado de busqueda en nodes es nulo el usuario no exisate en el dominio
            if (result == null)
            {
                loginResult = LoginResult.LOGIN_USER_DOESNT_EXIST;
                return null;
            }

            //PasswordExpired
            if (ADHelper.GetProperty(result, ADProperties.PWDLASTSET) == "0")
            {
                loginResult = LoginResult.ERROR_PASSWORD_MUST_CHANGE;
                return null;
            }




            //string str = EnlistValue(results);
            //si result no es nulo se puede crear una DirectoryEntry
            if (result != null)
                userDirectoryEntry = new DirectoryEntry(result.Path, userName, password);

            //Intenta obtener una propiedad para determinar si el usuario se logueo con clave correcta o no.-
            try
            {
                int userAccountControl = Convert.ToInt32(ADHelper.GetProperty(userDirectoryEntry, ADProperties.USERACCOUNTCONTROL));
            }
            catch (TechnicalException te)
            {
                if (te.ErrorId == "4101")
                {
                    loginResult = LoginResult.LOGIN_USER_OR_PASSWORD_INCORRECT;
                    return userDirectoryEntry;
                }
                if (te.ErrorId == "4100")
                {
                    loginResult = LoginResult.ERROR_SERVER_IS_NOT_OPERATIONAL;
                    return userDirectoryEntry;
                }
            }

            if (ADHelper.User_IsAccountActive(userDirectoryEntry) == false)
            {
                loginResult = LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
                return userDirectoryEntry;
            }

            if (ADHelper.User_IsAccountLockout(userDirectoryEntry))
            {
                loginResult = LoginResult.LOGIN_USER_ACCOUNT_LOCKOUT;
                return userDirectoryEntry;
            }


            return userDirectoryEntry;
        
        }
예제 #24
0
        public async Task<string> ajax_Login(LoginViewModel model)
        {
            var userManager = UserManager;

            LoginResult getLoginResult = new LoginResult();

            //if (!ModelState.IsValid)
            //{
            //    getLoginResult.result = false;
            //    getLoginResult.message = "資訊不完整";
            //    return defJSON(getLoginResult);
            //}

            #region 驗證碼檢查程序

#if DEBUG
            getLoginResult.vildate = true;
#else
            //if (string.IsNullOrEmpty(Session["CheckCode"].ToString()))
            //{
            //    Session["CheckCode"] = Guid.NewGuid();
            //    getLoginResult.result = false;
            //    getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
            //    return defJSON(getLoginResult);
            //}

            //getLoginResult.vildate = Session["CheckCode"].Equals(model.validate) ? true : false;
            ValidateResponse Validate = ValidateCaptcha(model.validate, "6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx");//正式:6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx,Demo:6LfOXBcTAAAAAOqEElEieoCCTQmHAmtRfnqSS141
            getLoginResult.vildate = Validate.Success;
            
#endif
            if (!getLoginResult.vildate)
            {
                //Session["CheckCode"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                getLoginResult.result = false;
                getLoginResult.message = Resources.Res.Log_Err_googleValideNotEquel;
                return defJSON(getLoginResult);
            }
            #endregion

            #region 帳密碼檢查

            var result = await SignInManager.PasswordSignInAsync(model.account, model.password, model.rememberme, shouldLockout: false);

            if (result == SignInStatus.Failure)
            {
                getLoginResult.result = false;
                getLoginResult.message = Resources.Res.Login_Err_Password;
                return defJSON(getLoginResult);
            }

            getLoginResult.result = true;
            var item = await userManager.FindByNameAsync(model.account);

            if (isTablet)
            {
                getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);  //是行動裝置
            }
            else
            {
                //不是行動裝置
                var get_user_roles_id = item.Roles.Select(x => x.RoleId);

                ApplicationDbContext context = ApplicationDbContext.Create();
                var roleManage = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                var get_user_roles_name = roleManage.Roles.Where(x => get_user_roles_id.Contains(x.Id)).Select(x => x.Name);

                if (get_user_roles_name.Contains("Admins") || get_user_roles_name.Contains("Managers"))
                {
                    getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);
                }
                else
                {
                    getLoginResult.url = Url.Content("~/Active/Sales/PersonalInfo");
                }
            }

            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_UserName, item.UserName));
            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_LastLogin, DateTime.Now.ToString("yyyy-MM-dd")));
            #endregion

            //語系使用
            HttpCookie WebLang = Request.Cookies[CommWebSetup.WebCookiesId + ".Lang"];
            //WebLang.Value = model.lang;
            Response.Cookies.Add(WebLang);

            try
            {
                var db = getDB0();

                var item_department = await db.Department.FindAsync(item.department_id);

                Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentId, item.department_id.ToString()));
                //Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentName, item_department.department_name));
                Response.Cookies.Add(new HttpCookie("user_login", Server.UrlEncode(EncryptString.desEncryptBase64("N"))));
                var item_lang = db.i_Lang
                    .Where(x => x.lang == WebLang.Value)
                    .Select(x => new { x.area })
                    .Single();

                ViewData["lang"] = item_lang.area;
                //Response.Cookies.Add(new HttpCookie(CommWebSetup.WebCookiesId + ".IsAuthorized", "OK"));//CKFinder
                Session["IsAuthorized"] = true;//ckfinder用
                db.Dispose();
            }
            catch (Exception ex)
            {
                getLoginResult.result = false;
                getLoginResult.message = ex.Message;
                return defJSON(getLoginResult);
            }

            return defJSON(getLoginResult);
        }
	// callback on successful LoginToPlayFab request 
	void OnLoginSuccess(LoginResult result)
	{
		Debug.Log(result.PlayFabId);
		StartCoroutine(GetUserStats());
		this.playfabId = result.PlayFabId;
		GetPhotonAuthenticationTokenRequest request = new GetPhotonAuthenticationTokenRequest();
		request.PhotonApplicationId = photonComponent.AppId.Trim();
		// get an authentication ticket to pass on to Photon 
		PlayFabClientAPI.GetPhotonAuthenticationToken(request, OnPhotonAuthenticationSuccess, OnPlayFabError);
	}
예제 #26
0
	void OnLoginCallback (LoginResult result)
	{
		Debug.Log(string.Format("Login Successful. Welcome Player:{0}!", result.PlayFabId));
		Debug.Log(string.Format("Your session ticket is: {0}", result.SessionTicket));
		Debug.Log(string.Format("Your friend referral code is: {0}", result.PlayFabId));
		this.myReferralCode.text = string.Format("REFERRAL CODE [{0}]", result.PlayFabId);
		GetInventory();
	}
예제 #27
0
        public async Task<string> ajax_MemberLogin(MemberLogin obj)
        {
            LoginResult rAjaxResult = new LoginResult();
            if (!ModelState.IsValid)
            {
                rAjaxResult.result = false;
                rAjaxResult.message = "資訊不完整";
                return defJSON(rAjaxResult);
            }

            #region 驗證碼檢查程序
            if (string.IsNullOrEmpty(Session["MemberLogin"].ToString()))
            {
                Session["MemberLogin"] = Guid.NewGuid();
                rAjaxResult.result = false;
                rAjaxResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                return defJSON(rAjaxResult);
            }

            rAjaxResult.vildate = Session["MemberLogin"].Equals(obj.validate) ? true : false;
            //#if DEBUG
            //            rAjaxResult.vildate = true;
            //#endif
            if (!rAjaxResult.vildate)
            {
                Session["MemberLogin"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                rAjaxResult.result = false;
                rAjaxResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                return defJSON(rAjaxResult);
            }
            #endregion
            var db0 = getDB0();
            obj.pwd = HttpUtility.UrlEncode(EncryptString.desEncryptBase64(obj.pwd));
            var get_user = db0.Sales.Where(x => x.account == obj.act & x.password == obj.pwd).FirstOrDefault();

            if (get_user != null)
            {
                #region 前台_會員登入用cookie
                Response.Cookies.Add(new HttpCookie(CommWebSetup.WebCookiesId + ".member_id", Server.UrlEncode(EncryptString.desEncryptBase64(get_user.sales_no))));
                Response.Cookies.Add(new HttpCookie(CommWebSetup.WebCookiesId + ".member_name", Server.UrlEncode(get_user.sales_name)));
                //設定過期時間1天
                //Response.Cookies[CommWebSetup.WebCookiesId + ".member_id"].Expires = DateTime.Now.AddDays(1);
                //Response.Cookies[CommWebSetup.WebCookiesId + ".member_name"].Expires = DateTime.Now.AddDays(1);
                #endregion
                #region 後台_會員登入用cookie
                Session["CheckCode"] = "jcin";


                #region 不同等級(rank)用不同帳號登入
                string login_model = string.Empty;
                if (get_user.rank == (int)SalesRankState.managementOffice)
                {//管理處
                    login_model = await ajax_Login(new LoginViewModel()
                    {
                        account = "ManagementOffice",
                        password = "******",
                        lang = "zh-TW",
                        rememberme = false,
                        validate = "jcin"
                    });
                }
                else if (get_user.rank == (int)SalesRankState.operationsCenter)
                {//營運中心
                    login_model = await ajax_Login(new LoginViewModel()
                    {
                        account = "OperationsCenter",
                        password = "******",
                        lang = "zh-TW",
                        rememberme = false,
                        validate = "jcin"
                    });
                }
                else if (get_user.rank == (int)SalesRankState.manager)
                {//經理人
                    login_model = await ajax_Login(new LoginViewModel()
                    {
                        account = "SalesManager",
                        password = "******",
                        lang = "zh-TW",
                        rememberme = false,
                        validate = "jcin"
                    });
                }
                else
                {//共享會員(一般會員)
                    login_model = await ajax_Login(new LoginViewModel()
                    {
                        account = "user",
                        password = "******",
                        lang = "zh-TW",
                        rememberme = false,
                        validate = "jcin"
                    });
                }
                #endregion
                LoginResult trnResult = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginResult>(login_model);
                if (trnResult.result)
                {
                    Response.Cookies.Add(new HttpCookie("user_login", Server.UrlEncode(EncryptString.desEncryptBase64("Y"))));
                }

                #endregion

                rAjaxResult.result = true;
                rAjaxResult.url = Url.Content("~");
                return defJSON(rAjaxResult);
            }
            else
            {
                rAjaxResult.result = false;
                rAjaxResult.message = "帳號或密碼錯誤 請重新輸入";
                return defJSON(rAjaxResult);
            }
        }
        public async Task<string> ajax_Login(LoginViewModel model)
        {
            var userManager = UserManager;

            LoginResult getLoginResult = new LoginResult();

            if (ModelState.IsValid)
            {
                var item = await userManager.FindAsync(model.account, model.password);
                if (item != null)
                {
                    if (String.IsNullOrEmpty(Session["CheckCode"].ToString()))
                    {
                        Session["CheckCode"] = Guid.NewGuid();
                        getLoginResult.result = false;
                        getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                        return defJSON(getLoginResult);
                    }

                    getLoginResult.vildate = Session["CheckCode"].Equals(model.img_vildate) ? true : false;
#if DEBUG
                    getLoginResult.vildate = true;
#endif
                    if (!getLoginResult.vildate)
                    {
                        Session["CheckCode"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                        getLoginResult.result = false;
                        getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                        return defJSON(getLoginResult);
                    }
                    //Session.RemoveAll();
                    await SignInAsync(item, model.rememberme);
                    getLoginResult.result = true;
                    getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);
                    //Session.Timeout = 40;
                    //Session[CommWebSetup.Session_UserId] = item.Id;
                    Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_UserName, item.UserName));
                    Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_LastLogin, DateTime.Now.ToString()));

                    //語系使用
                    HttpCookie WebLang = Request.Cookies[CommWebSetup.WebCookiesId + ".Lang"];
                    WebLang.Value = model.lang;
                    Response.Cookies.Add(WebLang);

                    var db = getDB0();

                    var item_department = await db.Department.FindAsync(item.department_id);

                    Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentId, item.department_id.ToString()));
                    Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentName, item_department.department_name));

                    var item_lang = db.i_Lang
                        .Where(x => x.lang == WebLang.Value)
                        .Select(x => new { x.area })
                        .Single();

                    ViewData["lang"] = item_lang.area;
                    db.Dispose();
                    Session["IsAuthorized"] = true;
                }
                else
                {
                    getLoginResult.result = false;
                    getLoginResult.message = Resources.Res.Login_Err_Password;
                }
            }
            return defJSON(getLoginResult);
        }
예제 #29
0
 public ReceivedLoginResultEventArgs(LoginResult result)
 {
     this.Result = result;
 }
예제 #30
0
        private void LoginFinished(LoginResult success, DateTime BanEnd, string message)
        {
            if (success == LoginResult.WaitingForResponse)
            {
                LoginTimer = new Timer((object o) =>
                {
                    LoginFinished(LoginResult.Failure, DateTime.Now, "Please try again.");
                }, null, 10000, 10000);
                return;
            }
            Trace.TraceInformation("Login finished.");
            if (LoginTimer != null)
            {
                LoginTimer.Dispose();
                LoginTimer = null;
            }
            Dispatcher.Invoke((Action)(() =>
            {
                Program.lobbyClient.OnCaptchaRequired -= lobbyClient_OnCaptchaRequired;
                Program.LauncherWindow.Closing -= LauncherWindow_Closing;
                isLoggingIn = false;
                Stop_Spinning();
                if(success == LoginResult.Success)
                {
                    if (cbSavePassword.IsChecked == true)
                    {
                        Registry.WriteValue("Password", passwordBox1.Password.Encrypt());
                    }
                    else
                        Registry.WriteValue("Password", "");
                    Registry.WriteValue("E-Mail", textBox1.Text);
                    Registry.WriteValue("Nickname", Program.lobbyClient.Me.DisplayName);

                    Program.ClientWindow = new Main();
                    Program.ClientWindow.Show();
                    Application.Current.MainWindow = Program.ClientWindow;
                    Program.LauncherWindow.Close();
                }
                else if(success == LoginResult.Banned)
                {
                    DoErrorMessage("You have been banned until " + BanEnd.ToShortTimeString() + " on " + BanEnd.ToShortDateString());
                }
                else if(success == LoginResult.Failure)
                {
                    DoErrorMessage("Login Failed: " + message);
                }
            }), new object[0] { });
        }