Ejemplo n.º 1
0
 public bool Store(AuthData data)
 {
     GD.Delete (m_realm, new string[1] {"UUID"}, new object[1] { data.PrincipalID });
     return GD.Insert (m_realm, new string[] { "UUID", "passwordHash", "passwordSalt",
         "webLoginKey", "accountType" }, new object[] { data.PrincipalID, 
             data.PasswordHash, data.PasswordSalt, data.WebLoginKey, data.AccountType });
 }
Ejemplo n.º 2
0
        public static Task<string> AddUserDailyTask(AuthData authData, UserDailyVM d)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<string>();

            EventHandler<AddUserDailyCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.AddUserDailyCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.AddUserDailyCompleted += handler;
            client.AddUserDailyAsync(authData, d);

            return tcs.Task;
        }
Ejemplo n.º 3
0
        public static Task<LebensmittelConsumedVM> AddConsumedTask(AuthData authData, string p1, float p2, int daytime, DateTime currentDate)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<LebensmittelConsumedVM>();

            AddConsumedResponse a;

            EventHandler<AddConsumedCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.AddConsumedCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.AddConsumedCompleted += handler;
            client.AddConsumedAsync(authData, p1, p2, daytime, currentDate);

            return tcs.Task;
        }
Ejemplo n.º 4
0
        public static Task<LebensmittelVM> AddFoodTask(AuthData authData, LebensmittelVM lebensmittelItem)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<LebensmittelVM>();

            EventHandler<AddFoodCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.AddFoodCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.AddFoodCompleted += handler;
            client.AddFoodAsync(authData, lebensmittelItem);

            return tcs.Task;
        }
Ejemplo n.º 5
0
 public AuthData Get(UUID principalID, string authType)
 {
     List<string> query = GD.Query (new string[2] { "UUID", "accountType" }, new object[2] { principalID.ToString (), authType }, m_realm, "*");
     AuthData data = null;
     for (int i = 0; i < query.Count; i += 5)
     {
         data = new AuthData();
         data.PrincipalID = UUID.Parse(query[i]);
         data.PasswordHash = query[i + 1];
         data.PasswordSalt = query[i + 2];
         data.AccountType = query[i + 3];
     }
     return data;
 }
Ejemplo n.º 6
0
 public AuthData Get(UUID principalID)
 {
     List<string> query = GD.Query("UUID", principalID.ToString(), m_realm, "*");
     AuthData data = null;
     for (int i = 0; i < query.Count; i += 5)
     {
         data = new AuthData();
         data.PrincipalID = UUID.Parse(query[i]);
         data.PasswordHash = query[i + 1];
         data.PasswordSalt = query[i + 2];
         data.WebLoginKey = query[i + 3];
         data.AccountType = query[i + 4];
     }
     return data;
 }
Ejemplo n.º 7
0
 /* ************************************
  *             FACEBOOK               *
  **************************************
  */
 private void onFacebookAccessTokenChange(AccessToken token)
 {
     if (token != null)
     {
         mAuthProgressDialog.show();
         mFirebaseRef.authWithOAuthToken("facebook", token.Token, new AuthResultHandler(this, "facebook"));
     }
     else
     {
         // Logged out of Facebook and currently authenticated with Firebase using Facebook, so do a logout
         if (this.mAuthData != null && this.mAuthData.Provider.Equals("facebook"))
         {
             mFirebaseRef.unauth();
             AuthenticatedUser = null;
         }
     }
 }
Ejemplo n.º 8
0
        private void CheckToken()
        {
            if (_token == null)
            {
                throw new UnauthorizedAccessException("Cannot create GoogleDrive session with given token");
            }
            if (_token.IsExpired)
            {
                _token = OAuth20TokenHelper.RefreshToken <GoogleLoginProvider>(_token);

                using (var dbDao = new CachedProviderAccountDao(CoreContext.TenantManager.GetCurrentTenant().TenantId, FileConstant.DatabaseId))
                {
                    var authData = new AuthData(token: _token.ToJson());
                    dbDao.UpdateProviderInfo(ID, authData);
                }
            }
        }
Ejemplo n.º 9
0
        public static void MakeGetRequest(AuthData authData, string url, Dictionary<string, string> param, DownloadStringCompletedEventHandler handler)
        {
            url += "?";
            foreach (KeyValuePair<string, string> keyValuePair in param)
            {
                url += String.Format("{0}={1}&", keyValuePair.Key, keyValuePair.Value);
            }

            if (url[url.Length - 1] == '&')
            {
                url = url.Substring(0, url.Length - 1);
            }

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += handler;
            wc.DownloadStringAsync(new Uri(url));
        }
