示例#1
0
        public async Task <bool> BulkSaveFavorites(DtoAccount account)
        {
            SqliteDatabase sqlite          = new SqliteDatabase();
            var            sqlitefavorites = await sqlite.GetFavorites();

            string             apiUrl  = string.Format("https://{0}/api/favorite/{1}/bulk", databaseAPIIP, account.Id);
            Uri                uri     = new Uri(string.Format(apiUrl, string.Empty));
            HttpRequestMessage request = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = uri,
                Content    = new StringContent(JsonConvert.SerializeObject(sqlitefavorites), Encoding.UTF8, "application/json")
            };
            var response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                var success = JsonConvert.DeserializeObject <bool>(content);

                return(success);
            }
            return(false);
        }
 private void AppendAccountToFile(DtoAccount account)
 {
     using (var writer = new BinaryWriter(File.Open(_filePath, FileMode.Append), Encoding.UTF8))
     {
         WriteAccountToFile(writer, account);
     }
 }
示例#3
0
        public async Task <ActionResult <DtoAccount> > Get([FromBody] Account account)
        {
            if (account == null)
            {
                return(BadRequest());
            }
            var dtoAccount = new DtoAccount()
            {
                Id       = 0,
                Email    = account.Email,
                Username = account.Username,
                Password = account.Password
            };

            dtoAccount = await db.Login(dtoAccount);

            if (dtoAccount == null)
            {
                return(BadRequest());
            }
            dtoAccount.Token = Authenticate(dtoAccount.Id);


            return(Ok(dtoAccount));
        }
示例#4
0
 /// <summary>
 /// Maps <paramref cref="DtoAccount"/> to <paramref cref="BankAccount"/>.
 /// </summary>
 public static BankAccount ToBllAccount(this DtoAccount dalAccount) =>
 (BankAccount)Activator.CreateInstance(
     GetBllAccountType(dalAccount.AccountType),
     dalAccount.AccountNumber,
     dalAccount.OwnerFirstName,
     dalAccount.OwnerLastName,
     dalAccount.Balance,
     dalAccount.Bonus);
 private static void WriteAccountToFile(BinaryWriter writer, DtoAccount account)
 {
     writer.Write(account.AccountType);
     writer.Write(account.AccountNumber);
     writer.Write(account.OwnerFirstName);
     writer.Write(account.OwnerLastName);
     writer.Write(account.Balance);
     writer.Write(account.Bonus);
 }
 public static Account ToOrmAccount(this DtoAccount account, AccountOwner accountOwner) =>
 new Account
 {
     AccountType = new AccountType
     {
         Name = account.AccountType
     },
     Balance       = account.Balance,
     Bonus         = account.Bonus,
     AccountNumber = account.AccountNumber,
     AccountOwner  = accountOwner
 };
示例#7
0
        /// <summary>
        /// Maps <paramref cref="DtoAccount"/> to <paramref cref="BankAccount"/>.
        /// </summary>
        public static BankAccount ToBllAccount(this DtoAccount account, AccountOwner owner)
        {
            var type       = GetBllAccountType(account.AccountType);
            var bllAccount = (BankAccount)Activator.CreateInstance(
                type,
                CryptoService.RijndaelDecrypt(account.AccountNumber, owner.Email),
                owner,
                account.Balance,
                account.Bonus);

            bllAccount.AccountType = type.Name;
            return(bllAccount);
        }
示例#8
0
        /// <inheritdoc />
        public void AddAccount(DtoAccount account)
        {
            if (ReferenceEquals(account, null))
            {
                throw new ArgumentNullException(nameof(account));
            }

            if (_accounts.Any(dalAccount => dalAccount.AccountNumber == account.AccountNumber))
            {
                throw new RepositoryException("Account already exists in repository.");
            }

            _accounts.Add(account);
        }
示例#9
0
        /// <inheritdoc />
        public void RemoveAccount(DtoAccount account)
        {
            if (ReferenceEquals(account, null))
            {
                throw new ArgumentNullException(nameof(account));
            }

            if (!_accounts.Any(dalAccount => dalAccount.AccountNumber == account.AccountNumber))
            {
                throw new RepositoryException("Account can't be found in repository.");
            }

            _accounts.RemoveAll(dalAccount => dalAccount.AccountNumber == account.AccountNumber);
        }
