Ejemplo n.º 1
0
    public static async Task StartConnectionAsync(LoginObject loginInfor)
    {
        _connection = new WSConnection();
        await _connection.StartConnectionAsync("ws://file.pingg.vn:83/filetracking", loginInfor);

        //await _connection.StartConnectionAsync(Constants.ServerAddress, loginInfor);
    }
Ejemplo n.º 2
0
        public static LoginObject Authenticate(int id, string password)
        {
            LoginObject received = UserSelector <Employee> .Authenticate(id, password);

            ServiceFactory.token = received.Token;
            return(received);
        }
Ejemplo n.º 3
0
        public LoginObject ReceiveLoginHttp(HttpWebRequest request)
        {
            string result;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }

            try
            {
                var serializer   = new JavaScriptSerializer();
                var loginObjects = serializer.Deserialize <List <LoginObject> >(result);

                loginObjects[0].Result = true;
                return(loginObjects[0]);
            }
            catch
            {
                LoginObject errorObject = new LoginObject();
                errorObject.Result = false;
                return(errorObject);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns a loginObject if successful login
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static LoginObject CheckLogin(string username, string password)
        {
            LoginObject loginObject = null;
            DataTable   dt          = null;

            Query query = new Query(SqlQueryType.SqlStoredProc, "AccountCheckLogin");

            query.AddParameter("@Username", username);
            query.AddParameter("@Password", password);

            DBManager.Execute(query, ref dt);

            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];

                int    accountId     = (int)row["AccountID"];
                int    accountTypeId = (int)row["AccountTypeID"];
                string landingUrl    = row["AccountTypeLandingUrl"] as string;

                loginObject = new LoginObject {
                    AccountId = accountId, AccountTypeId = accountTypeId, LandingUrl = landingUrl
                };
            }

            return(loginObject);
        }
Ejemplo n.º 5
0
        private void btLog_Edit_Click(object sender, EventArgs e)
        {
            EditContent editC = new EditContent(main);

            editC.editLogin(currentLog);
            DialogResult edited = editC.ShowDialog();

            if (edited == DialogResult.OK)
            {
                currentLog = editC.TmpLogObject;

                //Update ListViews
                main.updateListItem(currentLog);
                main.resetSearch();

                //Clear Content
                clearContent();

                //Update Content
                updateContent(currentLog.ID.ToString());

                //update Bts-States
                toggleFavStates(!currentLog.Fav);

                //update in xml file
                xml.saveLoginObjects();
            }
        }
Ejemplo n.º 6
0
 //Login method
 private void Login()
 {
     using (View.LoginModal frmLogin = new View.LoginModal())
     {
         if (frmLogin.ShowDialog() == DialogResult.OK)
         {
             var loginObject = new LoginObject()
             {
                 UserName     = frmLogin.UserName,
                 UserPassword = frmLogin.Password
             };
             var jsonObject = JsonConvert.SerializeObject(loginObject, Formatting.Indented);
             if (dataManager.LoginCheck(jsonObject))
             {
                 userName = loginObject.UserName;
                 MessageBox.Show("Welcome, " + userName);
             }
             else
             {
                 MessageBox.Show("Your login information is incorrect, \nplease try again.");
                 Login();
             }
         }
         else
         {
             Application.Exit();
         }
     }
 }
        private void loginButton_Click(object sender, RoutedEventArgs e)
        {
            if (user == null)
            {
                // Login
                LoginObject          loginObeject = new LoginObject(loginUsernameTextBox.Text, loginPasswordTextBox.Password);
                Server.Models.Client loginClient  = RequestsManager.Login(clientObject.stream, loginObeject.toJsonObject());

                if (loginClient != null)
                {
                    user = loginClient;
                    TransactionsTab.Visibility = Visibility.Visible;
                    checkAll.Visibility        = Visibility.Visible;


                    loginButton.Content           = "SignOut";
                    loginUsernameTextBox.Text     = "";
                    loginPasswordTextBox.Password = "";
                }
                else
                {
                    checkAll.Visibility        = Visibility.Hidden;
                    TransactionsTab.Visibility = Visibility.Hidden;
                }
            }
            else
            {
                // Sign out
                TransactionsTab.Visibility    = Visibility.Hidden;
                checkAll.Visibility           = Visibility.Hidden;
                loginButton.Content           = "Login";
                loginUsernameTextBox.Text     = "";
                loginPasswordTextBox.Password = "";
            }
        }
        /// <summary>
        /// Login - User Login (This is a dummy post call which returns a json we pass as a request json, to simulate login in demo project)
        /// </summary>
        /// <returns>The login.</returns>
        /// <param name="LoginData1">Login data1.</param>
        public static async Task <LoginModel> Login(LoginModel LoginData1)
        {
            LoginModel UDI = new LoginModel();

            try
            {
                var client = new System.Net.Http.HttpClient();

                LoginObject Loginobj = new LoginObject();
                Loginobj.LoginData = LoginData1;

                client.BaseAddress = new Uri(APIService.ServiceUrl);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var jData    = JsonConvert.SerializeObject(Loginobj);
                var content1 = new StringContent(jData, Encoding.UTF8, "application/json");

                var response = await client.PostAsync("/post", content1);

                var result = response.Content.ReadAsStringAsync().Result;

                var resultobject = JsonConvert.DeserializeObject <LoginResponse>(result);

                UDI = resultobject?.Data?.LoginData;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                UDI.Errors.Add(AppResources.MESSAGE_ERROR_SOMETHING_WENT_WRONG_WITH_USER_LOGIN);
            }
            return(UDI);
        }
