コード例 #1
0
ファイル: LoginState.cs プロジェクト: kofight/CapsUnity
    public override void DoInitState()
    {
		base.DoInitState();
		
		Instance = this;

        if (UIWindowManager.Singleton.GetUIWindow<UIMap>() == null)
        {
            UIWindowManager.Singleton.CreateWindow<UIMainMenu>(UIWindowManager.Anchor.BottomLeft);
            UIWindowManager.Singleton.CreateWindow<UIQuitConfirm>();
            UIWindowManager.Singleton.CreateWindow<UIStageInfo>();
            UIWindowManager.Singleton.CreateWindow<UIMap>();
            UIWindowManager.Singleton.CreateWindow<UINoMoreHearts>();
            UIWindowManager.Singleton.CreateWindow<UIHowToPlay>();
            UIWindowManager.Singleton.CreateWindow<UIWindow>("UILoading", UIWindowManager.Anchor.Center);
            UIWindowManager.Singleton.CreateWindow<UIDialog>(UIWindowManager.Anchor.Bottom);
            UIWindowManager.Singleton.CreateWindow<UIStore>();
            //UIWindowManager.Singleton.CreateWindow<UIWait>();
            UIWindowManager.Singleton.CreateWindow<UIPurchaseNotEnoughMoney>();
            UIWindowManager.Singleton.CreateWindow<UIMessageBox>();
            UIWindowManager.Singleton.GetUIWindow<UIMap>().RefreshButtons();
        }

        if (GlobalVars.UseMusic)
        {
            UIToolkits.PlayMusic(CapsConfig.CurAudioList.MapMusic);
        }

        if (UIWindowManager.Singleton.GetUIWindow<UIMap>().Visible)
        {
            CurFlow = TLoginFlow.LoginFlow_Map;         //切换流程到显示地图
        }
    }
コード例 #2
0
ファイル: LoginState.cs プロジェクト: hiyijia/CapsUnity
    public override void DoInitState()
    {
		base.DoInitState();
		
		Instance = this;
		
        //UIWindowManager.Singleton.CreateWindow<UISplash>();
        //UIWindowManager.Singleton.CreateWindow<UIHowToPlay>();
        
        //UIWindowManager.Singleton.CreateWindow<UIOption>();

        if (UIWindowManager.Singleton.GetUIWindow<UIMap>() == null)
        {
            UIWindowManager.Singleton.CreateWindow<UIMainMenu>(UIWindowManager.Anchor.BottomLeft);
            UIWindowManager.Singleton.CreateWindow<UIQuitConfirm>();
            UIWindowManager.Singleton.CreateWindow<UIStageInfo>();
            UIWindowManager.Singleton.CreateWindow<UIMap>();
            UIWindowManager.Singleton.CreateWindow<UIBuyHeart>();
            UIWindowManager.Singleton.CreateWindow<UIWindow>("UILoading", UIWindowManager.Anchor.Center);

            UIWindowManager.Singleton.GetUIWindow<UIMap>().RefreshButtons();
        }
        
        //UIWindowManager.Singleton.GetUIWindow<UISplash>().ShowWindow();

        if (GlobalVars.UseMusic)
        {
            UIToolkits.PlayMusic(CapsConfig.CurAudioList.MapMusic);
        }

        if (UIWindowManager.Singleton.GetUIWindow<UIMap>().Visible)
        {
            CurFlow = TLoginFlow.LoginFlow_Map;         //切换流程到显示地图
        }
    }
コード例 #3
0
 public void SetState(LoginState state)
 {
     switch (state)
     {
         case LoginState.LoggedOut:
             InvokeGUI(() =>
                 {
                     tsmi_ConnectToServer.Enabled = true;
                     tsmi_Disconnect.Enabled = false;
                     lock (sync)
                     {
                         lv_Extension.Items.Clear();
                         lv_OutsideLine.Items.Clear();
                     }
                     lv_Files.Items.Clear();
                 });
             break;
         case LoginState.LoggingIn:
         case LoginState.LoggedIn:
             InvokeGUI(() =>
                 {
                     tsmi_ConnectToServer.Enabled = false;
                     tsmi_Disconnect.Enabled = true;
                 });
             break;
     }
 }
コード例 #4
0
 /// <summary>
 /// Resets the state of the SASL mechanism.
 /// </summary>
 /// <remarks>
 /// Resets the state of the SASL mechanism.
 /// </remarks>
 public override void Reset()
 {
     state     = LoginState.Auth;
     challenge = null;
     response  = null;
     cnonce    = null;
     base.Reset();
 }
コード例 #5
0
ファイル: LoginController.cs プロジェクト: imclab/Line-Art
    public void Connect()
    {
        PhotonConnection.Instance.Connect();

        loginScreen.SetActive(false);
        ShowPopup();

        state = LoginState.Connecting;
    }
コード例 #6
0
ファイル: Room.cs プロジェクト: sxtgyrq/VRPGame
        internal static async Task <State> setState(State s, WebSocket webSocket, LoginState ls)
        {
            s.Ls = ls;
            var msg      = Newtonsoft.Json.JsonConvert.SerializeObject(new { c = "setState", state = Enum.GetName(typeof(LoginState), s.Ls) });
            var sendData = Encoding.UTF8.GetBytes(msg);
            await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), WebSocketMessageType.Text, true, CancellationToken.None);

            return(s);
        }
コード例 #7
0
ファイル: UILogin.cs プロジェクト: Tristyn/if_source
    void OnLoginChanged(LoginState loginState)
    {
        SetState(loginState);

        if (loginState.playfabLoginState == PlayfabLoginState.LoggedIn)
        {
            MenuController.instance.Pop(MenuState.LoginMenu);
        }
    }
コード例 #8
0
        public void SessionOnLoginStateChanged(LoginState loginState)
        {
            //Trace.WriteLine("login state changed: " + loginState);

            if (loginState == LoginState.Success)
            {
                _authPage.SetConnectionConfigForm(false); // disable form input controls

                if (_networkHandler.IsDefaultUser)
                {
                    //must change password
                    _authPage.SetDefaultPasswordText();
                    SetOwnerChangePassVisibility(true);
                    _log.StatusMessage("Please supply a new password the default user ADMIN!");
                    _accountsHandler.OwnerPasswordSet += () =>
                    {
                        // successful default password change
                        _authPage.OwnerPasswordChanged();
                        SetEnableAllTabs(true);
                        FocusTab(serverInfoTab); // initially take the user to server info
                        _serverInfoPage.SendServerInfoGet();
                    };
                }
                else
                {
                    // default case = let the user select the next steps = unlock interface
                    SetEnableAllTabs(true);
                    _authPage.SetBackgroundColorsToDefault();
                }
            }
            else
            {
                FocusTab(authTab);
                _authPage.ResetAll();
                SetEnableAllTabs(false);
                SetEnabledTabByName("authTab", true);
                SetEnabledTabByName("localServerTab", true);

                if (loginState == LoginState.NoSuchUser)
                {
                    // some warning gui things
                    _authPage.ReactToUnsuccessfulLogin();
                }



                if (loginState == LoginState.Disconnected)
                {
                    _log.Log("Disconnected.");
                }
            }

            _authPage.SetTitleByLoginState();
            _accountsHandler.Reset();
            _accountsPage.Reset();
        }
