Exemple #1
0
        private async Task SetToken(LoginResponse tokenResponse, LoginDuration keepLoggedIn = LoginDuration.Temporary)
        {
            LoginResponseExtended token = new LoginResponseExtended(tokenResponse);


            switch (keepLoggedIn)
            {
            case LoginDuration.Temporary:
                token.SessionExpirationDate = DateTime.Now.AddHours(3);
                await _localStorage.SetItemAsync("Token", token);

                break;

            case LoginDuration.KeepLoggedIn:
                token.SessionExpirationDate = DateTime.MaxValue;
                await _localStorage.SetItemAsync("Token", token);

                break;

            case LoginDuration.None:
                break;
            }

            await _sessionStorage.SetItemAsync("Token", token);

            bool isLoggedIn = await IsLoggedInAsync();

            if (isLoggedIn)
            {
                UserLoggedIn?.Invoke(null, null);
                await PopulateUserObject();
            }
        }
        public void TryAutoLogIn()
        {
            _mainViewModel.IsLoadingData = true;

            Thread.Sleep(1200);

            new Task(() =>
            {
                try
                {
                    string username = _registryService.GetUsername();
                    string hash     = _registryService.GetPasswordHash();
                    string message  = string.Empty;

                    if (_authenticationService.LogIn(username, hash, ref message))
                    {
                        UserLoggedIn?.Invoke(this, username);
                    }
                    else
                    {
                        _logger.Warning($"Failed auto log in. Message: {message}.");
                    }
                }
                catch (AuthenticationException ex)
                {
                }
                catch (Exception ex)
                {
                    _logger.Error($"Auto log in error");
                    _logger.Error(ex);
                }

                _mainViewModel.IsLoadingData = false;
            }).Start();
        }
Exemple #3
0
        private void BtnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                string email    = tbxEmail.Text;
                string password = tbxPassword.Text;

                if (Customer == null)
                {
                    if (controller.RetrieveCustomer(email, password) == null)
                    {
                        lblLoginStatus.Visible = true;
                    }
                    else
                    {
                        lblLoginStatus.Visible = false;
                        Customer = controller.RetrieveCustomer(email, password);

                        userLoggedIn?.Invoke(Customer, EventArgs.Empty);
                    }
                }
                else
                {
                    lblLoginStatus.Text    = "You are already logged in!";
                    lblLoginStatus.Visible = true;
                }
            }
            catch (Exception ex)
            {
                lblLoginStatus.Text    = ExceptionHandler.ConvertExceptionToMessage(ex);
                lblLoginStatus.Visible = true;
            }
        }
Exemple #4
0
        private async Task InvokeUserLoggedInAsync(bool isAutoLogin)
        {
            await RequestNewKeysAndCertificateOnLoginAsync(isAutoLogin);

            LoggedIn = true;
            UserLoggedIn?.Invoke(this, new UserLoggedInEventArgs(isAutoLogin));
        }
        void OnLoggedIn(UserModelView userModelView)
        {
            IsLoggedIn = true;
            UserLoggedIn?.Invoke();
            CurrentUserModelView = userModelView;

            _network?.Connect(CurrentUserModelView.UserName);
        }
Exemple #6
0
        /// <summary>
        /// Logs in or registers a user whose email has not already been registered.
        /// If successful, calls the UserLoggedIn event handler and sets the user in ApiHelper
        /// </summary>
        /// <param name="info">Information needed by the api to log a user in</param>
        /// <returns></returns>
        public static async void LoginOrRegisterAsync()
        {
            AuthenticationResult result = null;

            try
            {
                PublicClientApplication pca = App.AuthClient;
                result = await pca.AcquireTokenAsync(Globals.DefaultScopes);

                ApiHelper.setToken(result.AccessToken);

                LoginInitiated?.Invoke(DateTime.Now, null);

                Models.User user = await ApiHelper.GetAsync <Models.User>("User");

                if (user == null || user.Email == null)
                {
                    user = await ApiHelper.PostAsync <Models.User>("User");
                }



                if (user != null && !String.IsNullOrWhiteSpace(user.Email))
                {
                    UserLoggedIn?.Invoke(DateTime.Now, user);
                }
                else
                {
                    AuthError?.Invoke(DateTime.Now, "No connection to server.");
                }
            }
            catch (MsalException ex)
            {
                if (ex.ErrorCode != "authentication_canceled")
                {
                    string message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        message += "\nInner Exception: " + ex.InnerException.Message;
                    }

                    AuthError?.Invoke(DateTime.Now, message);
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                // Launch warning popup
                ContentDialog notLoggedInDialog = new ContentDialog()
                {
                    Title             = "Could not login",
                    Content           = "Please check your wifi signal.",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);
            }
        }
        public static User Login(string username, string password)
        {
            int id = Context.Users.SingleOrDefault(x => x.ValidateCredentials(username, password))?.ID ?? -1;

            if (TryGetUser(id, out User user))
            {
                UserLoggedIn?.Invoke(user);
            }

            return(user);
        }
        /// <summary>
        /// Attempts to log in or register the user using the given provider info.
        /// If successful, saves their credentials for future use.
        /// </summary>
        private static async Task LoginOrRegisterAsync(ProviderInfo info)
        {
            var exists = await App.Api.GetAsync <User>("Users", info);

            string action = null != exists ? "Login" : "Register";

            var user = await App.Api.PostAsync <ProviderInfo, User>(action, info);

            if (null != user && !String.IsNullOrWhiteSpace(user.Email))
            {
                UserLoggedIn?.Invoke(DateTime.Now, user);
                StoreUserInfo(user.Auth);
            }
        }