Ejemplo n.º 10
0
        public virtual bool SetPasswordHashed(UUID principalID, string authType, string Hashedpassword)
        {
            string passwordSalt  = Util.Md5Hash(UUID.Random().ToString());
            string md5PasswdHash = Util.Md5Hash(Hashedpassword + ":" + passwordSalt);

            AuthData auth = m_Database.Get(principalID, authType);

            if (auth == null)
            {
                auth = new AuthData {
                    PrincipalID = principalID, AccountType = authType
                };
            }
            auth.PasswordHash = md5PasswdHash;
            auth.PasswordSalt = passwordSalt;
            return(SaveAuth(auth, principalID));
        }
Ejemplo n.º 11
0
        public IActionResult Login([FromBody] AuthData authData)
        {
            string passwordHash = usersRep.GetUserPassHashForCompare(authData.Email);

            if (passwordHash == "0" || !BCrypt.Net.BCrypt.Verify(authData.Password, passwordHash))
            {
                _logger.LogInformation("User with email " + authData.Email + " Signed in");
                return(BadRequest());
            }

            int reqData = usersRep.GetUserIdForAuth(authData.Email);

            Response.Cookies.Append("userId", reqData.ToString());

            _logger.LogInformation("User with email " + authData.Email + " Signed in");
            return(Ok());
        }
Ejemplo n.º 12
0
        public async Task <AuthData> AuthenticateAsync()
        {
            var authContext = new AuthenticationContext(azureSettings.Authority);
            var clientCred  = new ClientCredential(azureSettings.ClientId, azureSettings.Secret);
            var result      = await authContext.AcquireTokenAsync(azureSettings.ResourceId, clientCred);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            var authData = new AuthData {
                Scheme = AuthScheme.BEARER, PasswordOrToken = result.AccessToken
            };

            return(authData);
        }
Ejemplo n.º 13
0
        public AuthResult Post(AuthData data)
        {
            var adminUsername = WebConfigurationManager.AppSettings["adminUsername"];
            var adminPassword = WebConfigurationManager.AppSettings["adminPassword"];

            if (adminUsername != data.Username || adminPassword != data.Password)
            {
                log.Warn($"Invalid credentials on authentication. Username: { data.Username }");
                return(new AuthResult(false, string.Empty, DateTime.UtcNow));
            }

            var result = this.jwtTools.GetToken(data.Username);

            log.Info($"Successful authentication. Username: { data.Username }");

            return(new AuthResult(true, result.Token, result.ExpirationTime));
        }
Ejemplo n.º 14
0
        public void SignUp(AuthData authData_, Action onSuccess_, Action onFail_)
        {
            ParseUser user = new ParseUser();

            user.Add("Username", authData_.username);
            user.Add("Email", authData_.email);
            user.Add("Password", authData_.password);
            user.SignUpAsync().ContinueWith((Task task_) => {
                if (task_.IsCanceled || task_.IsFaulted)
                {
                    onFail_();
                }
                else
                {
                    onSuccess_();
                }
            });
        }
Ejemplo n.º 15
0
 public AuthData AuthById(int id)
 {
     using (StreamReader r = new StreamReader("/home/student/data/users.json"))
     {
         string json = r.ReadToEnd();
         try {
             UserData user = JsonConvert.DeserializeObject <Dictionary <string, UserData> >(json)[id.ToString()];
             var      data = new AuthData {
                 email    = user.email,
                 password = user.password,
                 salt     = user.salt
             };
             return(data);
         } catch (System.Collections.Generic.KeyNotFoundException e) {
             return(new AuthData());
         }
     }
 }
Ejemplo n.º 16
0
 public bool Store(AuthData data)
 {
     GD.Delete(m_realm, new string[2] {
         "UUID", "accountType"
     }, new object[2] {
         data.PrincipalID, data.AccountType
     });
     return(GD.Insert(m_realm, new[]
     {
         "UUID", "passwordHash", "passwordSalt",
         "accountType"
     }, new object[]
     {
         data.PrincipalID,
         data.PasswordHash.MySqlEscape(1024), data.PasswordSalt.MySqlEscape(1024),
         data.AccountType.MySqlEscape(32)
     }));
 }