Ejemplo n.º 9
0
    void OnLoginRequestComplete(Response response, int _clientId)
    {
        Debug.Log($"Status Code: {response.StatusCode}");
        Debug.Log($"Data: {response.Data}");
        Debug.Log($"Error: {response.Error}");


        if (!string.IsNullOrEmpty(response.Error) && response.StatusCode != 200)
        {
            ServerSend.LoginFailed(_clientId);
        }
        else if (string.IsNullOrEmpty(response.Error) && !string.IsNullOrEmpty(response.Data) && response.StatusCode == 200)
        {
            LoginObject loginObject = LoginObject.createFromJSON(response.Data);

            Server.clients[_clientId].objectId = loginObject._id;


            if (loginObject.characters.Length == 0)
            {
                ServerSend.ToCharacterCreation(_clientId);
            }
            if (loginObject.characters.Length > 0)
            {
                ServerSend.ToCharacterSelection(_clientId, loginObject);
            }
        }
    }
Ejemplo n.º 10
0
        private void btn_Login(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Password ))
            {
                MessageBox.Show("Kullanıcı adı ve şifre alanları boş geçilemez.");
                return;
            }

            Progress.IsIndeterminate = true;
            txtUserName.IsEnabled = false;
            txtPassword.IsEnabled = false;

            LoginObject log = new LoginObject();
            log.e = txtUserName.Text;
            log.p = txtPassword.Password;

            WebClient web = new WebClient();
            web.Headers["Content-Type"] = "application/json";
            web.Headers["User-Agent"] = "NeroIOS4/1.0.1 CFNetwork/609 Darwin/13.0.0";
            web.UploadStringCompleted += web_UploadStringCompleted;
            string PostData = JsonConvert.SerializeObject(log);

            ((ApplicationBarIconButton)sender).IsEnabled = false;
            web.UploadStringAsync(new Uri("http://api.nero.mekanist.net/v2/user/login", UriKind.Absolute), "POST", PostData, sender);
        }