Exemple #9
0
        public bool Login(string userName, string password)
        {
            var result    = _dbManager.UserCollection.Find <User>(u => u.UserName == userName && u.Password == password);
            var foundUser = result.SingleOrDefault();

            if (foundUser != null)
            {
                CurrentUser = foundUser;
                UserLoggedIn?.Invoke();

                _dbManager.StartChatWatcher(CurrentUser.UserID);
                _dbManager.StartContactListWatcher(CurrentUser.UserID);
                return(true);
            }
            else
            {
                return(false); //! Error  login error
            }
        }
        public async Task ConnectAsync()
        {
            _connection = new HubConnection(url);
            _hubProxy   = _connection.CreateHubProxy("OrderBook");
            _hubProxy.On <User>("UserLogin", (u) => UserLoggedIn?.Invoke(u));
            _hubProxy.On <string>("UserLogout", (n) => UserLoggedOut?.Invoke(n));
            _hubProxy.On <string>("UserDisconnection", (n) => UserDisconnected?.Invoke(n));
            _hubProxy.On <string>("UserReconnection", (n) => UserReconnected?.Invoke(n));
            _hubProxy.On <IEnumerable <Order> >("BroadcastOrders", (n) => ReceiveNewOrder?.Invoke(n));
            _hubProxy.On <string, MessageType>("NotifyUser", (n, m) => ReceiveNotification?.Invoke(n, m));
            _hubProxy.On <string>("SendBidDepth", (x) => ReceiveBidDepth?.Invoke(x));
            _hubProxy.On <string>("SendAskDepth", (x => ReceiveAskDepth?.Invoke(x)));

            _connection.Reconnecting += Reconnecting;
            _connection.Reconnected  += Reconnected;
            _connection.Closed       += Disconnected;

            ServicePointManager.DefaultConnectionLimit = 10;
            await _connection.Start();
        }
Exemple #11
0
        public async Task <bool> IsLoggedInAsync()
        {
            LoginResponse token = await GetToken();

            if (token != null)
            {
                if (token.AccessToken != null && token.TokenType != null)
                {
                    if (CurrentlyLoggedInUser == null)
                    {
                        loggedIn = true;
                        UserLoggedIn?.Invoke(null, null);
                        await PopulateUserObject();
                    }

                    return(true);
                }
            }

            return(false);
        }
Exemple #12
0
        private async Task <bool> CheckToken()
        {
            UserResponse currentUser = await _sessionApi.GetCurrentUserData(await GetToken());

            if (currentUser == null)
            {
                return(false);
            }
            if (String.IsNullOrEmpty(currentUser.Username))
            {
                return(false);
            }
            if (currentUser != CurrentlyLoggedInUser)
            {
                return(false);
            }
            loggedIn = true;
            UserLoggedIn?.Invoke(null, null);

            return(true);
        }
Exemple #13
0
 private void InvokeUserLoggedIn(bool autoLogin)
 {
     LoggedIn = true;
     UserLoggedIn?.Invoke(this, new UserLoggedInEventArgs(autoLogin));
 }
 public void RaiseUserLoggedIn()
 {
     UserLoggedIn?.Invoke(this, new EventArgs());
 }
        private void UserLoggedInEventHandler(object sender, string username)
        {
            User user = _usersDataModel.GetUser(username);

            UserLoggedIn?.Invoke(this, user);
        }