Ejemplo n.º 17
0
        public virtual int UpdateProviderInfo(int linkId, AuthData authData)
        {
            var forUpdate = FilesDbContext.ThirdpartyAccount
                            .Where(r => r.Id == linkId)
                            .Where(r => r.TenantId == TenantID)
                            .ToList();

            foreach (var f in forUpdate)
            {
                f.UserName = authData.Login ?? "";
                f.Password = EncryptPassword(authData.Password);
                f.Token    = EncryptPassword(authData.Token ?? "");
                f.Url      = authData.Url ?? "";
            }

            FilesDbContext.SaveChanges();

            return(forUpdate.Count == 1 ? linkId : default);
Ejemplo n.º 18
0
        public static void MakeGetRequest(AuthData authData, string url, Dictionary <string, string> param, DownloadStringCompletedEventHandler handler)
        {
            url += "?";
            foreach (KeyValuePair <string, string> keyValuePair in param)
            {
                url += String.Format("{0}={1}&", keyValuePair.Key, keyValuePair.Value);
            }

            if (url[url.Length - 1] == '&')
            {
                url = url.Substring(0, url.Length - 1);
            }

            WebClient wc = new WebClient();

            wc.DownloadStringCompleted += handler;
            wc.DownloadStringAsync(new Uri(url));
        }
        /// <summary>
        /// Gets the Auth Data to pass to Poniverse for proper login
        /// </summary>
        private static AuthData GetAuthData(CookieAwareWebClient c = null)
        {
            string url = "http://canterlotavenue.com/ponauth/";

            //Get the Poniverse URL
            //window\.location\.replace\("(.+)"\);
            if (c == null)
            {
                c = new CookieAwareWebClient();
            }

            string s = c.DownloadString(url);
            string poniverse_oauth = ExtractPoniverseOauth(s);

            AuthData d = new AuthData(poniverse_oauth);

            return(d);
        }
Ejemplo n.º 20
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (MechName.Length != 0)
            {
                hash ^= MechName.GetHashCode();
            }
            if (AuthData.Length != 0)
            {
                hash ^= AuthData.GetHashCode();
            }
            if (InitialResponse.Length != 0)
            {
                hash ^= InitialResponse.GetHashCode();
            }
            return(hash);
        }
Ejemplo n.º 21
0
        public async Task <Answer> GetOrderState(AuthData authData, string visit_id)
        {
            if (!Initialized)
            {
                Init(baseUrl);
            }
            Answer answer = new Answer();

            try
            {
                answer = await api.GetOrderState(authData, visit_id);
            }
            catch (Exception e)
            {
                return(ErrorHandler.HandleException(e));
            }
            return(answer);
        }