示例#10
0
 public bool CanLogin(DtoAccount dtoAccount)
 {
     using (SqlConnection sqlConnection = data.GetConnect()) {
         sqlConnection.Open();
         string     sql        = @"SELECT COUNT(*) FROM ACCOUNT WHERE Username = @Username AND Password = @Password";
         SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
         sqlCommand.Parameters.Add("@Username", SqlDbType.NVarChar).Value = dtoAccount.Username;
         sqlCommand.Parameters.Add("@Password", SqlDbType.NVarChar).Value = dtoAccount.Password;
         using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader()) {
             if (sqlDataReader.Read())
             {
                 return(sqlDataReader.GetInt32(0) > 0);
             }
             return(false);
         }
     }
 }
示例#11
0
 public static Account ToOrmAccount(this DtoAccount account) =>
 new Account
 {
     AccountType = new AccountType
     {
         Name = account.AccountType
     },
     Balance       = account.Balance,
     Bonus         = account.Bonus,
     AccountNumber = account.AccountNumber,
     AccountOwner  = new AccountOwner
     {
         FirstName = account.OwnerFirstName,
         LastName  = account.OwnerLastName,
         Email     = account.OwnerEmail
     }
 };
示例#12
0
 public bool Update(DtoAccount dtoAccount)
 {
     using (SqlConnection sqlConnection = data.GetConnect()) {
         try {
             sqlConnection.Open();
             string     sql = @"UPDATE ACCOUNT SET Password = @Password WHERE UserName = @UserName";
             SqlCommand cmd = new SqlCommand(sql, sqlConnection);
             cmd.Parameters.Add("@UserName", SqlDbType.NChar).Value = dtoAccount.Username;
             cmd.Parameters.Add("@Password", SqlDbType.NChar).Value = dtoAccount.Password;
             cmd.ExecuteNonQuery();
         }
         catch {
             return(false);
         }
     }
     return(true);
 }
示例#13
0
 public bool Add(DtoAccount dtoAccount)
 {
     using (SqlConnection sqlConnection = data.GetConnect()) {
         try {
             sqlConnection.Open();
             string     sql = @"INSERT INTO ACCOUNT VALUES(@UserName, @Password)";
             SqlCommand cmd = new SqlCommand(sql, sqlConnection);
             cmd.Parameters.Add("@UserName", SqlDbType.NChar).Value = dtoAccount.Username;
             cmd.Parameters.Add("@Password", SqlDbType.NChar).Value = dtoAccount.Password;
             cmd.ExecuteNonQuery();
         }
         catch {
             return(false);
         }
     }
     return(true);
 }
        /// <inheritdoc />
        public void RemoveAccount(DtoAccount account)
        {
            if (account is null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            try
            {
                var removingAccount = GetAccountByNumber(account.AccountNumber);
                if (removingAccount is null)
                {
                    throw new RepositoryException("Removing account can't be found in repository.");
                }

                _context.Set <Account>().Remove(removingAccount);
            }
            catch (Exception ex)
            {
                throw new RepositoryException("Error in removing account.", ex);
            }
        }
示例#15
0
        public async Task <DtoAccount> Register(Account account)
        {
            string             apiUrl  = string.Format("https://{0}/api/account/register", databaseAPIIP);
            Uri                uri     = new Uri(string.Format(apiUrl, string.Empty));
            HttpRequestMessage request = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = uri,
                Content    = new StringContent(JsonConvert.SerializeObject(account), Encoding.UTF8, "application/json")
            };
            var response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                DtoAccount dtoAccount = JsonConvert.DeserializeObject <DtoAccount>(content);

                return(dtoAccount);
            }
            return(null);
        }
        /// <inheritdoc />
        public void UpdateAccount(DtoAccount account)
        {
            if (account is null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            try
            {
                var updatingAccount = GetAccountByNumber(account.AccountNumber);
                if (updatingAccount is null)
                {
                    throw new RepositoryException("Updating account does not exist.");
                }

                UpdateAccount(updatingAccount, account);
                _context.Entry(updatingAccount).State = EntityState.Modified;
            }
            catch (Exception ex)
            {
                throw new RepositoryException("Error in updating account.", ex);
            }
        }
        /// <inheritdoc />
        public void AddAccount(DtoAccount account)
        {
            if (account is null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            try
            {
                if (GetAccountByNumber(account.AccountNumber) != null)
                {
                    throw new RepositoryException("Account already exists in repository.");
                }

                var accountOwner = GetOwnerByEmail(account.AccountOwner.Email);
                var ormAccount   = account.ToOrmAccount(accountOwner);
                _context.Set <Account>().Add(ormAccount);
            }
            catch (Exception ex)
            {
                throw new RepositoryException("Error in adding new account.", ex);
            }
        }
示例#18
0
        public async Task <DtoAccount> Login(Account account)
        {
            account.Email = "";
            string             apiUrl   = string.Format("https://{0}/api/account/login", databaseAPIIP);
            Uri                uri      = new Uri(string.Format(apiUrl, string.Empty));
            var                jsonData = JsonConvert.SerializeObject(account);
            HttpRequestMessage request  = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = uri,
                Content    = new StringContent(jsonData, Encoding.UTF8, "application/json")
            };
            var response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                DtoAccount dtoAccount = JsonConvert.DeserializeObject <DtoAccount>(content);
                Application.Current.Properties["token"] = dtoAccount.Token;
                return(dtoAccount);
            }
            return(null);
        }