Ejemplo n.º 11
0
        private bool Connect(string apiUrl)
        {
            //Calculating the Login and Device secret
            _loginSecret  = Utils.GetSecret(_loginObject.Email, _loginObject.Password, Utils.ServerDomain);
            _deviceSecret = Utils.GetSecret(_loginObject.Email, _loginObject.Password, Utils.DeviceDomain);

            //Creating the queryRequest for the connection request
            string connectQueryUrl =
                $"/my/connect?email={HttpUtility.UrlEncode(_loginObject.Email)}&appkey={HttpUtility.UrlEncode(Utils.AppKey)}";

            _apiHandler.SetApiUrl(apiUrl);
            //Calling the queryRequest
            var response = _apiHandler.CallServer <LoginObject>(connectQueryUrl, _loginSecret);

            //If the response is null the connection was not successful
            if (response == null)
            {
                return(false);
            }

            response.Email    = _loginObject.Email;
            response.Password = _loginObject.Password;

            //Else we are saving the response which contains the SessionToken, RegainToken and the RequestId
            _loginObject = response;
            _loginObject.ServerEncryptionToken = Utils.UpdateEncryptionToken(_loginSecret, _loginObject.SessionToken);
            _loginObject.DeviceEncryptionToken = Utils.UpdateEncryptionToken(_deviceSecret, _loginObject.SessionToken);
            IsConnected = true;
            return(true);
        }
        public static bool CheckValid(LoginObject accInfo)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                MessageBox.Show("Connecting.....");
                tcpclnt.Connect("192.168.1.114", 8000);
                MessageBox.Show("Connected");

                Stream stm = tcpclnt.GetStream();

                byte[] ba = ObjectToByteArray(accInfo.username, accInfo.password);

                stm.Write(ba, 0, ba.Length);

                byte[] bb = new byte[100];
                int    k  = stm.Read(bb, 0, 100);

                LoginVerify(ByteArrayToObject(bb));
                tcpclnt.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Error..... " + e.StackTrace);
            }
            return(false);
        }
Ejemplo n.º 13
0
        public static bool ValidateCredentials(LoginObject acc)
        {
            SqlConnection con = new SqlConnection();

            con.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
                                   "C:\\Users\\Giuseppe\\Documents\\SchoolManagement\\SchoolManagementSolution\\SchoolServer2\\DatabaseForSchool.mdf;Integrated Security=True";

            con.Open();
            SqlCommand     cmd = new SqlCommand("select username,password from loginInfo where username='******'and password='******'", con);
            SqlDataAdapter da  = new SqlDataAdapter(cmd);
            DataTable      dt  = new DataTable();

            da.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                Console.WriteLine("Accepted in validate login class");
                con.Close();
                return(true);
            }
            else
            {
                Console.WriteLine("RETURNING FALSE");
                con.Close();
                return(false);
            }
        }
Ejemplo n.º 14
0
 public static async Task StartConnectionAsync(LoginObject loginInfor)
 {
     try
     {
         _connection = new WSConnection();
         await _connection.StartConnectionAsync(Constants.ServerAddress, loginInfor);
     }catch { }
 }
Ejemplo n.º 15
0
        //U8EnvContext envContext = new U8EnvContext();
        public override object CallFunction(string cMenuId, string cMenuName, string cAuthId, string cCmdLine)
        {
            //canshu.uLogin = LoginObject;

            //赋值给公共变量 constr
            canshu.userName = LoginObject.GetLoginInfo().UserName;
            //canshu.conStr = LoginObject.GetLoginInfo().ConnString;
            //canshu.conStr = canshu.conStr.Substring(canshu.conStr.IndexOf("data"), canshu.conStr.IndexOf(";Conn") + 2);
            string userToken = LoginObject.userToken;

            //string accid = LoginObject.GetLoginInfo().AccID;
            //string iyear = LoginObject.GetLoginInfo().iYear;
            //string ztdb = "//ZT" + accid + "//" + iyear;
            canshu.acc = LoginObject.GetLoginInfo().AccID;


            //U8Login.clsLogin u8Login = new U8Login.clsLogin();
            //String sSubId = "AS";
            //String sAccID = LoginObject.GetLoginInfo().AccID;
            //String sYear = LoginObject.GetLoginInfo().iYear;
            //String sUserID = LoginObject.GetLoginInfo().UserId;
            //String sPassword =LoginObject.GetLoginInfo().Password;
            //String sDate = LoginObject.GetLoginInfo().operDate;
            //String sServer = LoginObject.GetLoginInfo().AppServer;
            ////String sSerial = "";
            //if (!u8Login.Login(ref sSubId, ref sAccID, ref sYear, ref sUserID, ref sPassword, ref sDate, ref sServer))
            ////if (!uLogin.Login(ref sSubId, ref sAccID, ref sYear, ref sUserID, ref sPassword, ref sDate, ref sServer))
            //{
            //    MessageBox.Show("登陆失败,原因:" + u8Login.ShareString);
            //    Marshal.FinalReleaseComObject(u8Login);
            //    return "0";
            //}

            //canshu.conStr = u8Login.UFDataConnstringForNet;

            U8Login.clsLogin u8Login2 = new U8Login.clsLoginClass();
            u8Login2.ConstructLogin(LoginObject.userToken);
            canshu.conStr = u8Login2.UFDataConnstringForNet;
            //////u8Login.UfDbPath = ztdb;
            canshu.u8Login = u8Login2;
            //U8Login.clsLogin u8Login = new U8Login.clsLoginClass();
            //u8Login.ConstructLogin(userToken);
            ////u8Login.UfDbPath = ztdb;

            //canshu.u8Login = u8Login;


            //MessageBox.Show(canshu.conStr);
            INetUserControl mycontrol = new MyNetUserControl();

            mycontrol.Title = cMenuName;
            base.ShowEmbedControl(mycontrol, cMenuId, true);



            return(null);
        }