Ejemplo n.º 22
0
        public async Task <Answer> GetQRCode(AuthData authData, Geoposition geopos)
        {
            if (!Initialized)
            {
                Init(baseUrl);
            }
            Answer answer = new Answer();

            try
            {
                answer = await api.GetQRCode(authData, geopos);
            }
            catch (Exception e)
            {
                return(ErrorHandler.HandleException(e));
            }
            return(answer);
        }
        public async Task LoginUser([FromBody] AuthData user)
        {
            TokenProvider _tokenProvider = new TokenProvider(db);
            var           userToken      = _tokenProvider.LoginUser(user.Login.Trim(), user.Password.Trim());

            if (userToken == null)
            {
                Response.StatusCode = 401;
                await Response.WriteAsync("Invalid username or password.");
            }
            else
            {
                Response.ContentType = "application/json";
                await Response.WriteAsync(JsonConvert.SerializeObject(userToken, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));
            }
        }
        /// <summary>
        /// HTTPs the client request.
        /// </summary>
        /// <param name="bodyEntity">The body entity.</param>
        /// <param name="request">The request.</param>
        /// <returns>The uniqueidentifer</returns>
        /// <exception cref="System.Exception">
        /// Unable to create the journal entry.
        /// or
        /// Error creating the journal entry.
        /// </exception>
        private async static Task <String> RequestData(string request, AuthData authData)
        {
            try
            {
                HttpResponseMessage responseContent = await Utils.HttpClientRequest(null, request, authData);

                if (responseContent.IsSuccessStatusCode)
                {
                    var result = await responseContent.Content.ReadAsStringAsync();

                    dynamic oDataResponse = JsonConvert.DeserializeObject(result);

                    List <JournalEntry> journalEntry = oDataResponse.data.ToObject <List <JournalEntry> >();

                    List <(string, string, string, double, double)> lst = new List <(string, string, string, double, double)>();

                    foreach (var i in journalEntry)
                    {
                        lst.Add((i.PostingDate, i.NaturalKey, i.Company, i.TotalCredit.Value, i.TotalDebit.Value));
                    }

                    Console.WriteLine(lst.ToStringTable(
                                          new[] { "Posting Date", "Journal", "Company", "T. Credit", "T. Debit" },
                                          a => a.Item1, a => a.Item2, a => a.Item3, a => a.Item4, a => a.Item5));

                    return(result.ToString());
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;

                    Console.WriteLine(string.Concat("Failed. ", responseContent.ToString()));
                    string result = await(responseContent.Content).ReadAsStringAsync();
                    Console.WriteLine(string.Concat("Content: ", result));

                    throw new Exception("Unable to create the invoice.");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                throw new Exception("Error creating the invoice.");
            }
        }
Ejemplo n.º 25
0
        public static AuthResult Authorize(AuthData data)
        {
            Keys keys = GetKeys();

            if (data != null && keys != null && keys.Public.Equals(data.PublicKey))
            {
                var privateKey = keys.Private;
                var hashCheck  = General.Sha1Hash(data.Data + privateKey + data.PublicKey);
                if (hashCheck != null && hashCheck.Equals(data.Hash))
                {
                    var newToken          = General.Sha1Hash(privateKey + hashCheck + GetDateTimeFormatted());
                    var computersJsonFile = GetFile("~/App_Data/", "computers.json");
                    var computers         = new List <ComputerData>();
                    try
                    {
                        computers = JsonConvert.DeserializeObject <List <ComputerData> >(GetFileContents(computersJsonFile));
                    }
                    catch { }
                    var computerData = GetComputerData(data);
                    var computer     = computers.Where(c => c.Hash == computerData.Hash).FirstOrDefault();
                    if (computer == null)
                    {
                        computerData.IsOnline = true;
                        computers.Add(computerData);
                    }
                    else
                    {
                        computer.IsOnline = true;
                    }
                    var computersJson = JsonConvert.SerializeObject(computers);
                    try
                    {
                        File.WriteAllText(computersJsonFile, computersJson);
                    }
                    catch { }
                    return(new AuthResult()
                    {
                        Token = newToken,
                        IpExternal = data.IpExternal
                    });
                }
            }
            return(null);
        }
        /// <summary>
        /// HTTPs the client request.
        /// </summary>
        /// <param name="bodyEntity">The body entity.</param>
        /// <param name="request">The request.</param>
        /// <returns>The uniqueidentifer</returns>
        /// <exception cref="System.Exception">
        /// Unable to create the journal entry.
        /// or
        /// Error creating the journal entry.
        /// </exception>
        private async static Task <String> RequestData(string request, AuthData authData)
        {
            try
            {
                HttpResponseMessage responseContent = await Utils.HttpClientRequest(null, request, authData);

                if (responseContent.IsSuccessStatusCode)
                {
                    var result = await responseContent.Content.ReadAsStringAsync();

                    dynamic oDataResponse = JsonConvert.DeserializeObject(result);

                    List <Invoice> invoices = oDataResponse.data.ToObject <List <Invoice> >();

                    List <(string, string, string, string)> lst = new List <(string, string, string, string)>();

                    foreach (var i in invoices)
                    {
                        lst.Add((i.DueDate, i.NaturalKey, i.AccountingPartyName, i.Company));
                    }

                    Console.WriteLine(lst.ToStringTable(
                                          new[] { "Invoice", "Date", "Customer", "Company" },
                                          a => a.Item1, a => a.Item2, a => a.Item3, a => a.Item4));

                    return(result.ToString());
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;

                    Console.WriteLine(string.Concat("Failed. ", responseContent.ToString()));
                    string result = await(responseContent.Content).ReadAsStringAsync();
                    Console.WriteLine(string.Concat("Content: ", result));

                    throw new Exception("Unable to create the invoice.");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                throw new Exception("Error creating the invoice.");
            }
        }
Ejemplo n.º 27
0
        private async static Task <String> RequestData(string request, AuthData authData)
        {
            try
            {
                HttpResponseMessage responseContent = await Utils.HttpClientRequest(null, request, authData);

                if (responseContent.IsSuccessStatusCode)
                {
                    var result = await responseContent.Content.ReadAsStringAsync();

                    dynamic oDataResponse = JsonConvert.DeserializeObject(result);

                    List <Order> orders = oDataResponse.data.ToObject <List <Order> >();


                    List <Tuple <string, string, string, string> > lst = new List <Tuple <string, string, string, string> >();
                    foreach (var i in orders)
                    {
                        Tuple <string, string, string, string> item = new Tuple <string, string, string, string>(i.PostingDate, i.NaturalKey, i.BuyerCustomerPartyDescription, i.PayableAmount.Value.ToString());
                        lst.Add(item);
                    }
                    Console.WriteLine(lst.ToStringTable(
                                          new[] { "Date", "Order", "Customer", "Total" },
                                          a => a.Item1, a => a.Item2, a => a.Item3, a => a.Item4));

                    return(result.ToString());
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;

                    Console.WriteLine(string.Concat("Failed. ", responseContent.ToString()));
                    string result = await(responseContent.Content).ReadAsStringAsync();
                    Console.WriteLine(string.Concat("Content: ", result));

                    throw new Exception("Unable to create the order.");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                throw new Exception("Error creating the order.");
            }
        }
Ejemplo n.º 28
0
        private void btnReg2serv_Click(object sender, EventArgs e)
        {
            string pass1 = TBPass1.Text;
            string pass2 = TBPass2.Text;

            if (pass1 == pass2)
            {
                WebRequest req = WebRequest.Create("http://localhost:5000/api/reg");
                req.Method = "POST";
                AuthData auth_data = new AuthData();
                auth_data.login    = fieldUserName.Text;
                auth_data.password = pass1;
                string postData = JsonConvert.SerializeObject(auth_data);
                req.ContentType = "application/json";
                StreamWriter reqStream = new StreamWriter(req.GetRequestStream());
                reqStream.Write(postData);
                reqStream.Close();
                HttpWebResponse resp    = (HttpWebResponse)req.GetResponse();
                StreamReader    sr      = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                string          content = sr.ReadToEnd();
                sr.Close();
                int int_token = Convert.ToInt32(content, 10);
                if (int_token != -1)
                {
                    mForm.int_token             = int_token;
                    mForm.TextBox_username.Text = auth_data.login;
                    mForm.Show();
                    this.Visible = false;
                    SendMessage(new Message()
                    {
                        username = auth_data.login,
                        text     = " присоединился к чату",
                    });
                }
                else
                {
                    MessageBox.Show("Такой пользователь уже зарегистрирован, обратитесь к администратору");
                }
            }
            else
            {
                MessageBox.Show("Passwords don't match");
            }
        }
Ejemplo n.º 29
0
        public void UpdateUserAuthData(AuthData userData)
        {
            if (userData == null)
            {
                throw new ArgumentNullException("UserRegister object is null!");
            }

            var user = _userRepository.Find(x => x.EmailAddress.Equals(userData.EmailAddress)).SingleOrDefault();

            if (user == null)
            {
                throw new ItemNotFoundException();
            }

            user.EmailAddress = userData.EmailAddress;
            user.PasswordHash = userData.PasswordHash;

            _userRepository.Update(user);
        }
Ejemplo n.º 30
0
        private async void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            AuthData data = new AuthData()
            {
                user     = txtLogin.Text,
                password = txtPass.Password
            };
            var response = await ApiHelper.RequestInternalJson <AuthResponse>("api/v1/login", data, null);

            if (response.status == "success")
            {
                AppPersistent.Token = new AuthTokens()
                {
                    UserId = response.data.userId,
                    Token  = response.data.authToken
                };
                PageNavigationManager.SwitchToPage(new RoomsPage());
            }
        }
Ejemplo n.º 31
0
 public AuthData Get(UUID principalID, string authType)
 {
     QueryFilter filter = new QueryFilter();
     filter.andFilters["UUID"] = principalID;
     filter.andFilters["accountType"] = authType;
     List<string> query = GD.Query(new string[1] {"*"}, m_realm, filter, null, null, null);
     AuthData data = null;
     for (int i = 0; i < query.Count; i += 5)
     {
         data = new AuthData
                    {
                        PrincipalID = UUID.Parse(query[i]),
                        PasswordHash = query[i + 1],
                        PasswordSalt = query[i + 2],
                        AccountType = query[i + 3]
                    };
     }
     return data;
 }
Ejemplo n.º 32
0
        public async Task GetDHLPackages()
        {
            DHL24WebapiPortClient service = new DHL24WebapiPortClient();

            AuthData auth = new AuthData();

            auth.username = dhl_login;    //"BALTICAD";
            auth.password = dhl_password; //"r#Q,rwwJdh6IJQJ";

            progressBar.Maximum = 3;
            progressBar.Value   = 1;

            try
            {
                getMyShipmentsResponse response = await service.getMyShipmentsAsync(auth, dateTimePickerDHL.Value.ToString("yyyy-MM-dd"), DateTime.Today.ToString("yyyy-MM-dd"), 0);

                progressBar.PerformStep();
                listViewDHL.Items.Clear();
                foreach (ShipmentBasicData shipmentData in response.getMyShipmentsResult)
                {
                    String[]     arr = new String[7];
                    ListViewItem itm;

                    arr[0] = shipmentData.receiver.name;
                    arr[1] = shipmentData.receiver.contactPerson;
                    arr[2] = shipmentData.receiver.street + " " + shipmentData.receiver.houseNumber;
                    arr[3] = shipmentData.receiver.city;
                    arr[4] = shipmentData.receiver.contactEmail;
                    arr[5] = shipmentData.shipmentId;
                    arr[6] = "";

                    itm = new ListViewItem(arr);

                    listViewDHL.Items.Add(itm);
                }
                progressBar.PerformStep();
                listViewPocztaPolska.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                listViewPocztaPolska.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            } catch (Exception e)
            {
                MessageBox.Show("Wystąpił błąd podczas pobierania danych z API DHL. Treść błędu: " + e.Message);
            }
        }
Ejemplo n.º 33
0
        public ActionResult Login(string authData)
        {
            if (string.IsNullOrEmpty(authData))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var authDataDecoded = AuthData.Decode(authData);

            // basic scenarios perform well using in-memory session
            // advanced scenarios, please check session store
            Session.Add("BotId", authDataDecoded.BotId);
            Session.Add("userBotId", authDataDecoded.UserId);
            Session.Add("channelId", authDataDecoded.ChannelId);
            Session.Add("conversationId", authDataDecoded.ConversationId);
            Session.Add("serviceUrl", authDataDecoded.ServiceUrl);

            return(View());
        }
Ejemplo n.º 34
0
        public void SetUser(string username, string password)
        {
            username = username.ToLower().Trim();
            var salt = Hasher.GenerateSalt();

            _userDictionary[username] = new AuthData()
            {
                PasswordHash = Hasher.HashPassword(password, salt),
                PasswordSalt = salt,
                Username     = username
            };
            foreach (var k in _sessionMap)
            {
                if (k.Value.Username == username)
                {
                    _sessionMap.Remove(k.Key);
                }
            }
        }
Ejemplo n.º 35
0
        private AuthData GetUserData()
        {
            AuthData authData = null;

            try
            {
                authData = Helpers.JsonSerializer.DeserializeFromFile <AuthData>(m_AuthDataFile);
            }
            catch
            {
            }

            if (authData == null)
            {
                authData = new AuthData();
            }

            return(authData);
        }
Ejemplo n.º 36
0
        public static async Task <GameData> getGameData(AuthData data)
        {
            var httpClient = new HttpClient();

            HttpContent sendContent = Json.generateRequestGameDataJson(data);
            var         response    = await httpClient.PostAsync(QueryApi.SERVER + QueryApi.QUERY_GET_DATA, sendContent);

            var respBody = await response.Content.ReadAsStringAsync();

            respBody.Remove(0, 1);
            if (response.IsSuccessStatusCode)
            {
                GameData constructedData = Json.parseGameDataJson(respBody);
                return(constructedData);
            }

            Message.show((int)response.StatusCode);
            return(null);
        }
Ejemplo n.º 37
0
    private IEnumerator executeLogin()
    {
        Debug.Log("clicked");

        AuthData auth          = new AuthData(loginText.text, passwordText.text);
        String   requestString = auth.toJson();

        Debug.Log("requestString: " + requestString);

        System.Collections.Generic.Dictionary <string, string> headers = new System.Collections.Generic.Dictionary <string, string>();
        headers.Add("Content-Type", "application/json");

        var encoding = new System.Text.UTF8Encoding();
        WWW request  = new WWW(LOGIN_URI, encoding.GetBytes(requestString), headers);

        yield return(request);

        LoginResponse jResponse = JsonUtility.FromJson <LoginResponse>(request.text);

        hideProgress();
        // Print the error to the console
        if (request.error != null)
        {
            Debug.Log("request error: " + request.error);
            showDialog("request error: " + request.error);
        }
        else
        {
            if (!String.IsNullOrEmpty(jResponse.message))
            {
                Debug.Log("request error: " + jResponse.message);
                showDialog(jResponse.message);
            }
            else
            {
                AppGlobal.token        = jResponse.token;
                AppGlobal.finalText    = jResponse.finalText;
                AppGlobal.finalTextUrl = jResponse.finalTextUrl;
                AppGlobal.youtubeUrl   = jResponse.youtubeUrl;
                SceneManager.LoadScene("MainMenu");
            }
        }
    }
Ejemplo n.º 38
0
        public virtual bool SetPassword(UUID principalID, string authType, string password)
        {
            string passwordSalt = Util.Md5Hash(UUID.Random().ToString());
            string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + passwordSalt);

            AuthData auth = m_Database.Get(principalID, authType);
            if (auth == null)
            {
                auth = new AuthData {PrincipalID = principalID, AccountType = authType};
            }
            auth.PasswordHash = md5PasswdHash;
            auth.PasswordSalt = passwordSalt;
            if (!m_Database.Store(auth))
            {
                MainConsole.Instance.DebugFormat("[AUTHENTICATION DB]: Failed to store authentication data");
                return false;
            }

            MainConsole.Instance.InfoFormat("[AUTHENTICATION DB]: Set password for principalID {0}", principalID);
            return true;
        }
Ejemplo n.º 39
0
 public override int UpdateProviderInfo(int linkId, string customerTitle, AuthData authData, FolderType folderType)
 {
     ProviderCache.Reset(_rootKey, linkId.ToString(CultureInfo.InvariantCulture));
     return base.UpdateProviderInfo(linkId, customerTitle, authData, folderType);
 }
Ejemplo n.º 40
0
        private static AuthData GetEncodedAccesToken(AuthData authData, string providerName)
        {
            var prName = (nSupportedCloudConfigurations) Enum.Parse(typeof (nSupportedCloudConfigurations), providerName, true);
            if (prName != nSupportedCloudConfigurations.Google)
                return authData;

            var tokenSecret = ImportConfiguration.GoogleTokenManager.GetTokenSecret(authData.Token);
            var consumerKey = ImportConfiguration.GoogleTokenManager.ConsumerKey;
            var consumerSecret = ImportConfiguration.GoogleTokenManager.ConsumerSecret;

            var accessToken = GoogleDocsAuthorizationHelper.BuildToken(authData.Token, tokenSecret, consumerKey, consumerSecret);
            var storage = new CloudStorage();

            authData.Token = storage.SerializeSecurityTokenToBase64Ex(accessToken, typeof (GoogleDocsConfiguration), null);
            return authData;
        }
Ejemplo n.º 41
0
 private static IProviderInfo ToProviderInfo(int id, string providerName, string customerTitle, AuthData authData, string owner, FolderType type, DateTime createOn)
 {
     return ToProviderInfo(new object[] {id, providerName, customerTitle, authData.Login, EncryptPassword(authData.Password), authData.Token, owner, (int) type, createOn});
 }
Ejemplo n.º 42
0
        public static Task<AsyncCompletedEventArgs> SendFeedbackTask(AuthData authData, string feedback)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<AsyncCompletedEventArgs>();

            EventHandler<AsyncCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.SendFeedbackCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e);
                }
            };

            client.SendFeedbackCompleted += handler;
            client.SendFeedbackAsync(authData, feedback);

            return tcs.Task;
        }