コード例 #9
0
        protected void SetUIState(LoginState state)
        {
            // reset the result label
            LoginResult.Field.Text = "";

            switch (state)
            {
            case LoginState.Out:
            {
                UserNameField.Field.Enabled = true;
                PasswordField.Field.Enabled = true;
                LoginButton.Enabled         = true;
                CancelButton.Enabled        = true;
                RegisterButton.Hidden       = false;
                RegisterButton.Enabled      = true;

                LoginButton.SetTitle(LoginStrings.LoginButton, UIControlState.Normal);

                break;
            }

            case LoginState.Trying:
            {
                FadeLoginResult(false);
                BlockerView.Show(null);
                BlockerView.BringToFront( );

                UserNameField.Field.Enabled = false;
                PasswordField.Field.Enabled = false;
                LoginButton.Enabled         = false;
                CancelButton.Enabled        = false;
                RegisterButton.Enabled      = false;

                LoginButton.SetTitle(LoginStrings.LoginButton, UIControlState.Normal);

                break;
            }

            // Deprecated state
            case LoginState.In:
            {
                UserNameField.Field.Enabled = false;
                PasswordField.Field.Enabled = false;
                LoginButton.Enabled         = true;
                CancelButton.Enabled        = true;
                RegisterButton.Hidden       = true;
                RegisterButton.Enabled      = false;

                LoginButton.SetTitle("Logout", UIControlState.Normal);

                break;
            }
            }

            State = state;
        }
コード例 #10
0
        private async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            OAuth2Authenticator authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }
            //           User user = new User ( );
            //           string userJson = "";
            string user = "";

            if (e.IsAuthenticated)
            {
                StoringDataIntoCacheAsync(_provider, e.Account.Serialize());
                switch (_provider)
                {
                case Constants.VK:
                    //    Authentcation ( );
                    break;

                case Constants.FACEBOOK:
                    break;

                /*       case Constants.TWITTER:
                 *         TwitterAuth (sender, e);
                 *         break;*/
                case Constants.MICROSOFT:
                    user = await FromMicrosoftAsync(endpoint, e.Account.Properties["access_token"]);

                    break;

                default:
                    user = await FromGoolgeAsync(endpoint, e.Account);

                    break;
                }
                ISharedPreferences       prefs  = PreferenceManager.GetDefaultSharedPreferences(this);
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("name", user);
                editor.Commit();
                Toast.MakeText(this, "User " + user, ToastLength.Long).Show();
                loginState            = LoginState.Success;
                authButton.Visibility = ViewStates.Visible;
                editText.Text         = user;
                editText.Focusable    = false;
                return;
            }
            else
            {
                Toast.MakeText(this, Constants.FAIL_AUTH, ToastLength.Short).Show();
                loginState = LoginState.Failed;
                return;
            }
        }
コード例 #11
0
 /// <summary>
 /// Constructor
 /// </summary>
 public HomeController()
 {
     //IsDevMode = true;
     PlatformSelection = 0;
     State             = PlatformState.VIEW;
     _loginState       = LoginState.NONE;
     AppInfo           = new AppData();
     LoginInfo         = new LoginCredentials();
     GetLatestNews();
 }
コード例 #12
0
        protected override void OnDisappearing()
        {
            App.Credentials = App.CredentialsManager.GetAllCredentials();

            usernameEntry.Text = "";
            passwordEntry.Text = "";
            EntriesVisible(false);
            loginState = LoginState.ServerAutoLogin;
            base.OnDisappearing();
        }
コード例 #13
0
        protected void SetState(LoginState state)
        {
            var prev = LoginState;

            LoginState = state;
            if (prev != state || state == LoginState.LoggedIn)
            {
                Hub.Instance.SendMessage("OnLoginStateChanged", state);
            }
        }
コード例 #14
0
    private void Start()
    {
        state = LoginState.Instantiated;

        LoginWithCustomIDRequest request = new LoginWithCustomIDRequest {
            CustomId = playerGUID, CreateAccount = true
        };

        PlayFabClientAPI.LoginWithCustomID(request, onLoginSuccess, onLoginFailure);
    }
コード例 #15
0
        private void button_home_Click(object sender, RoutedEventArgs e)
        {
            Globals.loginAccount     = null;
            this.num_screen.Text     = "";
            this.login_label.Content = request_acc_num_label;
            this.loginState          = LoginState.ACCOUNT_NUM;
            NavigationService service = NavigationService.GetNavigationService(this);

            service.GoBack();
        }
コード例 #16
0
        private LoginState GetCurrentLoginState()
        {
            LoginState currentState = LoginState.LOGGED_OUT;

            if (m_connectedDevicesManager.Accounts.Count > 0)
            {
                currentState = m_connectedDevicesManager.Accounts[0].Type == Microsoft.ConnectedDevices.ConnectedDevicesAccountType.AAD ? LoginState.LOGGED_IN_AAD : LoginState.LOGGED_IN_MSA;
            }
            return(currentState);
        }
コード例 #17
0
        private LoginState GetCurrentLoginState()
        {
            LoginState currentState = LoginState.LoggedOut;

            if (notificationsManager.SignedInAccount != null)
            {
                currentState = notificationsManager.IsMSA ? LoginState.LoggedInMsa : LoginState.LoggedInAad;
            }
            return(currentState);
        }