Ejemplo n.º 16
0
 public void SetCredentials(string username, string password)
 {
     LoginInfo = new LoginObject {
         Salt = CipherUtility.GetNewSalt()
     };
     LoginInfo.EncryptedUsername = CipherUtility.Encrypt(username, LoginInfo.Salt);
     LoginInfo.EncryptedPassword = CipherUtility.Encrypt(password, LoginInfo.Salt);
     LoginInfo.PasswordSetDate   = DateTime.Now.Date;
 }
Ejemplo n.º 17
0
        public async Task <ActionResult> Login(string leagueKey, string hashedPassword)
        {
            //get the league, if not exist return notfound
            var league = await LeagueRepository.GetAsync(leagueKey);

            if (league == null)
            {
                return(new BadRequestObjectResult("failed"));
            }

            //check hashed password matches if not return error
            if (league.HashPassword != hashedPassword)
            {
                return(new BadRequestObjectResult("failed"));
            }

            //generate login key, insert into db
            var token = Guid.NewGuid().ToString();

            var login = new Login();

            login.LeagueId       = league.LeagueId;
            login.LoginTimestamp = DateTime.Now;
            login.Expiry         = DateTime.Now.AddHours(1);
            login.LoginKey       = token;


            if (await LoginExistsForLeague(league.LeagueId))
            {
                try
                {
                    var oldLogin = await this.LoginRepository.GetAsync(league.LeagueId);

                    oldLogin.LoginTimestamp = DateTime.Now;
                    oldLogin.Expiry         = DateTime.Now.AddHours(1);
                    oldLogin.LoginKey       = token;

                    await this.LoginRepository.UpdateAsync(oldLogin);
                }
                catch (Exception ex)
                {
                    // handle somehow
                }
            }
            else
            {
                await this.LoginRepository.AddAsync(login);
            }
            // return login key
            LoginObject loginSuccess = new LoginObject(login);

            loginSuccess.LeagueId   = league.LeagueId;
            loginSuccess.LeagueName = league.LeagueName;
            loginSuccess.LeagueKey  = league.LeagueKey;
            loginSuccess.Logo       = league.Logo;
            return(new OkObjectResult(loginSuccess));
        }
Ejemplo n.º 18
0
        public void newLogin()
        {
            TmpLogObject              = new LoginObject();
            TmpLogObject.ID           = Guid.NewGuid();
            TmpLogObject.ChangeDate   = DateTime.Today;
            TmpLogObject.CreationDate = DateTime.Today;

            loading = false;
        }