Ejemplo n.º 43
0
        public static Task<ObservableCollection<LebensmittelConsumedVM>> GetConsumedTask(AuthData token, int daytime, DateTime date)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<ObservableCollection<LebensmittelConsumedVM>>();

            //GetConsumedResponse a;

            EventHandler<GetConsumedCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetConsumedCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetConsumedCompleted += handler;
            client.GetConsumedAsync(token, daytime, date);

            return tcs.Task;
        }
Ejemplo n.º 44
0
        public static Task<ObservableCollection<NutritionPlanVM>> GetNutritionPlans(AuthData a)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<ObservableCollection<NutritionPlanVM>>();

            EventHandler<GetNutritionPlansCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetNutritionPlansCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetNutritionPlansCompleted += handler;
            client.GetNutritionPlansAsync(a);

            return tcs.Task;
        }
Ejemplo n.º 45
0
        public static Task<ObservableCollection<UserDailyVM>> GetUserDailyRangeTask(AuthData authData, int i, int p)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<ObservableCollection<UserDailyVM>>();

            EventHandler<GetUserDailyRangeCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetUserDailyRangeCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetUserDailyRangeCompleted += handler;
            client.GetUserDailyRangeAsync(authData, i, p);

            return tcs.Task;
        }
			public override void onAuthenticated(AuthData authData)
			{
				Log.v(TAG, "Authentication worked");
			}