Exemple #16
0
 protected Task OnUserLoggedIn(IUser user)
 {
     return(UserLoggedIn?.Invoke(user));
 }
Exemple #17
0
        //线程函数,封装一个建立连接的通信套接字
        private void StartListen()
        {
            isListen = true;
            //default()只是设置为一个初始值,这里应该为null  参考网址:https://stackoverflow.com/questions/28720717/why-default-in-c-sharp-tcpclient-clientsocket-defaulttcpclient
            Socket clientSocket = default(Socket);

            while (isListen)
            {
                try
                {
                    //参考网址: http://bbs.csdn.net/topics/30100253
                    //  int accept(int sockfd, void *addr, int *addrlen);
                    //注意这个serverSocket,它是用来监听的套接字,当有用户连接上端口后会返回一个新的套接字也就是这里的clientSocket,sercerSocket还是在那儿继续监听的
                    //详细参考网址:http://www.360doc.com/content/13/0908/17/13253385_313070996.shtml
                    //返回值是一个新的套接字描述符,它代表的是和客户端的新的连接,这个socket相当于一个客户端的socket,包含的是客户端的ip和port
                    //但是它也继承字本地的监听套接字,因此它也有服务器的ip和port信息
                    if (serverSocket == null)   //如果服务停止,即serverSocket为空了,那就直接返回
                    {
                        return;
                    }
                    clientSocket = serverSocket.Accept();   //这个方法返回一个通信套接字,并用这个套接字进行通信,错误时返回-1并设置全局错误变量
                }
                catch (SocketException e)
                {
                    Log?.Invoke(e.ToString() + "StartListen" + DateTime.Now.ToString() + "");
                }

                //TCP是面向字节流的
                Byte[] bytesFrom      = new Byte[4096];
                String dataFromClient = null;

                if (clientSocket != null && clientSocket.Connected)
                {
                    try
                    {
                        //Socket.Receive() 参考网址:http://blog.csdn.net/cpcpc/article/details/7245420
                        //public int Receive(  byte[] buffer,  int offset,   int size,  SocketFlags socketFlags )
                        //buffer  是byte类型的数组,存储收到的数据的位置
                        //offset  是buffer中存储所接收数据的位置
                        //size    要接收的字节数
                        //socketFlags  socketFlages值的按位组合

                        Int32 len = clientSocket.Receive(bytesFrom);    //获取客户端发来的信息,返回的就是收到的字节数,并且把收到的信息都放在bytesForm里面

                        if (len > -1)
                        {
                            String tmp = Encoding.UTF8.GetString(bytesFrom, 0, len);  //将字节流转换成字符串

                            /*try
                             * {
                             *  dataFromClient = EncryptionAndDecryption.TripleDESDecrypting(tmp);      //数据加密传输
                             * }
                             * catch (Exception e)
                             * {
                             *
                             * }
                             * catch (Exception e)
                             * {
                             *
                             * }*/
                            dataFromClient = tmp;
                            Int32 sublen = dataFromClient.LastIndexOf("$");
                            if (sublen > -1)
                            {
                                dataFromClient = dataFromClient.Substring(0, sublen);   //获取用户名

                                if (!clientList.ContainsKey(dataFromClient))
                                {
                                    clientList.Add(dataFromClient, clientSocket);   //如果用户名不存在,则添加用户名进去

                                    //BroadCast是下面自己定义的一个类,是用来将消息对所有用户进行推送的
                                    //PushMessage(String msg, String uName, Boolean flag, Dictionary<String, Socket> clientList)
                                    UserLoggedIn?.Invoke(dataFromClient);

                                    //HandleClient也是一个自己定义的类,用来负责接收客户端发来的消息并转发给所有的客户端
                                    //StartClient(Socket inClientSocket, String clientNo, Dictionary<String, Socket> cList)
                                    HandleClient client = new HandleClient();
                                    client.MessageRecieved += RecMsg;
                                    client.UserLoggedOut   += ULogout;

                                    client.StartClient(clientSocket, dataFromClient, clientList);

                                    Log?.Invoke(dataFromClient + "连接上了服务器");
                                }
                                else
                                {
                                    //用户名已经存在
                                    clientSocket.Send(Encoding.UTF8.GetBytes("#" + dataFromClient + "#"));
                                }
                            }
                        }
                    }
                    catch (Exception ep)
                    {
                        Log?.Invoke(ep.ToString() + "\t\t" + DateTime.Now.ToString() + "");
                    }
                }
            }
        }