示例#19
0
 public bool CanLogin(DtoAccount dtoAccount)
 {
     return(dalAccount.CanLogin(dtoAccount));
 }
 private static void UpdateAccount(Account updatingAccount, DtoAccount account)
 {
     updatingAccount.Balance = account.Balance;
     updatingAccount.Bonus   = account.Bonus;
 }
示例#21
0
 // called from the loader
 public void InitNewAccout(DtoAccount dto)
 {
     dto.flags = DtoFlags.Init;
     ValidateNewAccount(dto);
     PostNewAccount(dto);
 }
示例#22
0
        // called from IO thread, respond as fast as possible
        public int ValidateNewAccount(DtoAccount dto)
        {
            // id
            if (!dto.flags.HasFlag(DtoFlags.Id))
            {
                return(400);
            }

            var id = dto.id;

            if (dto.id == 31631)
            {
            }

            // phone (if provided) contains area code
            if (dto.phone != null)
            {
                var openBrace  = dto.phone.IndexOf('(');
                var closeBrace = dto.phone.IndexOf(')');
                if (openBrace < 0 || closeBrace != openBrace + 4)
                {
                    return(400);
                }
            }

            // joined within range
            if (Utils.TimestampToDate(dto.joined) < MinJoined || Utils.TimestampToDate(dto.joined) > MaxJoined)
            {
                return(400);
            }

            // premium
            if (dto.premium.start > 0 && Utils.TimestampToDate(dto.premium.start) < MinPremium ||
                dto.premium.finish > 0 && Utils.TimestampToDate(dto.premium.finish) < MinPremium)
            {
                return(400);
            }

            // check email syntaxis
            if (dto.email.IsEmpty || dto.email.Length > 100)
            {
                return(400);
            }

            // validate email syntax and create the email buffer
            if (!bufferFromEmail(dto.email, out var intEmail))
            {
                return(400);
            }

            // the rest requires locking
            bool lockTaken = false;

            try
            {
                updateLock.Enter(ref lockTaken);

                // is there an account with such id already?
                if (All[id])
                {
                    return(400); // account already exists
                }
                if (!Emails.Add(intEmail))
                {
                    return(400); // must be unique
                }
                // check if liked accounts all exist
                if (dto.flags != DtoFlags.Init && dto.likes != null)
                {
                    if (!verifyLikes(dto.likes))
                    {
                        return(400);
                    }
                }

                // store the email and include into the domain list
                var acct = Accounts[id];
                acct.Email = intEmail;
                Domains[acct.GetDomainIdx()].Include(id);

                // all is good! mark as existing
                All.Set(id, true);
                Accounts[id] = acct;
            }
            finally
            {
                if (lockTaken)
                {
                    updateLock.Exit();
                }
            }

            return(201);
        }