Ejemplo n.º 19
0
    IEnumerator Submit()
    {
        WWW       www;
        Hashtable postHeader = new Hashtable();

        postHeader.Add("Content-Type", "application/json");

        LoginObject postData = new LoginObject();

        postData.Username = userName.text;
        postData.Password = userPassword.text;

        var jsonData = JsonMapper.ToJson(postData);

        //var formData = System.Text.Encoding.UTF8.GetBytes("{'Username':'******', 'Password':'******'}");
        if (Constant.CheckNetworkAvailability())
        {
            www = new WWW(Constant.LOGIN_URL, System.Text.Encoding.UTF8.GetBytes(jsonData), postHeader);

            yield return(www);

            if (www.text.Equals("null"))
            {
                alertText.text = "Check Your User Name Password";
            }
            //else if (www.text != null)
            //{
            //    string[] msg = www.text.Split(char.Parse(":"));
            //    if (msg[1].Equals("\"An error has occurred.\"}"))
            //    {
            //        print("An error has occurred!!!!!!!!!!!!!");
            //    }
            //}
            else
            {
                Debug.Log("request success");
                alertText.text = "Login Success";
                landingPanel.SetActive(true);

                //loginPannel.enabled = false;
                print(www.text);

                var userData = JsonMapper.ToObject <PlayerObject>(www.text);
                PlayerPrefsUtil.SavePlayer(userData);
                titleText.text = "Hi " + userData.Name.ToString();
                loggedUsername = userData.Name;

                StartCoroutine(Deactivatetext());
            }
        }
        else
        {
            SSTools.ShowMessage("No Network Connection", SSTools.Position.bottom, SSTools.Time.oneSecond);
        }
    }
Ejemplo n.º 20
0
 public async Task StartConnectionAsync(string uri, LoginObject user)
 {
     UserInfor = user;
     //await _clientWebSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);
     SendLogin();
     // await Receive(_clientWebSocket, (message) =>
     // {
     //     Invoke(message);
     // });
 }