Ejemplo n.º 47
0
        public static Task<string> UpdateUserGoalTask(AuthData a, UserGoalVM data)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<string>();

            EventHandler<UpdateUserGoalCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.UpdateUserGoalCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.UpdateUserGoalCompleted += handler;
            client.UpdateUserGoalAsync(a, data);

            return tcs.Task;
        }
Ejemplo n.º 48
0
        public static Task SetTrainingExerciseTask(AuthData authData, TrainingExerciseVM item)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<TrainingDayVM>();

            EventHandler<SetTrainingExerciseCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.SetTrainingExerciseCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.SetTrainingExerciseCompleted += handler;
            client.SetTrainingExerciseAsync(authData, item);

            return tcs.Task;
        }
Ejemplo n.º 49
0
        public static Task<NutritionPlanFavoriteVM> SetNutritionPlanFavoriteTask(AuthData a, NutritionPlanFavoriteVM fav)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<NutritionPlanFavoriteVM>();

            EventHandler<SetNutritionPlanFavoriteCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.SetNutritionPlanFavoriteCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.SetNutritionPlanFavoriteCompleted += handler;
            client.SetNutritionPlanFavoriteAsync(a, fav);

            return tcs.Task;
        }
Ejemplo n.º 50
0
        public static Task<int> SetFoodTask(AuthData authData, LebensmittelVM lebensmittelItem)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<int>();

            tcs.SetResult(0);

            client.SetFoodAsync(authData, lebensmittelItem);

            return tcs.Task;
        }