示例#23
0
 public bool Add(DtoAccount dtoAccount)
 {
     return(dalAccount.Add(dtoAccount));
 }
示例#24
0
        public async Task <DtoAccount> Register(Account account)
        {
            DtoAccount dtoAccount = new DtoAccount()
            {
                Id       = 0,
                Email    = account.Email,
                Username = account.Username,
                Password = account.Password
            };

            //Check if the Username exist in the database #Yes go on #No return and send back false boolean
            using (MySqlConnection conn = new MySqlConnection(constring))
            {
                try
                {
                    conn.Open();
                    string query = "select COUNT(*) as accounts from Account where username = @username";

                    using (MySqlCommand cmd = new MySqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@username", account.Username);
                        MySqlDataReader reader = await cmd.ExecuteReaderAsync();

                        if (reader.HasRows)
                        {
                            await reader.ReadAsync();

                            if (reader.GetInt16(0) != 0)
                            {
                                reader.Close();
                                await conn.CloseAsync();

                                return(null);
                            }
                        }
                        else
                        {
                            reader.Close();
                            await conn.CloseAsync();

                            return(null);
                        }

                        reader.Close();
                    }
                    query = "INSERT INTO Radio.Account (email,username,password,enabled) VALUES (@email,@username,@password,@enabled)";
                    //Create User

                    account.Password = Hash.CreateHash(account.Password);
                    using (MySqlCommand cmd = new MySqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@email", account.Email);
                        cmd.Parameters.AddWithValue("@username", account.Username);
                        cmd.Parameters.AddWithValue("@password", account.Password);
                        cmd.Parameters.AddWithValue("@enabled", 1);


                        cmd.ExecuteNonQuery();
                        dtoAccount.Id = (int)cmd.LastInsertedId;
                    }


                    await conn.CloseAsync();

                    return(dtoAccount);
                }
                catch (Exception)
                {
                    await conn.CloseAsync();

                    return(null);
                }
            }
        }
示例#25
0
        public async Task <DtoAccount> Login(DtoAccount account)
        {
            using (MySqlConnection conn = new MySqlConnection(constring))
            {
                try
                {
                    conn.Open();
                }
                catch (Exception)
                {
                    throw;
                }
                int    id             = 0;
                string hashedPassword = "";
                int    attempt        = 0;
                int    enabled        = 0;
                string query          = "select password,id,attempt,enabled from Account where username = @username";
                using (var cmd = new MySqlCommand(query, conn))
                {
                    cmd.Parameters.AddWithValue("@username", account.Username);
                    MySqlDataReader reader = await cmd.ExecuteReaderAsync();

                    if (reader.HasRows)
                    {
                        while (await reader.ReadAsync())
                        {
                            hashedPassword = reader.GetString(0);
                            id             = reader.GetInt32(1);
                            attempt        = reader.GetInt32(2);
                            enabled        = reader.GetInt16(3);
                        }
                    }
                    reader.Close();
                }


                try
                {
                    //Check if user attempted to login more than 3 times
                    if (attempt < 3 && enabled == 1)
                    {
                        if (Hash.VerifyHash(account.Password, hashedPassword))
                        {
                            //Logged in
                            //reset attempt to zero
                            string query1 = "Update Radio.Account SET attempt = @attempt WHERE username = @username and id = @id";
                            using (MySqlCommand cmd1 = new MySqlCommand(query1, conn))
                            {
                                cmd1.Parameters.AddWithValue("@username", account.Username);
                                cmd1.Parameters.AddWithValue("@attempt", 0);
                                cmd1.Parameters.AddWithValue("@id", id);
                                await cmd1.ExecuteNonQueryAsync();
                            }
                            account.Id = id;
                            await conn.CloseAsync();
                        }
                        else
                        {
                            //failed login attempt + 1
                            string query1 = "Update Radio.Account SET attempt = @attempt WHERE username = @username and id = @id";
                            using (MySqlCommand cmd1 = new MySqlCommand(query1, conn))
                            {
                                cmd1.Parameters.AddWithValue("@username", account.Username);
                                cmd1.Parameters.AddWithValue("@attempt", attempt + 1);
                                cmd1.Parameters.AddWithValue("@id", id);
                                await cmd1.ExecuteNonQueryAsync();
                            }
                            return(null);
                        }
                    }
                    else
                    {
                        //Attempted more than 3 times Freeze account
                        query = "Update Radio.Account SET enabled = @enabled WHERE username = @username and id = @id";
                        using (MySqlCommand cmd1 = new MySqlCommand(query, conn))
                        {
                            cmd1.Parameters.AddWithValue("@username", account.Username);
                            cmd1.Parameters.AddWithValue("@enabled", 0);
                            cmd1.Parameters.AddWithValue("@id", id);
                            await cmd1.ExecuteNonQueryAsync();
                        }
                        return(null);
                    }



                    await conn.CloseAsync();

                    return(account);
                }
                catch (Exception e)
                {
                    string d = e.Message;
                    await conn.CloseAsync();

                    return(null);
                }
            }
        }