コード例 #18
0
        /// <summary>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </summary>
        /// <returns>The next challenge response.</returns>
        /// <param name="token">The server's challenge token.</param>
        /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
        /// <param name="length">The length of the server's challenge.</param>
        /// <exception cref="SaslException">
        /// An error has occurred while parsing the server's challenge token.
        /// </exception>
        protected override byte[] Challenge(byte[] token, int startIndex, int length)
        {
            if (IsAuthenticated)
            {
                throw new InvalidOperationException();
            }

            if (token == null)
            {
                return(null);
            }

            var cred = Credentials.GetCredential(Uri, MechanismName);

            switch (state)
            {
            case LoginState.Auth:
                if (token.Length > 2048)
                {
                    throw new SaslException(MechanismName, SaslErrorCode.ChallengeTooLong, "Server challenge too long.");
                }

                challenge = DigestChallenge.Parse(Encoding.UTF8.GetString(token));
                response  = new DigestResponse(challenge, Uri.Scheme, Uri.DnsSafeHost, cred.UserName, cred.Password);
                state     = LoginState.Final;
                return(response.Encode());

            case LoginState.Final:
                if (token.Length == 0)
                {
                    throw new SaslException(MechanismName, SaslErrorCode.MissingChallenge, "Server response did not contain any authentication data.");
                }

                var    text = Encoding.UTF8.GetString(token);
                string key, value;
                int    index = 0;

                if (!DigestChallenge.TryParseKeyValuePair(text, ref index, out key, out value))
                {
                    throw new SaslException(MechanismName, SaslErrorCode.IncompleteChallenge, "Server response contained incomplete authentication data.");
                }

                var expected = response.ComputeHash(cred.Password, false);
                if (value != expected)
                {
                    throw new SaslException(MechanismName, SaslErrorCode.IncorrectHash, "Server response did not contain the expected hash.");
                }

                IsAuthenticated = true;
                return(new byte[0]);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #19
0
        protected override void InnerRespond(string userString)
        {
            switch (this.CurrentState)
            {
            case LoginState.FirstPrompt:
                AccountObjects accounts = AccountObjects.Get();
                accountName  = userString;
                foundAccount = accounts.GetAccount(userString);     //Transition to either AccountPassword or IsNewAccount
                User.sendMessage(this.PromptMessage);
                break;

            case LoginState.AccountPassword:
                if (Account.EncryptionMethod.Compare(userString, foundAccount.Password))
                {
                    FinishLogin();
                }
                else
                {
                    User.sendMessage("That password does not match the account's password.");
                    accountName = null;     //Return to account name prompt.
                    User.sendMessage(this.PromptMessage);
                }
                break;

            case LoginState.IsNewAccount:
                if (userString.Length > 0 && userString.Substring(0, 1).ToUpper() == "Y")
                {
                    currentSubState = LoginState.NewAccountPassword;
                }
                else
                {
                    accountName = null;
                }
                User.sendMessage(this.PromptMessage);
                break;

            case LoginState.NewAccountPassword:
                foundAccount          = new Account();
                foundAccount.Name     = accountName;
                foundAccount.Password = userString;
                bool success = AccountObjects.Get().Add(foundAccount);
                if (success)
                {
                    foundAccount.Save();
                    FinishLogin();
                }
                else
                {
                    User.sendMessage("Account creation failed.");
                    Reset();
                    User.sendMessage(this.PromptMessage);
                }
                break;
            }
        }
コード例 #20
0
        void OnClientLoginRequest(IMessage msg, SessionEventArgs e, bool reLogin = false)
        {
            var        loginInfo        = msg.Obj as LoginInfo;
            LoginState clientLoginstate = LoginState.Failed;

            if (loginInfo != null)
            {
                var session = Global.GetSession(new UserSessionIdMetaData
                {
                    Account  = loginInfo.User.Account,
                    IsClient = true
                });

                if (!reLogin && session != null)
                {
                    clientLoginstate = LoginState.LoggedIn;
                }
                else
                {
                    if (reLogin && session != null)
                    {
                        session.SessionId = null;
                    }

                    try
                    {
                        clientLoginstate = _userBll.Login(loginInfo.User);
                        if (clientLoginstate == LoginState.Successed)
                        {
                            e.Session.SessionId = new UserSessionIdMetaData
                            {
                                Id           = loginInfo.User.Id,
                                Account      = loginInfo.User.Account,
                                IsClient     = true,
                                LastCalcTime = DateTime.Now,
                                UpdateInfo   = loginInfo.UpdateInfo
                            };

                            _userBll.UpdateClientLogin(new UserLoginState
                            {
                                UserId = loginInfo.User.Id,
                                ClientLastLoginIpAddress = e.Session.RemoteEndPoint.Address.ToString(),
                                ClientLastLoginTime      = DateTime.Now
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorLog(msg.Header.Type, ex);
                    }
                }
            }
            e.Session.Send(clientLoginstate, reLogin ?
                           MessageType.ClientReLoginReponse : MessageType.ClientLoginReponse);
        }
コード例 #21
0
 private void LoginResultCallback(object sender, Login session, LoginState state)
 {
     Application.Current.Dispatcher.Invoke(() =>
     {
         if (sessions.ContainsKey(session))
         {
             sessions[session].Dispose();
             sessions.Remove(session);
         }
     });
 }
コード例 #22
0
 protected virtual void OnStateChanged(LoginState state)
 {
     if (LogManager != null)
     {
         LogManager.InfoFormat("Logging state changed: state={0}", state);
     }
     if (LoginStateChanged != null)
     {
         LoginStateChanged(this, new LoginStateEventArgs(state, StartAttempt + 1, LastError));
     }
 }
コード例 #23
0
        /// <summary>
        /// Resets the state of the SASL mechanism.
        /// </summary>
        /// <remarks>
        /// Resets the state of the SASL mechanism.
        /// </remarks>
        public override void Reset()
        {
            state  = LoginState.Initial;
            client = null;
            server = null;
            salted = null;
            cnonce = null;
            auth   = null;

            base.Reset();
        }
コード例 #24
0
 private void UpdateContactingServer()
 {
     if (_webCom.PingTime >= 0 && string.IsNullOrEmpty(_webCom.NetworkError))
     {
         _loginState       = LoginState.ReadingUserInput;
         _messageText.text = "";
         _fadeComponent.FadeIn();
         EnableInput(true);
         loadingImageObject.SetActive(false);
     }
 }
コード例 #25
0
    protected override void MakeFSM()
    {
        LoginState loginState = new LoginState();

        loginState.AddTRANSITION(Transition.TRANSITION_TO_REGISTER, StateID.REGISTER);

        _FSM = new FSMSystem(this);
        _FSM.AddState(loginState);

        base.MakeFSM();
    }
コード例 #26
0
    /// <summary>
    /// Checks if login was successful
    /// </summary>
    /// <returns>true/false based on success</returns>
    public bool IsLoginSuccessful()
    {
        EnjinEditor.CurrentUser = Enjin.StartPlatform(LoginInfo.apiurl, LoginInfo.username, LoginInfo.password);

        if (EnjinEditor.CurrentUser == null)
        {
            _loginState = Enjin.LoginState;
            return(false);
        }

        return(true);
    }
コード例 #27
0
        private void OnAuthError(object sender, AuthenticatorErrorEventArgs e)
        {
            OAuth2Authenticator authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }
            Toast.MakeText(this, "Authentication error: " + e.Message, ToastLength.Short).Show();
            loginState = LoginState.Failed;
        }
コード例 #28
0
 public SessionState(LoginState loggedState, UnityUser user, ProjectRoom[] rooms)
 {
     this.loggedState      = loggedState;
     this.user             = user;
     this.rooms            = rooms;
     userIdentity          = default;
     linkShareLoggedOut    = false;
     linkSharePermission   = LinkPermission.Private;
     isInPrivateMode       = false;
     collaborationState    = CollaborationState.Disconnected;
     linkSharedProjectRoom = default;
 }
コード例 #29
0
    public GameStateManager()
    {
        gameStates = new Dictionary <GameStateType, IGameState>();

        IGameState gameState;

        gameState = new LoginState();
        gameStates.Add(gameState.GetStateType(), gameState);

        gameState = new LobbyState();
        gameStates.Add(gameState.GetStateType(), gameState);
    }
コード例 #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!LoginState.TestLogin())
        {
            return;
        }

        if (string.IsNullOrEmpty(RouteName.Value))
        {
            RouteName.Value = Request.Params["Route"];
        }

        string script = string.Format(@"
function getRouteName(){{
    return document.getElementById('{0}').value; 
}}
function getGpsField(){{
    return document.getElementById('{1}'); 
}}
function getUpdateImagesButton(){{
    return document.getElementById('{2}'); 
}}", RouteName.ClientID, TextBoxGPS.ClientID, ReloadImages.ClientID);

        ScriptManager.RegisterClientScriptBlock(
            this,
            GetType(),
            "ScriptFunctions",
            script,
            true);


        MapFrame.Attributes["src"]            = "map.aspx?EditMode=true&Route=" + RouteName.Value;
        MapFrame.Attributes["onload"]         = "frameLoaded(this);";
        UploadImageFrame.Attributes["src"]    = "UploadFile.aspx?Route=" + RouteName.Value;
        UploadImageFrame.Attributes["onload"] = "imagesUploaded(this);";
        route = DBHelper.GetRoute(RouteName.Value);

        if (!IsPostBack && route != null)
        {
            TextBoxTitle.Text         = route.Title;
            TextBoxDescription.Text   = route.Description;
            TextBoxCiclyng.Text       = route.Cycling.ToString();
            TextBoxDifficulty.Text    = route.Difficulty;
            CheckBoxPublished.Checked = !route.Draft;
            DifficultyFromString();
            mainImage = route.Image;
        }

        SetDifficulties(ClimbPanel);
        SetDifficulties(DownPanel);
        DifficultyToString();
        BuildImageControls();
    }
コード例 #31
0
 void OnLoginStateChanged(LoginState state)
 {
     switch (state)
     {
     case LoginState.LoggedIn:
     {
         State = HubState.LogginIn;
         SubSystemConnect();
     }
     break;
     }
 }
コード例 #32
0
ファイル: NdCenter.cs プロジェクト: KangLLL/century_war
 public void Login()
 {
     if (Application.platform == RuntimePlatform.IPhonePlayer)
     {
         if (Bonjour.IsLogined())
         {
             Bonjour.LoginOut();
         }
         Bonjour.Login();
         this.m_LoginState = LoginState.Logining;
     }
 }
コード例 #33
0
        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public LoginState CheckLogin(SYS_LOGIN logininfo)
        {
            LoginState state = LoginState.NoLogin;

            using (var dbcontext = DbFactory.Create())
            {
                try
                {
                    Expression <Func <SYS_LOGIN, bool> > exp = a => a.UserName == logininfo.UserName;

                    SYS_LOGIN model = dbcontext.Get(exp);

                    if (model == null)
                    {
                        //账号不存在
                        state = LoginState.AccountNoExist;
                    }
                    else
                    {
                        string inputpwd = EncryptHelper.MD5DecryptString(logininfo.UserPassword);
                        if (inputpwd == model.UserPassword)
                        {
                            if (model.State == 1)
                            {
                                //成功
                                state = LoginState.Success;
                                SaveSession(model);
                            }
                            else if (model.State == 0)
                            {
                                //未授权
                                state = LoginState.NoAuthorize;
                            }
                            else if (model.State == 2)
                            {
                                //账号锁定
                                state = LoginState.AccountLock;
                            }
                        }
                        else
                        {
                            //密码错误
                            state = LoginState.PwdError;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(string.Format("【账号】-{0},登录异常,异常信息:{1}", logininfo.UserName, ex.ToString()));
                }
            }
            return(state);
        }
コード例 #34
0
 public void SetState(LoginState state)
 {
     if (!InvokeRequired)
     {
         switch (state)
         {
             case LoginState.LoggedOut:
                 btn_Connect.Enabled = true;
                 break;
             case LoginState.LoggingIn:
             case LoginState.LoggedIn:
                 btn_Connect.Enabled = false;
                 //btn_Cancel.Enabled = false;
                 break;
         }
     }
     else Invoke(new Delegates.VoidResultLoginStateParams(SetState), state);
 }
コード例 #35
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
 public void OnEvent(EventData eData)
 {
     if (eData.eventType == "LOGIN_RESPONSE") {
         dialogMessage = "";
         if (eData.eventArgs[0] == "Success") {
             StartCharacterSelection();
         } else {
             errorMessage = eData.eventArgs[0];
         }
     } else if (eData.eventType == "REGISTER_RESPONSE") {
         dialogMessage = "";
         if (eData.eventArgs[0] == "Success") {
             loginState = LoginState.Login;
             errorMessage = "Account created. You can now log in";
         } else {
             errorMessage = eData.eventArgs[0];
         }
     }
 }
コード例 #36
0
		/// <summary>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </summary>
		/// <returns>The next challenge response.</returns>
		/// <param name="token">The server's challenge token.</param>
		/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
		/// <param name="length">The length of the server's challenge.</param>
		/// <exception cref="SaslException">
		/// An error has occurred while parsing the server's challenge token.
		/// </exception>
		protected override byte[] Challenge (byte[] token, int startIndex, int length)
		{
			var cred = Credentials.GetCredential (Uri, MechanismName);
			byte[] challenge;

			switch (state) {
			case LoginState.UserName:
				challenge = Encoding.UTF8.GetBytes (cred.UserName);
				state = LoginState.Password;
				break;
			case LoginState.Password:
				challenge = Encoding.UTF8.GetBytes (cred.Password);
				IsAuthenticated = true;
				break;
			default:
				throw new InvalidOperationException ();
			}

			return challenge;
		}
コード例 #37
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
 void StartCharacterCreation()
 {
     if (character != null)
         Destroy(character);
     characterName = "";
     int randomResult = Random.Range(0, 2);
     if(randomResult == 0)
     {
         gender = "Male";
     }else{
         gender = "Female";
     }
     //SetCharacter(npcAppearance.GenerateRandomUMA(race + gender));
     SetCharacter(characterPrefabs[selectedPrefab]);
     loginState = LoginState.CharacterCreate;
     creationState = CreationState.Body;
 }
コード例 #38
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
    // Use this for initialization
    void Start()
    {
        loginState = LoginState.Login;
        EventSystem.RegisterEvent("LOGIN_RESPONSE", this);
        EventSystem.RegisterEvent("REGISTER_RESPONSE", this);

        aspect = classes[0];

        // Play music
        SoundSystem.LoadSoundSettings();
        if (musicObject != null)
            SoundSystem.PlayMusic(musicObject.GetComponent<AudioSource>());
    }
コード例 #39
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
 void DrawRegisterUI()
 {
     GUILayout.BeginArea(CreateCenteredRect (220, 360), skin.GetStyle("Window"));
     GUILayout.Label ("Create Account");
     GUILayout.Label ("Username:"******"Password:"******"Confirm Password:"******"Email:");
     email = GUILayout.TextField (email);
     GUILayout.Label("Confirm Email:");
     email2 = GUILayout.TextField (email2);
     if (GUILayout.Button("Create")) {
         Register();
     }
     if (GUILayout.Button("Cancel")) {
         loginState = LoginState.Login;
     }
     GUILayout.EndArea();
 }
コード例 #40
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
 void DrawLoginUI()
 {
     GUILayout.BeginArea(CreateCenteredRect (220, 150), skin.GetStyle("Window"));
     GUILayout.Label ("Username:"******"Password:"******"Create Account")) {
         loginState = LoginState.Register;
     }
     GUILayout.Space(20);
     if (GUILayout.Button("Login")) {
         dialogMessage = "Logging in...";
         // Verify username and password are entered, then pass them to the client
         // Also convert password to md5
         if (useSaltedPasswords) {
             Client.Instance.Login(username, password);
         } else {
             Client.Instance.Login(username, Encryption.Md5Sum(password));
         }
     }
     GUILayout.EndHorizontal();
     GUILayout.EndArea();
 }
コード例 #41
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
    void DrawCharacterCreateUI()
    {
        GUILayout.BeginArea(new Rect(10, 100, 200, Screen.height - 100), skin.GetStyle("Window"));
        GUILayout.Label("Gender:");
        /*GUILayout.BeginHorizontal();
        if (GUILayout.Button("Male")) {
            gender = "Male";
            //SetRace("HumanMale");
            selectedPrefab = 0;
        } else if (GUILayout.Button("Female")) {
            gender = "Female";
            //SetRace("HumanFemale");
            selectedPrefab = 1;
        }
        GUILayout.EndHorizontal();*/
        for (int i = 0; i < characterPrefabs.Count; i++) {
            if (GUILayout.Button(characterPrefabs[i].name)) {
                SetCharacter(characterPrefabs[i]);
                selectedPrefab = i;
            }
        }
        GUILayout.Label("Name:");
        characterName = GUILayout.TextField(characterName);
        if (GUILayout.Button("Create")) {
            Dictionary<string, object> properties = new Dictionary<string, object>();
            // Core properties - these are needed
            properties.Add("characterName", characterName);
            properties.Add("prefab", characterPrefabs[selectedPrefab].name);
            properties.Add("race", race);
            properties.Add("aspect", aspect);
            properties.Add("gender", gender);

            // Custom properties - add whatever you want
            /*properties.Add ("custom:test", 27);
            properties.Add ("custom:umaData:floatVal", 1.5f);
            properties.Add ("custom:umaData:stringVal", "hi");
            properties.Add ("custom:umaData:intVal", 7);*/

            // End custom property adding

            dialogMessage = "Please wait...";
            CharacterEntry entry = Client.Instance.NetworkHelper.CreateCharacter(properties);
            if (entry == null) {
                errorMessage = "Unknown Error";
            } else {
                if (!entry.Status) {
                    if (entry.ContainsKey("errorMessage")) {
                        errorMessage = (string)entry["errorMessage"];
                    }
                }
            }
            dialogMessage = "";
            if (errorMessage == "") {
                loginState = LoginState.CharacterSelect;
                characterSelected = entry;
            }
        }
        if (GUILayout.Button("Cancel")) {
            CancelCharacterCreation();
            StartCharacterSelection();
        }
        GUILayout.EndArea();

        // Customisation Window
        /*GUILayout.BeginArea(new Rect(Screen.width - 210, 50, 200, 100), skin.GetStyle("Window"));
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Body")) {
            creationState = CreationState.Body;
        } else if (GUILayout.Button("Head")) {
            creationState = CreationState.Head;
        }
        GUILayout.EndHorizontal();
        GUILayout.EndArea();*/
    }
コード例 #42
0
 public AccountLoginStateChangeEventArgs(string AccountHandle, int StatusCode, string StatusString, LoginState State)
 {
     this.AccountHandle = AccountHandle;
     this.StatusCode = StatusCode;
     this.StatusString = StatusString;
     this.State = State;
 }
コード例 #43
0
ファイル: LoginController.cs プロジェクト: zukeru/ageofasura
 // Use this for initialization
 void Start()
 {
     loginState = LoginState.Login;
     AtavismEventSystem.RegisterEvent("LOGIN_RESPONSE", this);
     AtavismEventSystem.RegisterEvent("REGISTER_RESPONSE", this);
     // Play music
     SoundSystem.LoadSoundSettings();
     SoundSystem.PlayMusic(musicObject.GetComponent<AudioSource>());
 }
コード例 #44
0
		/// <summary>
		/// Resets the state of the SASL mechanism.
		/// </summary>
		/// <remarks>
		/// Resets the state of the SASL mechanism.
		/// </remarks>
		public override void Reset ()
		{
			state = LoginState.Auth;
			challenge = null;
			response = null;
			cnonce = null;
			base.Reset ();
		}
コード例 #45
0
        /// <summary>
        /// Send Unit Server login state to client
        /// </summary>
        /// <param name="uls"></param>
        /// <param name="PlayerID"></param>
        /// <returns></returns>
        public static byte[] SendUnitLoginState(LoginState uls, int PlayerID)
        {
            Packet p = new Packet(100);
            if (uls == LoginState.Success)
            {
                p.WriteShort((short)uls);
                p.WriteInt(PlayerID); // if client were ingame before, else its just 00 00 00 00
            }
            else
            {
                p.WriteShort((short)uls);
                p.WriteHexString("00 00 00 00"); // if its error just logintype and rest zeroes
            }

            return p.GetWrittenBuffer(PacketIds.SendUnitLoginState);
        }
コード例 #46
0
ファイル: Chat.aspx.cs プロジェクト: paopaofeng/dp2
    // ajax请求发送文字内容,创建一个条目
    // chat.aspx?action=send&data=xxx&room=xxx&text=xxx&style=xxx&name=xxx
    void DoSendText(LoginState loginstate)
    {
        string strError = "";
        int nRet = 0;

        SendResultInfo result_info = new SendResultInfo();

        string strDate = this.Request["date"];
        if (strDate != DateTimeUtil.DateTimeToString8(DateTime.Now))
        {
            result_info.ErrorString = "不允许发送到非今天的文件中";
            result_info.ResultValue = -1;
            goto END_SEND;
        }

        string strRoom = this.Request.Form["room"];
        string strText = this.Request.Form["text"];
        string strStyle = this.Request.Form["style"];
        string strUserName = this.Request.Form["name"];

        string strUserID = sessioninfo.UserID;
        string strDisplayName = "";
        string strIP = "";
        if (loginstate == LoginState.NotLogin
            || loginstate == LoginState.Public)
        {
            strUserID = "(访客)" + strUserName;
            strIP = this.Request.UserHostAddress.ToString();
        }
        else if (loginstate == LoginState.Reader)
        {
            if (sessioninfo.ReaderInfo != null
                && string.IsNullOrEmpty(sessioninfo.ReaderInfo.DisplayName) == false)
                strDisplayName = sessioninfo.ReaderInfo.DisplayName;
        }

        nRet = app.CreateChatItem(
            MergeRights(sessioninfo.RightsOrigin, sessioninfo.SsoRights),
            strRoom,
            strUserID,
            strDisplayName,
            strIP,
            strText,
            strStyle,
            sessioninfo.PostedFileInfo != null ? sessioninfo.PostedFileInfo.FileName : "",
            // null,   // this.FileUpload1.PostedFile,
            sessioninfo.PhotoUrl,
            out strError);
        result_info.ErrorString = strError;
        result_info.ResultValue = nRet;

        DeleteTempFile();

    END_SEND:
        this.Response.Write(GetResultString(result_info));
        this.Response.End();
    }
コード例 #47
0
        /// <summary>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </summary>
        /// <returns>The next challenge response.</returns>
        /// <param name="token">The server's challenge token.</param>
        /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
        /// <param name="length">The length of the server's challenge.</param>
        /// <exception cref="SaslException">
        /// An error has occurred while parsing the server's challenge token.
        /// </exception>
        protected override byte[] Challenge(byte[] token, int startIndex, int length)
        {
            if (IsAuthenticated)
                throw new InvalidOperationException ();

            if (token == null)
                return null;

            var cred = Credentials.GetCredential (Uri, MechanismName);

            switch (state) {
            case LoginState.Auth:
                if (token.Length > 2048)
                    throw new SaslException (MechanismName, SaslErrorCode.ChallengeTooLong, "Server challenge too long.");

                challenge = DigestChallenge.Parse (Encoding.UTF8.GetString (token));
                response = new DigestResponse (challenge, Uri.Scheme, Uri.DnsSafeHost, cred.UserName, cred.Password);
                state = LoginState.Final;
                return response.Encode ();
            case LoginState.Final:
                if (token.Length == 0)
                    throw new SaslException (MechanismName, SaslErrorCode.MissingChallenge, "Server response did not contain any authentication data.");

                var text = Encoding.UTF8.GetString (token);
                string key, value;
                int index = 0;

                if (!DigestChallenge.TryParseKeyValuePair (text, ref index, out key, out value))
                    throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Server response contained incomplete authentication data.");

                var expected = response.ComputeHash (cred.Password, false);
                if (value != expected)
                    throw new SaslException (MechanismName, SaslErrorCode.IncorrectHash, "Server response did not contain the expected hash.");

                IsAuthenticated = true;
                return new byte[0];
            default:
                throw new ArgumentOutOfRangeException ();
            }
        }
コード例 #48
0
 /// <summary>
 /// Resets the state of the SASL mechanism.
 /// </summary>
 public override void Reset()
 {
     state = LoginState.UserName;
     base.Reset ();
 }
コード例 #49
0
		/// <summary>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </summary>
		/// <remarks>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </remarks>
		/// <returns>The next challenge response.</returns>
		/// <param name="token">The server's challenge token.</param>
		/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
		/// <param name="length">The length of the server's challenge.</param>
		/// <exception cref="System.InvalidOperationException">
		/// The SASL mechanism is already authenticated.
		/// </exception>
		/// <exception cref="SaslException">
		/// An error has occurred while parsing the server's challenge token.
		/// </exception>
		protected override byte[] Challenge (byte[] token, int startIndex, int length)
		{
			if (IsAuthenticated)
				throw new InvalidOperationException ();

			var cred = Credentials.GetCredential (Uri, MechanismName);
			byte[] response, signature;

			switch (state) {
			case LoginState.Initial:
				if (string.IsNullOrEmpty (cnonce)) {
					var entropy = new byte[18];

					using (var rng = RandomNumberGenerator.Create ())
						rng.GetBytes (entropy);

					cnonce = Convert.ToBase64String (entropy);
				}

				client = "n=" + Normalize (cred.UserName) + ",r=" + cnonce;
				response = Encoding.UTF8.GetBytes ("n,," + client);
				state = LoginState.Final;
				break;
			case LoginState.Final:
				server = Encoding.UTF8.GetString (token, startIndex, length);
				var tokens = ParseServerChallenge (server);
				string salt, nonce, iterations;
				int count;

				if (!tokens.TryGetValue ('s', out salt))
					throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Challenge did not contain a salt.");

				if (!tokens.TryGetValue ('r', out nonce))
					throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Challenge did not contain a nonce.");

				if (!tokens.TryGetValue ('i', out iterations))
					throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Challenge did not contain an iteration count.");

				if (!nonce.StartsWith (cnonce, StringComparison.Ordinal))
					throw new SaslException (MechanismName, SaslErrorCode.InvalidChallenge, "Challenge contained an invalid nonce.");

				if (!int.TryParse (iterations, out count) || count < 1)
					throw new SaslException (MechanismName, SaslErrorCode.InvalidChallenge, "Challenge contained an invalid iteration count.");

				var password = Encoding.UTF8.GetBytes (SaslPrep (cred.Password));
				salted = Hi (password, Convert.FromBase64String (salt), count);

				var withoutProof = "c=" + Convert.ToBase64String (Encoding.ASCII.GetBytes ("n,,")) + ",r=" + nonce;
				auth = Encoding.UTF8.GetBytes (client + "," + server + "," + withoutProof);

				var key = HMAC (salted, Encoding.ASCII.GetBytes ("Client Key"));
				signature = HMAC (Hash (key), auth);
				Xor (key, signature);

				response = Encoding.UTF8.GetBytes (withoutProof + ",p=" + Convert.ToBase64String (key));
				state = LoginState.Validate;
				break;
			case LoginState.Validate:
				var challenge = Encoding.UTF8.GetString (token, startIndex, length);

				if (!challenge.StartsWith ("v=", StringComparison.Ordinal))
					throw new SaslException (MechanismName, SaslErrorCode.InvalidChallenge, "Challenge did not start with a signature.");

				signature = Convert.FromBase64String (challenge.Substring (2));
				var serverKey = HMAC (salted, Encoding.ASCII.GetBytes ("Server Key"));
				var calculated = HMAC (serverKey, auth);

				if (signature.Length != calculated.Length)
					throw new SaslException (MechanismName, SaslErrorCode.IncorrectHash, "Challenge contained a signature with an invalid length.");

				for (int i = 0; i < signature.Length; i++) {
					if (signature[i] != calculated[i])
						throw new SaslException (MechanismName, SaslErrorCode.IncorrectHash, "Challenge contained an invalid signatire.");
				}

				IsAuthenticated = true;
				response = new byte[0];
				break;
			default:
				throw new IndexOutOfRangeException ("state");
			}

			return response;
		}
コード例 #50
0
ファイル: LoginUI.cs プロジェクト: BladeFight/EgionOnline
 void StartCharacterSelection()
 {
     characterEntries = ClientAPI.GetCharacterEntries();
     if (characterEntries.Count > 0) {
         CharacterSelected(characterEntries[0]);
     }
     loginState = LoginState.CharacterSelect;
 }
コード例 #51
0
 private void OnLoginStateChanged(LoginState status)
 {
     if (LoginStateChanged != null)
     {
         LoginStateChanged(status);
     }
 }
コード例 #52
0
    void OnGUI()
    {
        #region LOGIN KEYBOARD
        if (mLoginState == LoginState.Default)
        {
            // Only show the Login Success message when LoginState.Default mode.
            if (isLoginSuccess)
            {
                GUI.Label(new Rect(xCancelBtn, INPUT_OFFSET, WELCOME_LABEL_WIDTH, INPUT_HEIGHT), successMessage, mGUIStyleLabel);
            }

            if (GUI.Button(new Rect(xLoginBtn, INPUT_OFFSET, INPUT_WIDTH, INPUT_HEIGHT), INPUT_BTN_LOGIN, mGUIStyleBtnInput))
            {
                mLoginState = LoginState.LoginAndCancel;
                if (mKeyboard == null)
                {
                    mKeyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, true, false, false, false);
                    mKeyboard.active = true;
                }
                else if (!mKeyboard.active)
                {
                    mInputUserName = "";
                    mKeyboard.active = true;
                }
            }
        }
        else if (mLoginState == LoginState.LoginAndCancel)
        {
            //mInputUserName = GUI.TextField(new Rect(xTextField, INPUT_OFFSET, TEXTFIELD_WIDTH, INPUT_HEIGHT), mInputUserName, 16, mGUIStyleTextField);

            GUI.Label(mRectTextField, mInputUserName, mGUIStyleTextField);
            if (!isMouseDownOnInputField && !mKeyboard.active && mRectTextField.Contains(Event.current.mousePosition) && Input.GetMouseButtonDown(0))
            {
                isMouseDownOnInputField = true;
            }

            if (GUI.Button(new Rect(xLoginBtn, INPUT_OFFSET, INPUT_WIDTH, INPUT_HEIGHT), INPUT_BTN_CONFIRM, mGUIStyleBtnInput))
            {
                // TODO: Check database for login information. 


                // RETURN: When user confirms login, check login information is correct
                isLoginSuccess = true;
                successMessage = "Welcome, " + mInputUserName + "!";
                mLoginState = LoginState.Default;
            }

            if (GUI.Button(new Rect(xCancelBtn, INPUT_OFFSET, INPUT_WIDTH, INPUT_HEIGHT), INPUT_BTN_CANCEL, mGUIStyleBtnInput))
            {
                mLoginState = LoginState.Default;
            }
        }
        #endregion // LOGIN KEYBOARD

        if (GUI.Button(new Rect(xPos, yPos, BUTTON_SIZE, BUTTON_SIZE), "", mGUIStyleBtnPlay))
        {
            WindowsGateway.OnClickPlay();
            Application.LoadLevel("Level");
        }
    }
コード例 #53
0
		/// <summary>
		/// Resets the state of the SASL mechanism.
		/// </summary>
		/// <remarks>
		/// Resets the state of the SASL mechanism.
		/// </remarks>
		public override void Reset ()
		{
			state = LoginState.Initial;
			client = null;
			server = null;
			salted = null;
			cnonce = null;
			auth = null;

			base.Reset ();
		}
コード例 #54
0
ファイル: SaslMechanismNtlm.cs プロジェクト: Gekctek/MailKit
		/// <summary>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </summary>
		/// <remarks>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </remarks>
		/// <returns>The next challenge response.</returns>
		/// <param name="token">The server's challenge token.</param>
		/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
		/// <param name="length">The length of the server's challenge.</param>
		/// <exception cref="System.InvalidOperationException">
		/// The SASL mechanism is already authenticated.
		/// </exception>
		/// <exception cref="SaslException">
		/// An error has occurred while parsing the server's challenge token.
		/// </exception>
		protected override byte[] Challenge (byte[] token, int startIndex, int length)
		{
			if (IsAuthenticated)
				throw new InvalidOperationException ();

			var cred = Credentials.GetCredential (Uri, MechanismName);
			string password = cred.Password ?? string.Empty;
			string userName = cred.UserName;
			string domain = cred.Domain;
			MessageBase message;

			if (string.IsNullOrEmpty (domain)) {
				int index = userName.IndexOf ('\\');
				if (index == -1)
					index = userName.IndexOf ('/');

				if (index >= 0) {
					domain = userName.Substring (0, index);
					userName = userName.Substring (index + 1);
				}
			}

			switch (state) {
			case LoginState.Initial:
				message = GetInitialResponse (domain);
				state = LoginState.Challenge;
				break;
			case LoginState.Challenge:
				message = GetChallengeResponse (userName, password, domain, token, startIndex, length);
				IsAuthenticated = true;
				break;
			default:
				throw new IndexOutOfRangeException ("state");
			}

			return message.Encode ();
		}
コード例 #55
0
ファイル: AppController.cs プロジェクト: weijunbao/chatapp
 /// <summary>
 /// Sends the current presence information to the server
 /// </summary>
 public void SendCurrentPresence(LoginState loginState)
 {
     if (m_currentPresence == null)
     {
         m_currentPresence = new AvailableRequest();
     }
     m_currentPresence.Status = loginState.ToString();
     SendCurrentPresence(m_currentPresence);
 }
コード例 #56
0
ファイル: SaslMechanismNtlm.cs プロジェクト: Gekctek/MailKit
		/// <summary>
		/// Resets the state of the SASL mechanism.
		/// </summary>
		/// <remarks>
		/// Resets the state of the SASL mechanism.
		/// </remarks>
		public override void Reset ()
		{
			state = LoginState.Initial;
			base.Reset ();
		}
コード例 #57
0
		/// <summary>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </summary>
		/// <remarks>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </remarks>
		/// <returns>The next challenge response.</returns>
		/// <param name="token">The server's challenge token.</param>
		/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
		/// <param name="length">The length of the server's challenge.</param>
		/// <exception cref="System.InvalidOperationException">
		/// The SASL mechanism is already authenticated.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// THe SASL mechanism does not support SASL-IR.
		/// </exception>
		/// <exception cref="SaslException">
		/// An error has occurred while parsing the server's challenge token.
		/// </exception>
		protected override byte[] Challenge (byte[] token, int startIndex, int length)
		{
			if (IsAuthenticated)
				throw new InvalidOperationException ();

			if (token == null)
				throw new NotSupportedException ("DIGEST-MD5 does not support SASL-IR.");

			var cred = Credentials.GetCredential (Uri, MechanismName);

			switch (state) {
			case LoginState.Auth:
				if (token.Length > 2048)
					throw new SaslException (MechanismName, SaslErrorCode.ChallengeTooLong, "Server challenge too long.");

				challenge = DigestChallenge.Parse (Encoding.UTF8.GetString (token, startIndex, length));

				if (string.IsNullOrEmpty (cnonce)) {
					var entropy = new byte[15];

					using (var rng = RandomNumberGenerator.Create ())
						rng.GetBytes (entropy);

					cnonce = Convert.ToBase64String (entropy);
				}

				response = new DigestResponse (challenge, Uri.Scheme, Uri.DnsSafeHost, cred.UserName, cred.Password, cnonce);
				state = LoginState.Final;
				return response.Encode ();
			case LoginState.Final:
				if (token.Length == 0)
					throw new SaslException (MechanismName, SaslErrorCode.MissingChallenge, "Server response did not contain any authentication data.");

				var text = Encoding.UTF8.GetString (token, startIndex, length);
				string key, value;
				int index = 0;

				if (!DigestChallenge.TryParseKeyValuePair (text, ref index, out key, out value))
					throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Server response contained incomplete authentication data.");

				var expected = response.ComputeHash (cred.Password, false);
				if (value != expected)
					throw new SaslException (MechanismName, SaslErrorCode.IncorrectHash, "Server response did not contain the expected hash.");

				IsAuthenticated = true;
				return new byte[0];
			default:
				throw new IndexOutOfRangeException ("state");
			}
		}
コード例 #58
0
 /// <summary>
 /// Send LoginState to client
 /// </summary>
 /// <param name="ls">State of login</param>
 /// <returns></returns>
 public static byte[] SendLoginState(LoginState ls, int ID)
 {
     Packet p = new Packet(100);
     if (ls == LoginState.Success)
     {
         p.WriteByte((short)ls);
         p.WriteShort(ID); // the total connection amounts from db or somewhere, used in gameserver
         p.WriteHexString("01 00 14");
     }
     else
     {
         p.WriteByte((short)ls);
         p.WriteHexString("00 00 00 00 00"); // if its error just logintype and rest zeroes
     }
     return p.GetWrittenBuffer(PacketIds.SendLoginState);
 }
コード例 #59
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //声明加密程序
        Encrypter encrypt = new Encrypter();

        //Action
        string Action = MakeUtil.getStringFromRequestByName(Request, "Action", -1);
        if (Action == "Login")
        {
            string result = "";
            string userid = MakeUtil.getStringFromRequestByName(Request, "UserID", -1);
            string userpwd = MakeUtil.getStringFromRequestByName(Request, "UserPWD", -1);
            string companypwd = MakeUtil.getStringFromRequestByName(Request, "CompanyPwd", -1);
            string[] FieldNames = MakeUtil.getStringFromRequestByName(Request, "FieldNames", -1).Split('|');
            string guid = MakeUtil.getStringFromRequestByName(Request, "Guid", -1);

            Dictionary<string, LoginState> LoginStateDic = (Dictionary<string, LoginState>)Application["LoginState"];

            bool newLS = true;
            LoginState ls = null;
            // 检测重复登录
            if (result.Length == 0)
            {
                if (LoginStateDic.Keys.Contains(userid))
                {
                    newLS = false;
                    ls = LoginStateDic[userid];
                    if (guid != ls.SerialID)
                    {
                        // 已有用户登录该账号
                        result = "error|该用户已登录";
                    }
                }
            }
            if (result.Length == 0)
            {
                IList<QueryModel> qmlist = new List<QueryModel>();
                qmlist.Add(MakeUtil.getQueryModel("UserID", "'", SqlWhere.WhereOperator.Equal, userid));
                qmlist.Add(MakeUtil.getQueryModel("UserPassword", "'", SqlWhere.WhereOperator.Equal,
                    encrypt.EncryptString(userpwd)));

                try
                {
                    UsersModel um = bllUE.getModel(qmlist);

                    if (um.UserID == "" || !um.Login)
                    {
                        result = "error|操作用户账号错误或操作用户密码错误";
                    }
                    else
                    {
                        if (newLS)
                        {
                            ls = new LoginState();
                        }

                        ls.SerialID = guid;
                        ls.LoginName = userid;
                        ls.LastTime = DateTime.Now;
                        ls.IP = MakeUtil.GetClientIP();
                        ls.MAC = MakeUtil.GetClientMAC(ls.IP);
                        string[] tempMac = ls.MAC.Split('|');
                        if (tempMac.Length > 1 && tempMac[0] != "error")
                        {
                            result = string.Format("error|对不起您的MAC地址不在允许的范围之内");
                        }
                        else
                        {
                            //验证MAC地址
                            if (checkMAC(um, ls.MAC))
                            {
                                if (newLS)
                                {
                                    LoginStateDic[userid] = ls;
                                }

                                Application["LoginState"] = LoginStateDic;

                                List<string> ModulesList = new List<string>();

                                ModulesList.AddRange(new string[] { "Base", "System", "Sale" });

                                foreach (string str in FieldNames)
                                {
                                    switch (str)
                                    {
                                        case "UserId":
                                            result += um.UserID + "|";
                                            break;
                                        case "UserName":
                                            result += um.UserName + "|";
                                            break;
                                        case "Power":
                                            result += getAllPower(um, ModulesList.ToArray()) + "|";
                                            break;
                                        case "PartsPower":
                                            result += getPartsPower(um) + "|";
                                            break;
                                        case "DepartmentNo":
                                            result += um.DepartmentNo + "|";
                                            break;
                                        case "Modules":
                                            result += string.Join(",", ModulesList.ToArray()) + "|";
                                            break;
                                    }
                                }
                                if (result.Length > 0)
                                {
                                    result = result.Substring(0, result.Length - 1);
                                }
                            }
                            else
                            {
                                result = string.Format("error|对不起您的MAC地址为{0},不在允许的范围之内", ls.MAC);
                            }
                        }
                    }
                }
                catch (Make.Exp.MakeException mEx)
                {
                    result = "error|" + mEx.Message;
                }
            }

            WriteBack(result);
        }
        else if (Action == "UpdateLS")
        {
            string userid = MakeUtil.getStringFromRequestByName(Request, "UserID", -1);
            string guid = MakeUtil.getStringFromRequestByName(Request, "Guid", -1);

            Dictionary<string, LoginState> LoginStateDic = (Dictionary<string, LoginState>)Application["LoginState"];
            {
                LoginState ls = LoginStateDic[userid];
                if (ls.SerialID == guid)
                {
                    ls.LastTime = DateTime.Now;
                    Application["LoginState"] = LoginStateDic;
                }
            }
        }
        else if (Action == "Exit")
        {
            string userid = MakeUtil.getStringFromRequestByName(Request, "UserID", -1);
            string guid = MakeUtil.getStringFromRequestByName(Request, "Guid", -1);

            Dictionary<string, LoginState> LoginStateDic = (Dictionary<string, LoginState>)Application["LoginState"];
            if (LoginStateDic.Keys.Contains(userid))
            {
                LoginState ls = LoginStateDic[userid];
                if (ls.SerialID == guid)
                {
                    LoginStateDic.Remove(userid);
                    Application["LoginState"] = LoginStateDic;
                }
            }
        }
    }
コード例 #60
0
		/// <summary>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </summary>
		/// <remarks>
		/// Parses the server's challenge token and returns the next challenge response.
		/// </remarks>
		/// <returns>The next challenge response.</returns>
		/// <param name="token">The server's challenge token.</param>
		/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
		/// <param name="length">The length of the server's challenge.</param>
		/// <exception cref="System.InvalidOperationException">
		/// The SASL mechanism is already authenticated.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The SASL mechanism does not support SASL-IR.
		/// </exception>
		/// <exception cref="SaslException">
		/// An error has occurred while parsing the server's challenge token.
		/// </exception>
		protected override byte[] Challenge (byte[] token, int startIndex, int length)
		{
			var cred = Credentials.GetCredential (Uri, MechanismName);
			byte[] challenge;

			if (token == null)
				throw new NotSupportedException ("LOGIN does not support SASL-IR.");

			switch (state) {
			case LoginState.UserName:
				challenge = encoding.GetBytes (cred.UserName);
				state = LoginState.Password;
				break;
			case LoginState.Password:
				challenge = encoding.GetBytes (cred.Password);
				IsAuthenticated = true;
				break;
			default:
				throw new InvalidOperationException ();
			}

			return challenge;
		}