Ejemplo n.º 21
0
        public void SetDataLogin(LoginObject auth)
        {
            try
            {
                UserDetails.Username    = EmailEditText.Text;
                UserDetails.FullName    = EmailEditText.Text;
                UserDetails.Password    = PasswordEditText.Text;
                UserDetails.AccessToken = auth.AccessToken;
                if (auth.Data.Id != null)
                {
                    UserDetails.UserId = auth.Data.Id;
                }
                UserDetails.Status = "Active";
                UserDetails.Cookie = auth.AccessToken;
                UserDetails.Email  = EmailEditText.Text;

                Current.AccessToken = auth.AccessToken;

                //Insert user data to database
                var user = new DataTables.LoginTb
                {
                    UserId      = UserDetails.UserId.ToString(),
                    AccessToken = UserDetails.AccessToken,
                    Cookie      = UserDetails.Cookie,
                    Username    = EmailEditText.Text,
                    Password    = PasswordEditText.Text,
                    Status      = "Active",
                    Lang        = "",
                    DeviceId    = UserDetails.DeviceId
                };
                ListUtils.DataUserLoginList.Clear();
                ListUtils.DataUserLoginList.Add(user);

                UserDetails.IsLogin = true;

                var dbDatabase = new SqLiteDatabase();
                dbDatabase.InsertOrUpdateLogin_Credentials(user);

                if (auth.Data != null)
                {
                    ListUtils.MyUserInfoList.Add(auth.Data);
                    PollyController.RunRetryPolicyFunction(new List <Func <Task> > {
                        () => ApiRequest.GetInfoData(this, UserDetails.UserId.ToString())
                    });
                }

                dbDatabase.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 22
0
        public static async Task <T?> CallAction <T>(DeviceObject device, LoginObject loginObject, string action, object?param, bool eventListener = false)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device), "The device can't be null.");
            }
            if (string.IsNullOrEmpty(device.Id))
            {
                throw new ArgumentException("The id of the device is empty. Please call again the GetDevices Method and try again.", nameof(device));
            }

            var query            = $"/t_{HttpUtility.UrlEncode(loginObject.SessionToken)}_{HttpUtility.UrlEncode(device.Id)}{action}";
            var callActionObject = new CallActionObject
            {
                ApiVer    = 1,
                Params    = param,
                RequestId = GetUniqueRid(),
                Url       = action
            };

            var url           = ApiUrl + query;
            var json          = JsonConvert.SerializeObject(callActionObject);
            var encryptedJson = await Encrypt(json, loginObject.DeviceEncryptionToken);

            var encryptedResponse = await PostMethod(url, encryptedJson, eventListener);

            if (encryptedResponse == null)
            {
                throw new Exception("Server response is empty");
            }

            var decryptedResponse = await Decrypt(encryptedResponse, loginObject.DeviceEncryptionToken);

            if (decryptedResponse == null)
            {
                throw new Exception("Can't decrypt message");
            }

            //special case as event responses are completly differerent
            if (decryptedResponse.Contains("subscriptionid"))
            {
                var direct = JsonConvert.DeserializeObject <T>(decryptedResponse);
                if (direct != null)
                {
                    return(direct);
                }
            }

            var res = JsonConvert.DeserializeObject <ApiObjects.DefaultReturnObject>(decryptedResponse);

            if (res?.Data == null)
            {
                return(default);
        public static Server.Models.Client Login(AdvanceStream stream, string loginData)
        {
            // To generate private key for RSA if not exist
            RSA rsa = new RSA(LoginObject.newLoginObject(loginData).username);

            KeyManager.generateRSAPublicKey(rsa.rsaSP);
            KeyManager.generateRSAPrivateKey(rsa.rsaSP);

            stream.Write("1");
            stream.Write(KeyManager.RSAPublicKey);
            AES aes = AES.getInstance();

            byte[] msg = Encoding.UTF8.GetBytes(loginData);
            byte[] EncreptedLoginData = rsa.encrypte(msg, KeyManager.serverRSAPublicKey);

            MainWindow.instance.Log("Login Data", loginData);
            MainWindow.instance.Log("Encrypted Login Data", Encoding.UTF8.GetString(EncreptedLoginData));
            stream.Write(EncreptedLoginData);



            string response = stream.ReadString();

            if (response.Equals("0"))
            {
                //no user
                MainWindow.instance.Log("No such user");
                MainWindow.instance.Log();
                return(null);
            }
            else if (response.Equals("1"))
            {
                //wrong password
                MainWindow.instance.Log("Wrong Password");
                MainWindow.instance.Log();
                return(null);
            }
            else
            {
                //ok
                response = stream.ReadString();
                Server.Models.Client loginClient = Server.Models.Client.newClientObject(response);
                MainWindow.instance.Log(response);
                byte[] inStream  = stream.ReadBytes();
                byte[] decrypKey = rsa.decrypt(inStream, KeyManager.RSAPrivateKey);
                MainWindow.instance.Log("Encrypted AES Key", Convert.ToBase64String(inStream, 0, inStream.Length));
                KeyManager.serverAESPublicKey = Convert.ToBase64String(decrypKey, 0, decrypKey.Length);
                MainWindow.instance.Log("AES Key", KeyManager.serverAESPublicKey);


                return(loginClient);
            }
        }
Ejemplo n.º 24
0
        public async Task <int> UserLogin(string email, string hashedPassword)
        {
            DataUtility.IgnoreBadCertificates();

            string userID       = "";
            string userEmail    = "";
            string userPassword = "";

            string loginUrl = ConfigurationManager.AppSettings["ServerAddress"] + ConfigurationManager.AppSettings["LoginFunction"];
            string json     = "{\"email\": \"" + email + "\", \"password\": \"" + hashedPassword + "\"}";

            HttpWebRequest request = await Task.Run(() => dataUtility.SendHttp(json, loginUrl));

            //validate
            if (request == null)
            {
                return(-1);
            }

            LoginObject loginObject = await Task.Run(() => ReceiveLoginHttp(request));

            //validate
            if (loginObject.Result == false)
            {
                return(0);
            }
            else
            {
                userID       = loginObject.UserID;
                userEmail    = loginObject.UserLoginEmail;
                userPassword = loginObject.UserLoginPassword;

                if (userEmail == email && userPassword == hashedPassword)
                {
                    if (userID != "")
                    {
                        App.Current.Properties["UserID"]    = userID;
                        App.Current.Properties["UserEmail"] = userEmail;
                    }
                    else
                    {
                        return(0);
                    }
                }
                else
                {
                    return(0);
                }

                return(1);
            }
        }
        /// <summary>
        /// Disconnects the your client from the api
        /// </summary>
        /// <returns>True if successful else false</returns>
        public bool Disconnect()
        {
            string query    = $"/my/disconnect?sessiontoken={HttpUtility.UrlEncode(LoginObject.SessionToken)}";
            var    response = _apiHandler.CallServer <object>(query, LoginObject.ServerEncryptionToken);

            if (response == null)
            {
                return(false);
            }

            LoginObject = null;
            return(true);
        }
Ejemplo n.º 26
0
        public async Task <HttpResponseMessage> Post([FromBody] LoginObject value)
        {
            var result     = new Result();
            var tokenLogin = false;
            var apnaLogin  = false;


            var employer = new EmployerEntity();

            PropertyCopier <LoginObject, EmployerEntity> .Copy(value, employer);

            var token = Request.Headers.Authorization;

            if (token != null)
            {
                tokenLogin = true;
                result     = _employersManager.Login(token.Parameter);
            }

            if ((string.IsNullOrEmpty(employer.Email) || string.IsNullOrEmpty(employer.Password)) && !tokenLogin)
            {
                result = new Result(false);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }

            if (!tokenLogin && !apnaLogin)
            {
                result    = _employersManager.Login(employer);
                apnaLogin = !result.Success;
            }


            var employer_model = new EmployerModel();
            var employerEntity = (EmployerEntity)result.Entity;

            if (!result.Success)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, result));
            }
            employer_model.Token = employerEntity.Token;
            PropertyCopier <EmployerEntity, EmployerModel> .Copy(employerEntity, employer_model);

            if (token != null)
            {
                employer_model.Token = token.Parameter;
            }


            result.Entity = employer_model;
            return(Request.CreateResponse(HttpStatusCode.OK, result));
        }