Ejemplo n.º 51
0
        public static Task<bool> SetConsumedTask(AuthData authData, LebensmittelConsumedVM cons)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<bool>();

            AddConsumedResponse a;

            EventHandler<SetConsumedCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.SetConsumedCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.SetConsumedCompleted += handler;
            client.SetConsumedAsync(authData, cons);

            return tcs.Task;
        }
Ejemplo n.º 52
0
 public bool Store(AuthData data)
 {
     GD.Delete (m_realm, new string[2] {"UUID", "accountType"}, new object[2] { data.PrincipalID, data.AccountType });
     return GD.Insert (m_realm, new string[] { "UUID", "passwordHash", "passwordSalt",
         "accountType" }, new object[] { data.PrincipalID, 
             data.PasswordHash.MySqlEscape(), data.PasswordSalt.MySqlEscape(), data.AccountType.MySqlEscape() });
 }
Ejemplo n.º 53
0
        public static Task<Plan1PointsVM> GetRemainingPlan1PointsTask(AuthData a, DateTime date)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<Plan1PointsVM>();

            EventHandler<GetRemainingPlan1PointsCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetRemainingPlan1PointsCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetRemainingPlan1PointsCompleted += handler;
            client.GetRemainingPlan1PointsAsync(a, date);

            return tcs.Task;
        }