示例#26
0
 public bool Update(DtoAccount dtoAccount)
 {
     return(dalAccount.Update(dtoAccount));
 }
示例#27
0
        // this call is serialized
        public void PostNewAccount(DtoAccount dto)
        {
            var id   = dto.id;
            var acct = Accounts[id];

            // sex
            if (dto.sex)
            {
                acct.Flags |= Account.Male;
            }

            // status
            if (dto.status == DtoAccount.STATUS_FREE)
            {
                acct.Flags |= Account.Free;
            }
            else
            if (dto.status == DtoAccount.STATUS_TAKEN)
            {
                acct.Flags |= Account.Taken;
            }
            else
            {
                acct.Flags |= (byte)(Account.Free | Account.Taken);
            }

            // birth date and year
            acct.Birth    = dto.birth;
            acct.BirthIdx = (byte)BirthYears.GetOrCreateRangeThenInclude(
                Utils.TimestampToDate(acct.Birth).Year, id).Index;

            // joined
            acct.JoinedIdx = (byte)JoinYears.GetOrCreateRangeThenInclude(
                Utils.TimestampToDate(dto.joined).Year, id).Index;

            // premium
            acct.PStart  = dto.premium.start;
            acct.PFinish = dto.premium.finish;
            bool premiumNow = acct.PStart <= Now && acct.PFinish >= Now;

            if (premiumNow)
            {
                acct.Flags |= Account.Premium;
            }

            // fname
            acct.FNameIdx = dto.fnameIdx;
            if (acct.FNameIdx > 0)
            {
                Fnames[acct.FNameIdx].Include(id);
            }

            // sname
            acct.SNameIdx = dto.snameIdx;
            if (acct.SNameIdx > 0)
            {
                var entry = Snames[dto.snameIdx];
                entry.Include(id);
                Snames2.GetOrCreateRangeThenInclude(entry.AName[0] + (entry.AName[1] << 8), id);
                Snames2.GetOrCreateRangeThenInclude(entry.AName[0] + (entry.AName[1] << 8) + (entry.AName[2] << 16) + (entry.AName[3] << 24), id);
            }

            // phone
            if (!dto.phone.IsEmpty)
            {
                acct.Phone = dto.phone.Buffer;
                // add to area code index
                var areaCodeStr = areaCodeFromPhone(dto.phone);
                if (!areaCodeStr.IsEmpty)
                {
                    AreaCodes.GetOrCreateRangeThenInclude(areaCodeStr, id);
                }
            }

            // country
            acct.CountryIdx = dto.countryIdx;
            if (acct.CountryIdx > 0)
            {
                Countries[acct.CountryIdx].Include(id);
            }

            // city
            acct.CityIdx = dto.cityIdx;
            if (acct.CityIdx > 0)
            {
                Cities[acct.CityIdx].Include(id);
            }

            // interests
            acct.InterestMask = dto.interests;
            for (int i = 1; i < BitMap96.MAX_BITS; i++)
            {
                if (acct.InterestMask.IsSet(i))
                {
                    Interests[i].Include(id);
                }
            }

            // likes
            if (dto.likes != null)
            {
                addLikes(id, ref acct, dto.likes);
            }

            // update the group hypercube
            updateGroups(ref acct, true);

            // store it
            Accounts[id] = acct;
        }