Ejemplo n.º 27
0
        public async Task <bool> AuthenticateAsync(LoginObject login)
        {
            try
            {
                AuthenticatedUser = await _client.LoginAsync("custom", JObject.FromObject(login));

                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(@"ERROR - AUTHENTICATION FAILED {0}", ex.Message);
                return(false);
            }
        }
Ejemplo n.º 28
0
 public bool LoginUser(LoginObject loginObject)
 {
     try
     {
         if (loginObject.UserName == "admin" && loginObject.Password == "Admin")
         {
             return(true);
         }
     }
     catch (Exception ex)
     {
         LogWriter.LogWrite(ex.ToString());
     }
     return(false);
 }
        private void SetDataLogin(LoginObject auth)
        {
            try
            {
                UserDetails.Username    = auth.Data.UserInfo.Email;
                UserDetails.FullName    = auth.Data.UserInfo.Fullname;
                UserDetails.Password    = auth.Data.UserInfo.Password;
                UserDetails.AccessToken = auth.Data.AccessToken;
                UserDetails.UserId      = auth.Data.UserId;
                UserDetails.Status      = "Pending";
                UserDetails.Cookie      = auth.Data.AccessToken;
                UserDetails.Email       = auth.Data.UserInfo.Email;

                Current.AccessToken = auth.Data.AccessToken;

                //Insert user data to database
                var user = new DataTables.LoginTb
                {
                    UserId      = UserDetails.UserId.ToString(),
                    AccessToken = UserDetails.AccessToken,
                    Cookie      = UserDetails.Cookie,
                    Username    = auth.Data.UserInfo.Email,
                    Password    = auth.Data.UserInfo.Password,
                    Status      = "Pending",
                    Lang        = "",
                    DeviceId    = UserDetails.DeviceId,
                };
                ListUtils.DataUserLoginList.Add(user);

                var dbDatabase = new SqLiteDatabase();
                dbDatabase.InsertOrUpdateLogin_Credentials(user);

                if (auth.Data.UserInfo != null)
                {
                    dbDatabase.InsertOrUpdate_DataMyInfo(auth.Data.UserInfo);

                    PollyController.RunRetryPolicyFunction(new List <Func <Task> > {
                        () => ApiRequest.GetInfoData(this, UserDetails.UserId.ToString())
                    });
                }

                dbDatabase.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 30
0
        public T CallAction <T>(DeviceObject device, string action, object param, LoginObject loginObject,
                                bool decryptResponse = false)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }
            if (string.IsNullOrEmpty(device.Id))
            {
                throw new ArgumentException(
                          "The id of the device is empty. Please call again the GetDevices Method and try again.");
            }

            string query =
                $"/t_{HttpUtility.UrlEncode(loginObject.SessionToken)}_{HttpUtility.UrlEncode(device.Id)}{action}";
            CallActionObject callActionObject = new CallActionObject
            {
                ApiVer    = 1,
                Params    = param,
                RequestId = GetUniqueRid(),
                Url       = action
            };

            //Regex _regex = new Regex("http\\:\\/\\/(192.168.*)\\:37733");
            //var match = _regex.Match(_apiUrl);
            //if (match.Success)
            //{
            //    _apiUrl = _apiUrl.Replace(match.Groups[0].Value, "89.163.144.231");
            //}
            string url = _apiUrl + query;
            //url = url.Replace("172.23.0.8", "89.163.144.231");
            string json = JsonConvert.SerializeObject(callActionObject);

            json = Encrypt(json, loginObject.DeviceEncryptionToken);
            string response = PostMethod(url,
                                         json, loginObject.DeviceEncryptionToken);

            if (response != null || !response.Contains(callActionObject.RequestId.ToString()))
            {
                if (decryptResponse)
                {
                    string tmp = Decrypt(response, loginObject.DeviceEncryptionToken);
                    return((T)JsonConvert.DeserializeObject(tmp, typeof(T)));
                }
                throw new InvalidRequestIdException("The 'RequestId' differs from the 'Requestid' from the query.");
            }
            return((T)JsonConvert.DeserializeObject(response, typeof(T)));
        }