Ejemplo n.º 54
0
        public static Task<SummaryData> GetSummaryTask(AuthData authData, int p, DateTime date)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<SummaryData>();

            EventHandler<GetSummaryCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetSummaryCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetSummaryCompleted += handler;
            client.GetSummaryAsync(authData, p,date);

            return tcs.Task;
        }
Ejemplo n.º 55
0
        public static Task<ObservableCollection<TrainingExerciseVM>> GetExerciseHistoryTask(AuthData authData, TrainingExerciseVM trainingExerciseItem)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<ObservableCollection<TrainingExerciseVM>>();

            EventHandler<GetExerciseHistoryCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetExerciseHistoryCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetExerciseHistoryCompleted += handler;
            client.GetExerciseHistoryAsync(authData, trainingExerciseItem);

            return tcs.Task;
        }
Ejemplo n.º 56
0
        public virtual int SaveProviderInfo(string providerName, string customerTitle, AuthData authData, FolderType folderType)
        {
            var prName = (nSupportedCloudConfigurations) Enum.Parse(typeof (nSupportedCloudConfigurations), providerName, true);

            //for google docs
            authData = GetEncodedAccesToken(authData, providerName);

            if (!CheckProviderInfo(ToProviderInfo(0, providerName, customerTitle, authData, SecurityContext.CurrentAccount.ID.ToString(), folderType, TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))))
                throw new UnauthorizedAccessException("Can't authorize at " + providerName + " provider with given credentials");

            var queryInsert = new SqlInsert(TableTitle, true)
                .InColumnValue("id", 0)
                .InColumnValue("tenant_id", TenantID)
                .InColumnValue("provider", prName.ToString())
                .InColumnValue("customer_title", customerTitle)
                .InColumnValue("user_name", authData.Login)
                .InColumnValue("password", EncryptPassword(authData.Password))
                .InColumnValue("folder_type", (int) folderType)
                .InColumnValue("create_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
                .InColumnValue("user_id", SecurityContext.CurrentAccount.ID.ToString())
                .InColumnValue("token", authData.Token)
                .Identity(0, 0, true);

            return Int32.Parse(DbManager.ExecuteScalar<string>(queryInsert));
        }
Ejemplo n.º 57
0
        public static Task<ArrayOfString> GetClassesTask(AuthData authData)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<ArrayOfString>();

            EventHandler<GetClassesCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetClassesCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetClassesCompleted += handler;
            client.GetClassesAsync(authData);

            return tcs.Task;
        }
Ejemplo n.º 58
0
        public virtual int UpdateProviderInfo(int linkId, string customerTitle, AuthData authData, FolderType folderType)
        {
            var oldprovider = GetProviderInfoInernal(linkId);

            //for google docs
            authData = GetEncodedAccesToken(authData, oldprovider.ProviderName);

            if (!CheckProviderInfo(ToProviderInfo(0, oldprovider.ProviderName, customerTitle, authData, SecurityContext.CurrentAccount.ID.ToString(), folderType, TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))))
                throw new UnauthorizedAccessException("Can't authorize at " + oldprovider.ProviderName + " provider with given credentials");

            var queryUpdate = new SqlUpdate(TableTitle)
                .Set("customer_title", customerTitle)
                .Set("user_name", authData.Login)
                .Set("password", EncryptPassword(authData.Password))
                .Set("folder_type", (int) folderType)
                .Set("create_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
                .Set("user_id", SecurityContext.CurrentAccount.ID.ToString())
                .Set("token", authData.Token)
                .Where("id", linkId)
                .Where("tenant_id", TenantID);

            return DbManager.ExecuteNonQuery(queryUpdate) == 1 ? linkId : default(int);
        }
Ejemplo n.º 59
0
        public static Task<NutritionPlanVM> GetNewNutritionPlanTask(AuthData a, string plan, float cals, DateTime date)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<NutritionPlanVM>();

            EventHandler<GetNewNutritionPlanCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetNewNutritionPlanCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetNewNutritionPlanCompleted += handler;
            client.GetNewNutritionPlanAsync(a, plan,cals,date);

            return tcs.Task;
        }
Ejemplo n.º 60
0
        public static Task<UserVM> GetUserProfileTask(AuthData a)
        {
            var client = WebService.Instance.WS;
            var tcs = new TaskCompletionSource<UserVM>();

            EventHandler<GetUserProfileCompletedEventArgs> handler = null;
            handler = (sender, e) =>
            {
                client.GetUserProfileCompleted -= handler;

                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else
                {
                    tcs.SetResult(e.Result);
                }
            };

            client.GetUserProfileCompleted += handler;
            client.GetUserProfileAsync(a);

            return tcs.Task;
        }