Ejemplo n.º 31
0
    public static void ToCharacterSelection(int _clientId, LoginObject _userData)
    {
        int clientId = _clientId;

        using (Packet _packet = new Packet((int)ServerPackets.toCharacterSelection))
        {
            _packet.Write(_userData.characters.Length);
            foreach (CharacterLoginObject characters in _userData.characters)
            {
                _packet.Write(characters.characterName);
                _packet.Write(characters.characterClass);
            }

            SendTCPData(clientId, _packet);
        }
    }
 public void UserLogin(String name, String passwd, Socket handler, LoginObject login, IPEndPoint clientipe)
 {
     if (userInfo.Contains(name))
     {
         if (GetTokenByName(name) =="")
         {
             if (((String)userInfo[name]).Equals(passwd))
             {
                 String token = GenerateToken(name, clientipe.Address.ToString(), clientipe.Port.ToString());
                 //MessageBox.Show("[" + clientipe.Address.ToString() + ":" + clientipe.Port.ToString() + "] login successfully.");
                 string[] arg = { token, name };
                 Send(handler, DealObject.Serialize(new ResponseObject("login ack", -1, arg)));
                 foreach (OnlineUser value in OnlineInfo.Values)
                 {
                     string[] args = { name };
                     Send(value.WorkSocket, DealObject.Serialize(new ResponseObject("online user", -1, args)));
                 }
                 OnlineInfo.Add(token, new OnlineUser(handler, name, token, login.publicKey));
             }
             else
             {
                 //MessageBox.Show("[" + clientipe.Address.ToString() + ":" + clientipe.Port.ToString() + "] login faild: password wrong.");
                 Send(handler, DealObject.Serialize(new NotificationObject("Password wrong.")));
             }
         }
         else
         {
             Send(handler, DealObject.Serialize(new NotificationObject("This user has logged in in another place..")));
         }
     }
     else
     {
         //MessageBox.Show("[" + clientipe.Address.ToString() + ":" + clientipe.Port.ToString() + "] login faild: Username not registered.");
         Send(handler, DealObject.Serialize(new NotificationObject("User name not registered")));
     }
 }