private UserAccountToken BuildToken(UserAccountData userData, IList <string> roles, string UserId)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, userData.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            foreach (var rol in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, rol));
            }

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expiration = DateTime.UtcNow.AddMinutes(60);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            var newtoken = new UserAccountToken()
            {
                Token          = new JwtSecurityTokenHandler().WriteToken(token),
                ExpirationDate = expiration,
                Id             = UserId
            };

            return(newtoken);
        }
        public bool Delete(string field, string val)
        {
            // Only delete by PrincipalID
            if (field.Equals("PrincipalID"))
            {
                UUID uuid = UUID.Zero;
                if (UUID.TryParse(val, out uuid) && m_DataByUUID.ContainsKey(uuid))
                {
                    UserAccountData account = m_DataByUUID[uuid];
                    m_DataByUUID.Remove(uuid);
                    if (m_DataByName.ContainsKey(account.FirstName + " " + account.LastName))
                    {
                        m_DataByName.Remove(account.FirstName + " " + account.LastName);
                    }
                    if (account.Data.ContainsKey("Email") && account.Data["Email"] != string.Empty && m_DataByEmail.ContainsKey(account.Data["Email"]))
                    {
                        m_DataByEmail.Remove(account.Data["Email"]);
                    }

                    return(true);
                }
            }

            return(false);
        }
        public bool StoreUserAccount(UserAccount data)
        {
//            m_log.DebugFormat(
//                "[USER ACCOUNT SERVICE]: Storing user account for {0} {1} {2}, scope {3}",
//                data.FirstName, data.LastName, data.PrincipalID, data.ScopeID);

            UserAccountData d = new UserAccountData();

            d.FirstName         = data.FirstName;
            d.LastName          = data.LastName;
            d.PrincipalID       = data.PrincipalID;
            d.ScopeID           = data.ScopeID;
            d.Data              = new Dictionary <string, string>();
            d.Data["Email"]     = data.Email;
            d.Data["Created"]   = data.Created.ToString();
            d.Data["UserLevel"] = data.UserLevel.ToString();
            d.Data["UserFlags"] = data.UserFlags.ToString();
            if (data.UserTitle != null)
            {
                d.Data["UserTitle"] = data.UserTitle.ToString();
            }

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

            foreach (KeyValuePair <string, object> kvp in data.ServiceURLs)
            {
                string key = System.Web.HttpUtility.UrlEncode(kvp.Key);
                string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
                parts.Add(key + "=" + val);
            }

            d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray());

            return(m_Database.Store(d));
        }
        public async Task <ActionResult <UserAccountToken> > CreateUser([FromBody] UserAccountData userData)
        {
            var user = new ApplicationUser {
                UserName = userData.Email, Email = userData.Email
            };

            var result = await _userManager.CreateAsync(user, userData.Password);

            if (result.Succeeded)

            {
                //Role assing
                var usuario = await _userManager.FindByIdAsync(user.Id);

                await _userManager.AddClaimAsync(usuario, new Claim(ClaimTypes.Role, "storeowner"));

                await _userManager.AddToRoleAsync(usuario, "storeowner");

                var token      = BuildToken(userData, new List <string>(), user.Id);
                var emailtoken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var confirmationLink = Url.Action(nameof(ConfirmEmail), "UserAccount", new { emailtoken, email = user.Email }, Request.Scheme);
                var message          = new EmailMessage(new string[] { user.Email }, "Confirmation email link", confirmationLink, "Confirm");

                _emailSender.SendEmail(message);
                return(Ok("Email was sent!"));
            }
            else
            {
                return(BadRequest(result.Errors));
            }
        }
        /// <summary>
        /// Tries to implement the Get [] semantics, but it cuts corners like crazy.
        /// Specifically, it relies on the knowledge that the only Gets used are
        /// keyed on PrincipalID, Email, and FirstName+LastName.
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public UserAccountData[] Get(string[] fields, string[] values)
        {
//            if (m_log.IsDebugEnabled)
//            {
//                m_log.DebugFormat(
//                    "[NULL USER ACCOUNT DATA]: Called Get with fields [{0}], values [{1}]",
//                    string.Join(", ", fields), string.Join(", ", values));
//            }

            UserAccountData[] userAccounts = new UserAccountData[0];

            List <string> fieldsLst = new List <string>(fields);

            if (fieldsLst.Contains("PrincipalID"))
            {
                int  i  = fieldsLst.IndexOf("PrincipalID");
                UUID id = UUID.Zero;
                if (UUID.TryParse(values[i], out id))
                {
                    if (m_DataByUUID.ContainsKey(id))
                    {
                        userAccounts = new UserAccountData[] { m_DataByUUID[id] }
                    }
                }
                ;
            }
            else if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName"))
            {
                int findex = fieldsLst.IndexOf("FirstName");
                int lindex = fieldsLst.IndexOf("LastName");
                if (m_DataByName.ContainsKey(values[findex] + " " + values[lindex]))
                {
                    userAccounts = new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] };
                }
            }
            else if (fieldsLst.Contains("Email"))
            {
                int i = fieldsLst.IndexOf("Email");
                if (m_DataByEmail.ContainsKey(values[i]))
                {
                    userAccounts = new UserAccountData[] { m_DataByEmail[values[i]] }
                }
                ;
            }

//            if (m_log.IsDebugEnabled)
//            {
//                StringBuilder sb = new StringBuilder();
//                foreach (UserAccountData uad in userAccounts)
//                    sb.AppendFormat("({0} {1} {2}) ", uad.FirstName, uad.LastName, uad.PrincipalID);
//
//                m_log.DebugFormat(
//                    "[NULL USER ACCOUNT DATA]: Returning {0} user accounts out of {1}: [{2}]", userAccounts.Length, m_DataByName.Count, sb);
//            }

            return(userAccounts);
        }
Exemple #6
0
        protected UserAccount ToUserAccount(UserAccountData d)
        {
            UserAccount account = new UserAccount(d.Data.ToDictionary(p => p.Key, p => (object)p.Value));

            account.PrincipalID = d.PrincipalID;
            account.ScopeID     = d.ScopeID;
            account.FirstName   = d.FirstName;
            account.LastName    = d.LastName;
            return(account);
        }
        public UserAccountData[] GetUsers(UUID scopeID, string query)
        {
//            m_log.DebugFormat(
//                "[NULL USER ACCOUNT DATA]: Called GetUsers with scope [{0}], query [{1}]", scopeID, query);

            string[] words = query.Split(new char[] { ' ' });

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length < 3)
                {
                    if (i != words.Length - 1)
                    {
                        Array.Copy(words, i + 1, words, i, words.Length - i - 1);
                    }
                    Array.Resize(ref words, words.Length - 1);
                }
            }

            if (words.Length == 0)
            {
                return(new UserAccountData[0]);
            }

            if (words.Length > 2)
            {
                return(new UserAccountData[0]);
            }

            List <string> lst = new List <string>(m_DataByName.Keys);

            if (words.Length == 1)
            {
                lst = lst.FindAll(delegate(string s) { return(s.StartsWith(words[0])); });
            }
            else
            {
                lst = lst.FindAll(delegate(string s) { return(s.Contains(words[0]) || s.Contains(words[1])); });
            }

            if (lst == null || (lst != null && lst.Count == 0))
            {
                return(new UserAccountData[0]);
            }

            UserAccountData[] result = new UserAccountData[lst.Count];
            int n = 0;

            foreach (string key in lst)
            {
                result[n++] = m_DataByName[key];
            }

            return(result);
        }
        private static void ValidatePermission(UserAccountData userToUpdate, LoggedUserModel requestedUser, string newRole)
        {
            if (requestedUser.Id != userToUpdate.Id && requestedUser.Role != UserRolesHelper.Root)
            {
                throw new ValidationException("Only user itself or user with role `root` can edit information of other user");
            }

            if (requestedUser.Id == userToUpdate.Id && requestedUser.Role != UserRolesHelper.Root && userToUpdate.Role != newRole)
            {
                throw new ValidationException("You don't have permission to change your own role");
            }
        }
 public static UserAccount ToModel(this UserAccountData node)
 {
     return(new UserAccount()
     {
         Id = node.Id,
         UserId = node.UserId,
         Balance = encrypt.Encrypto(node.Balance),
         BalanceTypeId = node.BalanceTypeId,
         AddTime = node.AddTime,
         Enable = node.Enable,
     });
 }
        public UserAccountData Get(UUID principalID, UUID scopeID)
        {
            UserAccountData ret = new UserAccountData();
            ret.Data = new Dictionary<string, object>();

            string command = "select * from `"+m_Realm+"` where UUID = ?principalID";
            if (scopeID != UUID.Zero)
                command += " and ScopeID = ?scopeID";

            using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
            {
                dbcon.Open();
                MySqlCommand cmd = new MySqlCommand(command, dbcon);

                cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
                cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());

                IDataReader result = cmd.ExecuteReader();

                if (result.Read())
                {
                    ret.PrincipalID = principalID;
                    UUID scope;
                    UUID.TryParse(result["ScopeID"].ToString(), out scope);
                    ret.ScopeID = scope;

                    if (m_ColumnNames == null)
                    {
                        m_ColumnNames = new List<string>();

                        DataTable schemaTable = result.GetSchemaTable();
                        foreach (DataRow row in schemaTable.Rows)
                            m_ColumnNames.Add(row["ColumnName"].ToString());
                    }

                    foreach (string s in m_ColumnNames)
                    {
                        if (s == "UUID")
                            continue;
                        if (s == "ScopeID")
                            continue;

                        ret.Data[s] = result[s].ToString();
                    }

                    return ret;
                }
                else
                {
                    return null;
                }
            }
        }
        public SignInError AttemptSignIn(SignInCredentials login)
        {
            // TODO: talk to server

            // for now we'll just build data and assume all is dandy
            _userAccountData = new UserAccountData
            {
                Username = login.Username,
                Password = login.Password
            };

            return(SignInError.None);
        }
        public UserAccountData Get(UUID principalID, UUID scopeID)
        {
            UserAccountData ret = new UserAccountData();
            ret.Data = new Dictionary<string, object>();

            string sql = string.Format("select * from '{0}' where UUID = @principalID", m_Realm);
            if (scopeID != UUID.Zero)
                sql += " and ScopeID = @scopeID";

            using (SqlConnection conn = new SqlConnection(m_ConnectionString))
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {

                cmd.Parameters.AddWithValue("@principalID", principalID);
                cmd.Parameters.AddWithValue("@scopeID", scopeID);
                conn.Open();
                using (SqlDataReader result = cmd.ExecuteReader())
                {
                    if (result.Read())
                    {
                        ret.PrincipalID = principalID;
                        UUID scope;
                        UUID.TryParse(result["ScopeID"].ToString(), out scope);
                        ret.ScopeID = scope;

                        if (m_ColumnNames == null)
                        {
                            m_ColumnNames = new List<string>();

                            DataTable schemaTable = result.GetSchemaTable();
                            foreach (DataRow row in schemaTable.Rows)
                                m_ColumnNames.Add(row["ColumnName"].ToString());
                        }

                        foreach (string s in m_ColumnNames)
                        {
                            if (s == "UUID")
                                continue;
                            if (s == "ScopeID")
                                continue;

                            ret.Data[s] = result[s].ToString();
                        }
                        return ret;
                    }
                }
            }
            return null;
        }
        public async Task <UserAccountData[]> getAllAccounts(string email_Address)
        {
            //connect to the database
            bool connection_result = connectToFirebase();

            //create the array which will be returned to the user as the output of this operation
            UserAccountData[] dBAccountData = null;
            try
            {
                //connection is succesfull
                if (connection_result)
                {
                    //Query for all the account
                    Query allAccounts = db.Collection("UserAccounts").Document(email_Address).Collection("MyAccounts");

                    //get the sanpshots for the collections
                    QuerySnapshot allAccountsSnapshots = await allAccounts.GetSnapshotAsync();

                    //to variable represensts the number of accounts
                    int number_of_accounts = allAccountsSnapshots.Count;
                    //create the array for the account data
                    dBAccountData = new UserAccountData[number_of_accounts];

                    //incremeant varibale
                    int i = 0;
                    foreach (DocumentSnapshot snap in allAccountsSnapshots.Documents)
                    {
                        DBAccountData tempData = snap.ConvertTo <DBAccountData>();
                        dBAccountData[i]           = new UserAccountData();
                        dBAccountData[i].userEmail = email_Address;
                        dBAccountData[i].Name      = tempData.accountName;
                        dBAccountData[i].UserName  = tempData.accountUserName;
                        dBAccountData[i].Password  = tempData.accountPassword;
                        dBAccountData[i].Password  = tempData.accountPassword;
                        i++;
                    }
                }
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Error while getting the data from the database";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }

            return(dBAccountData);
        }
        /// <summary>
        /// Tries to implement the Get [] semantics, but it cuts corners like crazy.
        /// Specifically, it relies on the knowledge that the only Gets used are
        /// keyed on PrincipalID, Email, and FirstName+LastName.
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public UserAccountData[] Get(string[] fields, string[] values)
        {
//            if (m_log.IsDebugEnabled)
//            {
//                m_log.DebugFormat(
//                    "[NULL USER ACCOUNT DATA]: Called Get with fields [{0}], values [{1}]", 
//                    string.Join(", ", fields), string.Join(", ", values));
//            }
            
            UserAccountData[] userAccounts = new UserAccountData[0];
            
            List<string> fieldsLst = new List<string>(fields);
            if (fieldsLst.Contains("PrincipalID"))
            {
                int i = fieldsLst.IndexOf("PrincipalID");
                UUID id = UUID.Zero;
                if (UUID.TryParse(values[i], out id))
                    if (m_DataByUUID.ContainsKey(id))
                        userAccounts = new UserAccountData[] { m_DataByUUID[id] };
            }            
            else if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName"))
            {
                int findex = fieldsLst.IndexOf("FirstName");
                int lindex = fieldsLst.IndexOf("LastName");
                if (m_DataByName.ContainsKey(values[findex] + " " + values[lindex]))
                {                                       
                    userAccounts = new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] };
                }
            }            
            else if (fieldsLst.Contains("Email"))
            {
                int i = fieldsLst.IndexOf("Email");
                if (m_DataByEmail.ContainsKey(values[i]))
                    userAccounts = new UserAccountData[] { m_DataByEmail[values[i]] };
            }
            
//            if (m_log.IsDebugEnabled)
//            {
//                StringBuilder sb = new StringBuilder();
//                foreach (UserAccountData uad in userAccounts)
//                    sb.AppendFormat("({0} {1} {2}) ", uad.FirstName, uad.LastName, uad.PrincipalID);
//                    
//                m_log.DebugFormat(
//                    "[NULL USER ACCOUNT DATA]: Returning {0} user accounts out of {1}: [{2}]", userAccounts.Length, m_DataByName.Count, sb);
//            }
            
            return userAccounts;
        }
        public bool Store(UserAccountData data)
        {
            if (data == null)
            {
                return(false);
            }

            m_DataByUUID[data.PrincipalID] = data;
            m_DataByName[data.FirstName + " " + data.LastName] = data;
            if (data.Data.ContainsKey("Email") && data.Data["Email"] != null && data.Data["Email"] != string.Empty)
            {
                m_DataByEmail[data.Data["Email"]] = data;
            }

            return(true);
        }
        public async Task <Guid> Handle(RegisterNewUserAccountCommand command, CancellationToken cancellationToken = default(CancellationToken))
        {
            await ValidateForUniqueness(command);

            var sponsorId = await GetSponsorId(command);

            var hashSalt = PasswordEncryptionUtilities.GenerateSaltedHash(command.Password);

            var userAccountData = new UserAccountData
                                  (
                id: Guid.NewGuid(),
                email: command.Email,
                login: command.Login,
                firstName: command.FirstName,
                lastName: command.LastName,
                street: command.Street,
                city: command.City,
                zipCode: command.ZipCode,
                country: command.Country,
                btcWalletAddress: command.BtcWalletAddress,
                role: UserRolesHelper.User
                                  );

            userAccountData.SetPassword(hashSalt.Salt, hashSalt.Hash);

            await _context.Set <UserAccountData>().AddAsync(userAccountData);

            await _context.SaveChangesAsync();

            // TODO: Event that user was created: eventhandler should create new multiaccount for him
            var userMultiAccount = new UserMultiAccount
                                   (
                id: Guid.NewGuid(),
                userAccountDataId: userAccountData.Id,
                sponsorId: sponsorId,
                multiAccountName: userAccountData.Login
                                   );

            userMultiAccount.SetAsMainAccount();

            await _userMultiAccountRepository.CreateAsync(userMultiAccount);

            return(userAccountData.Id);
        }
        public bool Store(UserAccountData data)
        {
            if (data == null)
            {
                return(false);
            }

            m_log.DebugFormat(
                "[NULL USER ACCOUNT DATA]: Storing user account {0} {1} {2} {3}",
                data.FirstName, data.LastName, data.PrincipalID, this.GetHashCode());

            m_DataByUUID[data.PrincipalID] = data;
            m_DataByName[data.FirstName + " " + data.LastName] = data;
            if (data.Data.ContainsKey("Email") && data.Data["Email"] != null && data.Data["Email"] != string.Empty)
            {
                m_DataByEmail[data.Data["Email"]] = data;
            }

//            m_log.DebugFormat("m_DataByUUID count is {0}, m_DataByName count is {1}", m_DataByUUID.Count, m_DataByName.Count);

            return(true);
        }
        public UserAccountInfo(UserAccountData data)
        {
            AccountHolderId = data.AccountHolderId;
            Accounts        = new Dictionary <AccountType, List <AccountInfo> >
            {
                { AccountType.Debit, new List <AccountInfo>() },
                { AccountType.Loan, new List <AccountInfo>() }
            };

            foreach (var account in data.Accounts)
            {
                if (account.GetType() == typeof(CreditAccountData))
                {
                    Accounts[AccountType.Loan].Add(new CreditAccountInfo(account as CreditAccountData));
                }

                else if (account.GetType() == typeof(DebitAccountData))
                {
                    Accounts[AccountType.Debit].Add(new DebitAccountInfo(account as DebitAccountData));
                }
            }
        }
        public async Task <ActionResult <UserAccountToken> > Login([FromBody] UserAccountData userData)
        {
            var result = await _signInManager.PasswordSignInAsync(userData.Email, userData.Password, isPersistent : false, lockoutOnFailure : false);

            var usuario = await _userManager.FindByEmailAsync(userData.Email);

            if (result.Succeeded)
            {
                if (usuario.EmailConfirmed == true)
                {
                    var roles = await _userManager.GetRolesAsync(usuario);

                    //logmanager.CreateLog("Informacion",$" User : {userData.Email} log in successfully!");
                    return(BuildToken(userData, roles, usuario.Id));
                }
                return(BadRequest("Email no confirmed"));
            }
            else
            {
                //await _userManager.IsEmailConfirmedAsync(ApplicationUser usuario.Id);
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(BadRequest(ModelState));
            }
        }
        public bool Store(UserAccountData data)
        {
            if (data.Data.ContainsKey("UUID"))
                data.Data.Remove("UUID");
            if (data.Data.ContainsKey("ScopeID"))
                data.Data.Remove("ScopeID");

            string[] fields = new List<string>(data.Data.Keys).ToArray();

            using (MySqlCommand cmd = new MySqlCommand())
            {
                string update = "update `" + m_Realm + "` set ";
                bool first = true;
                foreach (string field in fields)
                {
                    if (!first)
                        update += ", ";
                    update += "`" + field + "` = ?" + field;

                    first = false;

                    cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
                }

                update += " where UUID = ?principalID";

                if (data.ScopeID != UUID.Zero)
                    update += " and ScopeID = ?scopeID";

                cmd.CommandText = update;
                cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
                cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());

                if (ExecuteNonQuery(cmd) < 1)
                {
                    string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
                            String.Join("`, `", fields) +
                            "`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";

                    cmd.CommandText = insert;

                    if (ExecuteNonQuery(cmd) < 1)
                    {
                        cmd.Dispose();
                        return false;
                    }
                }
            }

            return true;
        }
        private UserAccount MakeUserAccount(UserAccountData d)
        {
            UserAccount u = new UserAccount();

            u.FirstName   = d.FirstName;
            u.LastName    = d.LastName;
            u.PrincipalID = d.PrincipalID;
            u.ScopeID     = d.ScopeID;
            if (d.Data.ContainsKey("Email") && d.Data["Email"] != null)
            {
                u.Email = d.Data["Email"].ToString();
            }
            else
            {
                u.Email = string.Empty;
            }
            u.Created = Convert.ToInt32(d.Data["Created"].ToString());
            if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null)
            {
                u.UserTitle = d.Data["UserTitle"].ToString();
            }
            else
            {
                u.UserTitle = string.Empty;
            }
            if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null)
            {
                Int32.TryParse(d.Data["UserLevel"], out u.UserLevel);
            }
            if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null)
            {
                Int32.TryParse(d.Data["UserFlags"], out u.UserFlags);
            }

            if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null)
            {
                string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' });
                u.ServiceURLs = new Dictionary <string, object>();

                foreach (string url in URLs)
                {
                    string[] parts = url.Split(new char[] { '=' });

                    if (parts.Length != 2)
                    {
                        continue;
                    }

                    string name = System.Web.HttpUtility.UrlDecode(parts[0]);
                    string val  = System.Web.HttpUtility.UrlDecode(parts[1]);

                    u.ServiceURLs[name] = val;
                }
            }
            else
            {
                u.ServiceURLs = new Dictionary <string, object>();
            }

            return(u);
        }
Exemple #22
0
 public void Login(UserAccountData userData)
 {
     SignInModule.WaitForLoginModuleEnabled();
     SignInModule.EnterEmailAndPasswordValue(userData);
     SignInModule.ClickLoginCTA();
 }
        private UserAccount MakeUserAccount(UserAccountData d)
        {
            UserAccount u = new UserAccount();
            u.FirstName = d.FirstName;
            u.LastName = d.LastName;
            u.PrincipalID = d.PrincipalID;
            u.ScopeID = d.ScopeID;
            if (d.Data.ContainsKey("Email") && d.Data["Email"] != null)
                u.Email = d.Data["Email"].ToString();
            else
                u.Email = string.Empty;
            u.Created = Convert.ToInt32(d.Data["Created"].ToString());
            if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null)
                u.UserTitle = d.Data["UserTitle"].ToString();
            else
                u.UserTitle = string.Empty;
            if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null)
                Int32.TryParse(d.Data["UserLevel"], out u.UserLevel);
            if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null)
                Int32.TryParse(d.Data["UserFlags"], out u.UserFlags);

            if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null)
            {
                string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' });
                u.ServiceURLs = new Dictionary<string, object>();

                foreach (string url in URLs)
                {
                    string[] parts = url.Split(new char[] { '=' });

                    if (parts.Length != 2)
                        continue;

                    string name = System.Web.HttpUtility.UrlDecode(parts[0]);
                    string val = System.Web.HttpUtility.UrlDecode(parts[1]);

                    u.ServiceURLs[name] = val;
                }
            }
            else
                u.ServiceURLs = new Dictionary<string, object>();

            return u;
        }
        public bool StoreUserAccount(UserAccount data)
        {
//            m_log.DebugFormat(
//                "[USER ACCOUNT SERVICE]: Storing user account for {0} {1} {2}, scope {3}",
//                data.FirstName, data.LastName, data.PrincipalID, data.ScopeID);

            UserAccountData d = new UserAccountData();

            d.FirstName = data.FirstName;
            d.LastName = data.LastName;
            d.PrincipalID = data.PrincipalID;
            d.ScopeID = data.ScopeID;
            d.Data = new Dictionary<string, string>();
            d.Data["Email"] = data.Email;
            d.Data["Created"] = data.Created.ToString();
            d.Data["UserLevel"] = data.UserLevel.ToString();
            d.Data["UserFlags"] = data.UserFlags.ToString();
            if (data.UserTitle != null)
                d.Data["UserTitle"] = data.UserTitle.ToString();

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

            foreach (KeyValuePair<string, object> kvp in data.ServiceURLs)
            {
                string key = System.Web.HttpUtility.UrlEncode(kvp.Key);
                string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
                parts.Add(key + "=" + val);
            }

            d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray());

            return m_Database.Store(d);
        }
        public bool StoreUserAccount(UserAccount data)
        {
            UserAccountData d = new UserAccountData();

            d.FirstName = data.FirstName;
            d.LastName = data.LastName;
            d.PrincipalID = data.PrincipalID;
            d.ScopeID = data.ScopeID;
            d.Data = new Dictionary<string, string>();
            d.Data["Email"] = data.Email;
            d.Data["Created"] = data.Created.ToString();

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

            foreach (KeyValuePair<string, object> kvp in data.ServiceURLs)
            {
                string key = System.Web.HttpUtility.UrlEncode(kvp.Key);
                string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
                parts.Add(key + "=" + val);
            }

            d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray());

            return m_Database.Store(d);
        }
 public void EnterEmailAndPasswordValue(UserAccountData user)
 {
     Driver.FindElement(BY_EMAIL_FIELD).SendKeys(user.UserName);
     Driver.FindElement(BY_PASSWORD_FIELD).SendKeys(user.Password);
 }
        public async Task <UserAccountData> requestDecryption(string email_Address, string accountName)
        {
            DBAccountData   dBAccountData = null;
            UserAccountData data          = null;
            //connect to the firestoredatabase
            bool connection_Result = connectToFirebase();

            try
            {
                if (connection_Result)
                {
                    DocumentReference documentReference = db.Collection("UserAccounts").Document(email_Address).Collection("MyAccounts").Document(accountName);
                    DocumentSnapshot  documentSnapshot  = await documentReference.GetSnapshotAsync();

                    if (documentSnapshot.Exists)
                    {
                        //first of all encrypt the user Data
                        //Get the User Encryption Key from the firestore database
                        DocumentReference getUserKey = db.Collection("UserEncryptionKeys").Document(email_Address);

                        //get the snapshot for the same
                        DocumentSnapshot snapshot = await getUserKey.GetSnapshotAsync();

                        if (snapshot.Exists)
                        {
                            string keyName = "";
                            Dictionary <string, object> userKeyDict = snapshot.ToDictionary();
                            foreach (KeyValuePair <string, object> pair in userKeyDict)
                            {
                                if (pair.Key == "userKeyName")
                                {
                                    keyName = pair.Value.ToString();
                                    break;
                                }
                            }

                            //Convert to the DBUserEncryption
                            //DBUserEncryptionKeys dBUserEncryptionKeys = snapshot.ConvertTo<DBUserEncryptionKeys>();
                            //string key_Name_For_Encryption = dBUserEncryptionKeys.userKeyName;

                            //Create the client for the azure KeyVault Access
                            var client = new KeyClient(vaultUri: new Uri(KeyVaultUrl), credential: new ClientSecretCredential(tenantId, clientid, client_secret));

                            //Retrive the key from the azure Key Vault
                            KeyVaultKey key = await client.GetKeyAsync(keyName);

                            //Now Creating the Crypto Client for the Encryption of the user Data
                            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new ClientSecretCredential(tenantId, clientid, client_secret));

                            //get the Account Details
                            DocumentReference documentReference_for_getting_data = db.Collection("UserAccounts").Document(email_Address).Collection("MyAccounts").Document(accountName);

                            //get the snapshots for the document
                            DocumentSnapshot documentSnapshot_for_getting_data = await documentReference_for_getting_data.GetSnapshotAsync();

                            if (documentSnapshot_for_getting_data.Exists)
                            {
                                //intiliaze the AccountData object and conver the snapshot to the Account Data object
                                dBAccountData = new DBAccountData();
                                dBAccountData = documentSnapshot_for_getting_data.ConvertTo <DBAccountData>();

                                //perform the decryption
                                DecryptResult decryptResult_for_userName = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, Convert.FromBase64String(dBAccountData.accountUserName));

                                DecryptResult decryptResult_for_password = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, Convert.FromBase64String(dBAccountData.accountPassword));

                                //convert decrypted result to the string
                                string decrypted_username_plaintext = Encoding.UTF8.GetString(decryptResult_for_userName.Plaintext);
                                string decrypted_password_plaintext = Encoding.UTF8.GetString(decryptResult_for_password.Plaintext);

                                //chnage the decrypted string to the plaintext
                                dBAccountData.accountUserName = decrypted_username_plaintext;
                                dBAccountData.accountPassword = decrypted_password_plaintext;

                                data           = new UserAccountData();
                                data.userEmail = email_Address;
                                data.Name      = dBAccountData.accountName;
                                data.UserName  = dBAccountData.accountUserName;
                                data.Password  = dBAccountData.accountPassword;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Error Occured while performing the decryption of the Username ans Password";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }
            return(data);
        }
        public bool Store(UserAccountData data)
        {
            if (data == null)
                return false;
                       
            m_log.DebugFormat(
                "[NULL USER ACCOUNT DATA]: Storing user account {0} {1} {2} {3}", 
                data.FirstName, data.LastName, data.PrincipalID, this.GetHashCode());
            
            m_DataByUUID[data.PrincipalID] = data;
            m_DataByName[data.FirstName + " " + data.LastName] = data;
            if (data.Data.ContainsKey("Email") && data.Data["Email"] != null && data.Data["Email"] != string.Empty)
                m_DataByEmail[data.Data["Email"]] = data;
            
//            m_log.DebugFormat("m_DataByUUID count is {0}, m_DataByName count is {1}", m_DataByUUID.Count, m_DataByName.Count);

            return true;
        }
        public async Task <bool> deleteAccount(UserAccountData userAccountData)
        {
            bool is_account_deleted = false;

            //connect to the database
            bool connection_result = connectToFirebase();

            try{
                //if connection is succesfull
                if (connection_result)
                {
                    bool accountExists = false;

                    //Query to check whether the account with same acoount name exists or not
                    Query checkIfAccountExists = db.Collection("UserAccounts").Document(userAccountData.userEmail).Collection("MyAccounts");

                    //if the object is not null means the user has some account in the database
                    if (checkIfAccountExists != null)
                    {
                        //get the snapshot of all the collection for the account name
                        QuerySnapshot snaps = await checkIfAccountExists.GetSnapshotAsync();

                        //Iterate through the collection and check for the same account name
                        foreach (DocumentSnapshot snap in snaps)
                        {
                            if (snap.Exists)
                            {
                                //remove all the white spaces characters from the string
                                string snapId          = snap.Id.ToString().Replace(" ", "").ToLower();
                                string userAccountName = userAccountData.Name.ToString().Replace(" ", "").ToLower();

                                //compare the string
                                if (snapId.Equals(userAccountName))
                                {
                                    accountExists = true;
                                }
                            }
                        }
                    }
                    if (accountExists)
                    {
                        //delete the account from the firestore
                        DocumentReference documentReference_for_deletion = db.Collection("UserAccounts").Document(userAccountData.userEmail).Collection("MyAccounts").Document(userAccountData.Name);
                        await documentReference_for_deletion.DeleteAsync();

                        //change the result of the account deletion variable
                        is_account_deleted = true;
                    }
                }
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Error Occured while deletion of this Account";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }

            //return the result of this operation
            return(is_account_deleted);
        }
 public Task UpdateAsync(UserAccountData userAccountData)
 {
     _context.Set <UserAccountData>().Attach(userAccountData);
     return(_context.SaveChangesAsync());
 }
        public bool Store(UserAccountData data)
        {
            if (data.Data.ContainsKey("UUID"))
                data.Data.Remove("UUID");
            if (data.Data.ContainsKey("ScopeID"))
                data.Data.Remove("ScopeID");

            string[] fields = new List<string>(data.Data.Keys).ToArray();

            using (SqlConnection conn = new SqlConnection(m_ConnectionString))
            using (SqlCommand cmd = new SqlCommand())
            {
                StringBuilder updateBuilder = new StringBuilder();
                updateBuilder.AppendFormat("update '{0}' set ", m_Realm);
                bool first = true;
                foreach (string field in fields)
                {
                    if (!first)
                        updateBuilder.Append(", ");
                    updateBuilder.AppendFormat("'{0}' = @{0}", field);

                    first = false;

                    cmd.Parameters.AddWithValue("@" + field, data.Data[field]);
                }

                updateBuilder.Append(" where UUID = @principalID");

                if (data.ScopeID != UUID.Zero)
                    updateBuilder.Append(" and ScopeID = @scopeID");

                cmd.CommandText = updateBuilder.ToString();
                cmd.Connection = conn;
                cmd.Parameters.AddWithValue("@principalID", data.PrincipalID);
                cmd.Parameters.AddWithValue("@scopeID", data.ScopeID);
                conn.Open();

                if (cmd.ExecuteNonQuery() < 1)
                {
                    StringBuilder insertBuilder = new StringBuilder();
                    insertBuilder.AppendFormat("insert into '{0}' ('UUID', 'ScopeID', '", m_Realm);
                    insertBuilder.Append(String.Join("', '", fields));
                    insertBuilder.Append("') values ( @principalID, @scopeID, @");
                    insertBuilder.Append(String.Join(", @", fields));
                    insertBuilder.Append(")");

                    cmd.CommandText = insertBuilder.ToString();

                    if (cmd.ExecuteNonQuery() < 1)
                    {
                        return false;
                    }
                }
            }
            return true;
        }
 protected UserAccount ToUserAccount(UserAccountData d)
 {
     UserAccount account = new UserAccount(d.Data.ToDictionary(p => p.Key, p => (object)p.Value));
     account.PrincipalID = d.PrincipalID;
     account.ScopeID = d.ScopeID;
     account.FirstName = d.FirstName;
     account.LastName = d.LastName;
     return account;
 }
        public async Task <bool> updateAccount(UserAccountData userAccountData)
        {
            bool is_account_updated = false;

            //connect to the database
            bool connection_result = connectToFirebase();

            try
            {
                //if connection is succesfull
                if (connection_result)
                {
                    bool accountExists = false;

                    //Query to check whether the account with same acoount name exists or not
                    Query checkIfAccountExists = db.Collection("UserAccounts").Document(userAccountData.userEmail).Collection("MyAccounts");

                    //if the object is not null means the user has some account in the database
                    if (checkIfAccountExists != null)
                    {
                        //get the snapshot of all the collection for the account name
                        QuerySnapshot snaps = await checkIfAccountExists.GetSnapshotAsync();

                        //Iterate through the collection and check for the same account name
                        foreach (DocumentSnapshot snap in snaps)
                        {
                            if (snap.Exists)
                            {
                                //remove all the white spaces characters from the string
                                string snapId          = snap.Id.ToString().Replace(" ", "").ToLower();
                                string userAccountName = userAccountData.Name.ToString().Replace(" ", "").ToLower();

                                //compare the string
                                if (snapId.Equals(userAccountName))
                                {
                                    accountExists = true;
                                }
                            }
                        }
                    }
                    if (accountExists)
                    {
                        //update the account data
                        //first of all encrypt the user Data
                        //Get the User Encryption Key from the firestore database
                        DocumentReference getUserKey = db.Collection("UserEncryptionKeys").Document(userAccountData.userEmail);

                        //get the snapshot for the same
                        DocumentSnapshot snapshot = await getUserKey.GetSnapshotAsync();

                        if (snapshot.Exists)
                        {
                            string keyName = "";
                            Dictionary <string, object> userKeyDict = snapshot.ToDictionary();
                            foreach (KeyValuePair <string, object> pair in userKeyDict)
                            {
                                if (pair.Key == "userKeyName")
                                {
                                    keyName = pair.Value.ToString();
                                    break;
                                }
                            }

                            //Convert to the DBUserEncryption
                            //DBUserEncryptionKeys dBUserEncryptionKeys = snapshot.ConvertTo<DBUserEncryptionKeys>();
                            //string key_Name_For_Encryption = dBUserEncryptionKeys.userKeyName;

                            //Create the client for the azure KeyVault Access
                            var client = new KeyClient(vaultUri: new Uri(KeyVaultUrl), credential: new ClientSecretCredential(tenantId, clientid, client_secret));

                            //Retrive the key from the azure Key Vault
                            KeyVaultKey key = await client.GetKeyAsync(keyName);

                            //Now Creating the Crypto Client for the Encryption of the user Data
                            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new ClientSecretCredential(tenantId, clientid, client_secret));

                            //Convert the Data into the byte array
                            byte[] newAccountUserName = Encoding.UTF8.GetBytes(userAccountData.UserName);
                            byte[] newAccountPassword = Encoding.UTF8.GetBytes(userAccountData.Password);

                            //Create the EncryptionResult Object to perform the encryption on the user data
                            EncryptResult encryptResult_for_userName = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, newAccountUserName);

                            EncryptResult encryptResult_for_password = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, newAccountPassword);

                            //Retrive the Cipher text from this Encryption Result objects
                            string newAccountUserNameCipherText = Convert.ToBase64String(encryptResult_for_userName.Ciphertext);
                            string newAccountPasswordCipherText = Convert.ToBase64String(encryptResult_for_password.Ciphertext);

                            //add the account in the database
                            DocumentReference documentReference = db.Collection("UserAccounts").Document(userAccountData.userEmail).Collection("MyAccounts").Document(userAccountData.Name);

                            //Create th Dictonary to add the data
                            Dictionary <string, object> keyValuePairs = new Dictionary <string, object>()
                            {
                                {
                                    "accountName", userAccountData.Name
                                },
                                {
                                    "accountUserName", newAccountUserNameCipherText
                                },
                                {
                                    "accountPassword", newAccountPasswordCipherText
                                }
                            };

                            //Synchronously add the new Account to the firestore database
                            await documentReference.UpdateAsync(keyValuePairs);

                            is_account_updated = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Error Occured while deletion of this Account";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }
            finally
            {
            }
            //return the result of this operation
            return(is_account_updated);
        }
 public bool SetHomePosition(UserAccountData data, UUID regionID, UUID regionSecret)
 {
     return false;
 }
 public bool CreateUserAccountData(UserAccountData data, UUID principalID, UUID sessionID)
 {
     return false;
 }
Exemple #36
0
        public static void Seed(this ModelBuilder modelBuilder)
        {
            var root = new UserAccountData
                       (
                Guid.NewGuid(),
                login: "******",
                email: "*****@*****.**",
                firstName: "FirstNameRoot",
                lastName: "LastNameRoot",
                street: "StreetRoot",
                city: "CityRoot",
                zipCode: "ZipCodeRoot",
                country: "CountryRoot",
                btcWalletAddress: "BtcWalletAddressRoot",
                role: UserRolesHelper.Root
                       );
            var hashSaltForRoot = Security.PasswordUtilities.PasswordEncryptionUtilities.GenerateSaltedHash("test$123");

            root.SetPassword(hashSaltForRoot.Salt, hashSaltForRoot.Hash);
            root.PaidMembershipFee();

            var admin = new UserAccountData
                        (
                Guid.NewGuid(),
                login: "******",
                email: "*****@*****.**",
                firstName: "FirstNameAdmin",
                lastName: "LastNameAdmin",
                street: "StreetAdmin",
                city: "CityAdmin",
                zipCode: "ZipCodeAdmin",
                country: "CountryAdmin",
                btcWalletAddress: "BtcWalletAddressAdmin",
                role: UserRolesHelper.Admin
                        );
            var hashSaltForAdmin = Security.PasswordUtilities.PasswordEncryptionUtilities.GenerateSaltedHash("test$123");

            admin.SetPassword(hashSaltForAdmin.Salt, hashSaltForAdmin.Hash);
            admin.PaidMembershipFee();

            modelBuilder.Entity <UserAccountData>().HasData(root, admin);


            var root1MultiAccount = new UserMultiAccount
                                    (
                id: Guid.NewGuid(),
                userAccountDataId: root.Id,
                sponsorId: null,
                multiAccountName: "root-001"
                                    );

            root1MultiAccount.SetAsMainAccount();

            var root2MultiAccount = new UserMultiAccount
                                    (
                id: Guid.NewGuid(),
                userAccountDataId: root.Id,
                sponsorId: null,
                multiAccountName: "root-002"
                                    );

            var root3MultiAccount = new UserMultiAccount
                                    (
                id: Guid.NewGuid(),
                userAccountDataId: root.Id,
                sponsorId: null,
                multiAccountName: "root-003"
                                    );

            var admin1MultiAccount = new UserMultiAccount
                                     (
                id: Guid.NewGuid(),
                userAccountDataId: admin.Id,
                sponsorId: null,
                multiAccountName: "admin-001"
                                     );

            admin1MultiAccount.SetReflink("xm3dgjTbckuxSfk0");
            admin1MultiAccount.SetAsMainAccount();

            var admin2MultiAccount = new UserMultiAccount
                                     (
                id: Guid.NewGuid(),
                userAccountDataId: admin.Id,
                sponsorId: null,
                multiAccountName: "admin-002"
                                     );

            admin2MultiAccount.SetReflink("CbJGE3bl65zWhUwK");

            var admin3MultiAccount = new UserMultiAccount
                                     (
                id: Guid.NewGuid(),
                userAccountDataId: admin.Id,
                sponsorId: null,
                multiAccountName: "admin-003"
                                     );

            admin3MultiAccount.SetReflink("nB1Mw99LCQuKXUY2");

            var admin4MultiAccount = new UserMultiAccount
                                     (
                id: Guid.NewGuid(),
                userAccountDataId: admin.Id,
                sponsorId: null,
                multiAccountName: "admin-004"
                                     );

            admin4MultiAccount.SetReflink("2ERrHKzmA7bigBeY");

            modelBuilder.Entity <UserMultiAccount>().HasData(
                root1MultiAccount, root2MultiAccount, root3MultiAccount,
                admin1MultiAccount, admin2MultiAccount, admin3MultiAccount, admin4MultiAccount);


            #region Seed Matrix Level 0
            var root1MatrixPosition = new MatrixPosition
                                      (
                // root-001
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 30
                                      );
            var root2MatrixPosition = new MatrixPosition
                                      (
                // root-002
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: root1MatrixPosition.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 15
                                      );
            var root3MatrixPosition = new MatrixPosition
                                      (
                // root-003
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: root1MatrixPosition.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 16,
                right: 29
                                      );
            var admin1MatrixPosition = new MatrixPosition
                                       (
                // admin-001
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: root2MatrixPosition.Id,
                userMultiAccountId: admin1MultiAccount.Id,
                depthLevel: 2,
                left: 3,
                right: 8
                                       );
            var admin2MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: root2MatrixPosition.Id,
                userMultiAccountId: admin2MultiAccount.Id,
                depthLevel: 2,
                left: 9,
                right: 14
                                       );
            var admin3MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: root3MatrixPosition.Id,
                userMultiAccountId: admin3MultiAccount.Id,
                depthLevel: 2,
                left: 17,
                right: 22
                                       );
            var admin4MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: root3MatrixPosition.Id,
                userMultiAccountId: admin4MultiAccount.Id,
                depthLevel: 2,
                left: 23,
                right: 28
                                       );
            var empty1MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin1MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 4,
                right: 5
                                       );
            var empty2MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin1MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 6,
                right: 7
                                       );
            var empty3MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin2MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 10,
                right: 11
                                       );
            var empty4MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin2MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 12,
                right: 13
                                       );
            var empty5MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin3MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 18,
                right: 19
                                       );
            var empty6MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin3MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 20,
                right: 21
                                       );
            var empty7MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin4MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 24,
                right: 25
                                       );
            var empty8MatrixPosition = new MatrixPosition
                                       (
                id: Guid.NewGuid(),
                matrixLevel: 0,
                parentId: admin4MatrixPosition.Id,
                userMultiAccountId: null,
                depthLevel: 3,
                left: 26,
                right: 27
                                       );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPosition,
                root2MatrixPosition,
                root3MatrixPosition,
                admin1MatrixPosition,
                admin2MatrixPosition,
                admin3MatrixPosition,
                admin4MatrixPosition,
                empty1MatrixPosition,
                empty2MatrixPosition,
                empty3MatrixPosition,
                empty4MatrixPosition,
                empty5MatrixPosition,
                empty6MatrixPosition,
                empty7MatrixPosition,
                empty8MatrixPosition
                );
            #endregion
            #region Seed Matrix Level 1
            var root1MatrixPositionLvl1 = new MatrixPosition
                                          (
                // root-001
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 14
                                          );
            var root2MatrixPositionLvl1 = new MatrixPosition
                                          (
                // root-002
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: root1MatrixPositionLvl1.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 7
                                          );
            var root3MatrixPositionLvl1 = new MatrixPosition
                                          (
                // root-003
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: root1MatrixPositionLvl1.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 8,
                right: 13
                                          );
            var empty1MatrixPositionLvl1 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: root2MatrixPositionLvl1.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 3,
                right: 4
                                           );
            var empty2MatrixPositionLvl1 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: root2MatrixPositionLvl1.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 5,
                right: 6
                                           );
            var empty3MatrixPositionLvl1 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: root3MatrixPositionLvl1.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 9,
                right: 10
                                           );
            var empty4MatrixPositionLvl1 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 1,
                parentId: root3MatrixPositionLvl1.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 11,
                right: 12
                                           );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPositionLvl1,
                root2MatrixPositionLvl1,
                root3MatrixPositionLvl1,
                empty1MatrixPositionLvl1,
                empty2MatrixPositionLvl1,
                empty3MatrixPositionLvl1,
                empty4MatrixPositionLvl1
                );
            #endregion
            #region Seed Matrix Level 2
            var root1MatrixPositionLvl2 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 14
                                          );
            var root2MatrixPositionLvl2 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: root1MatrixPositionLvl2.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 7
                                          );
            var root3MatrixPositionLvl2 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: root1MatrixPositionLvl2.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 8,
                right: 13
                                          );
            var empty1MatrixPositionLvl2 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: root2MatrixPositionLvl2.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 3,
                right: 4
                                           );
            var empty2MatrixPositionLvl2 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: root2MatrixPositionLvl2.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 5,
                right: 6
                                           );
            var empty3MatrixPositionLvl2 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: root3MatrixPositionLvl2.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 9,
                right: 10
                                           );
            var empty4MatrixPositionLvl2 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 2,
                parentId: root3MatrixPositionLvl2.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 11,
                right: 12
                                           );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPositionLvl2,
                root2MatrixPositionLvl2,
                root3MatrixPositionLvl2,
                empty1MatrixPositionLvl2,
                empty2MatrixPositionLvl2,
                empty3MatrixPositionLvl2,
                empty4MatrixPositionLvl2
                );
            #endregion
            #region Seed Matrix Level 3
            var root1MatrixPositionLvl3 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 14
                                          );
            var root2MatrixPositionLvl3 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: root1MatrixPositionLvl3.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 7
                                          );
            var root3MatrixPositionLvl3 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: root1MatrixPositionLvl3.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 8,
                right: 13
                                          );
            var empty1MatrixPositionLvl3 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: root2MatrixPositionLvl3.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 3,
                right: 4
                                           );
            var empty2MatrixPositionLvl3 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: root2MatrixPositionLvl3.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 5,
                right: 6
                                           );
            var empty3MatrixPositionLvl3 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: root3MatrixPositionLvl3.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 9,
                right: 10
                                           );
            var empty4MatrixPositionLvl3 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 3,
                parentId: root3MatrixPositionLvl3.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 11,
                right: 12
                                           );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPositionLvl3,
                root2MatrixPositionLvl3,
                root3MatrixPositionLvl3,
                empty1MatrixPositionLvl3,
                empty2MatrixPositionLvl3,
                empty3MatrixPositionLvl3,
                empty4MatrixPositionLvl3
                );
            #endregion
            #region Seed Matrix Level 4
            var root1MatrixPositionLvl4 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 14
                                          );
            var root2MatrixPositionLvl4 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: root1MatrixPositionLvl4.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 7
                                          );
            var root3MatrixPositionLvl4 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: root1MatrixPositionLvl4.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 8,
                right: 13
                                          );
            var empty1MatrixPositionLvl4 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: root2MatrixPositionLvl4.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 3,
                right: 4
                                           );
            var empty2MatrixPositionLvl4 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: root2MatrixPositionLvl4.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 5,
                right: 6
                                           );
            var empty3MatrixPositionLvl4 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: root3MatrixPositionLvl4.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 9,
                right: 10
                                           );
            var empty4MatrixPositionLvl4 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 4,
                parentId: root3MatrixPositionLvl4.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 11,
                right: 12
                                           );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPositionLvl4,
                root2MatrixPositionLvl4,
                root3MatrixPositionLvl4,
                empty1MatrixPositionLvl4,
                empty2MatrixPositionLvl4,
                empty3MatrixPositionLvl4,
                empty4MatrixPositionLvl4
                );
            #endregion
            #region Seed Matrix Level 5
            var root1MatrixPositionLvl5 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 14
                                          );
            var root2MatrixPositionLvl5 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: root1MatrixPositionLvl5.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 7
                                          );
            var root3MatrixPositionLvl5 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: root1MatrixPositionLvl5.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 8,
                right: 13
                                          );
            var empty1MatrixPositionLvl5 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: root2MatrixPositionLvl5.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 3,
                right: 4
                                           );
            var empty2MatrixPositionLvl5 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: root2MatrixPositionLvl5.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 5,
                right: 6
                                           );
            var empty3MatrixPositionLvl5 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: root3MatrixPositionLvl5.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 9,
                right: 10
                                           );
            var empty4MatrixPositionLvl5 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 5,
                parentId: root3MatrixPositionLvl5.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 11,
                right: 12
                                           );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPositionLvl5,
                root2MatrixPositionLvl5,
                root3MatrixPositionLvl5,
                empty1MatrixPositionLvl5,
                empty2MatrixPositionLvl5,
                empty3MatrixPositionLvl5,
                empty4MatrixPositionLvl5
                );
            #endregion
            #region Seed Matrix Level 6
            var root1MatrixPositionLvl6 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: null,
                userMultiAccountId: root1MultiAccount.Id,
                depthLevel: 0,
                left: 1,
                right: 14
                                          );
            var root2MatrixPositionLvl6 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: root1MatrixPositionLvl6.Id,
                userMultiAccountId: root2MultiAccount.Id,
                depthLevel: 1,
                left: 2,
                right: 7
                                          );
            var root3MatrixPositionLvl6 = new MatrixPosition
                                          (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: root1MatrixPositionLvl6.Id,
                userMultiAccountId: root3MultiAccount.Id,
                depthLevel: 1,
                left: 8,
                right: 13
                                          );
            var empty1MatrixPositionLvl6 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: root2MatrixPositionLvl6.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 3,
                right: 4
                                           );
            var empty2MatrixPositionLvl6 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: root2MatrixPositionLvl6.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 5,
                right: 6
                                           );
            var empty3MatrixPositionLvl6 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: root3MatrixPositionLvl6.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 9,
                right: 10
                                           );
            var empty4MatrixPositionLvl6 = new MatrixPosition
                                           (
                id: Guid.NewGuid(),
                matrixLevel: 6,
                parentId: root3MatrixPositionLvl6.Id,
                userMultiAccountId: null,
                depthLevel: 2,
                left: 11,
                right: 12
                                           );

            modelBuilder.Entity <MatrixPosition>().HasData(
                root1MatrixPositionLvl6,
                root2MatrixPositionLvl6,
                root3MatrixPositionLvl6,
                empty1MatrixPositionLvl6,
                empty2MatrixPositionLvl6,
                empty3MatrixPositionLvl6,
                empty4MatrixPositionLvl6
                );
            #endregion
        }
 public UserAccountsRep()
 {
     userAccountsData = new UserAccountData();
 }
        public UserAccountService(IConfigSource config)
            : base(config)
        {
            IConfig userConfig = config.Configs["UserAccountService"];

            if (userConfig == null)
            {
                throw new Exception("No UserAccountService configuration");
            }

            string gridServiceDll = userConfig.GetString("GridService", string.Empty);

            if (gridServiceDll != string.Empty)
            {
                m_GridService = LoadPlugin <IGridService>(gridServiceDll, new Object[] { config });
            }

            string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty);

            if (authServiceDll != string.Empty)
            {
                m_AuthenticationService = LoadPlugin <IAuthenticationService>(authServiceDll, new Object[] { config });
            }

            string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty);

            if (presenceServiceDll != string.Empty)
            {
                m_GridUserService = LoadPlugin <IGridUserService>(presenceServiceDll, new Object[] { config });
            }

            string invServiceDll = userConfig.GetString("InventoryService", string.Empty);

            if (invServiceDll != string.Empty)
            {
                m_InventoryService = LoadPlugin <IInventoryService>(invServiceDll, new Object[] { config });
            }

            string avatarServiceDll = userConfig.GetString("AvatarService", string.Empty);

            if (avatarServiceDll != string.Empty)
            {
                m_AvatarService = LoadPlugin <IAvatarService>(avatarServiceDll, new Object[] { config });
            }

            m_CreateDefaultAvatarEntries = userConfig.GetBoolean("CreateDefaultAvatarEntries", false);

            //  create a system grid god account
            UserAccount ggod = GetUserAccount(UUID.Zero, UUID_GRID_GOD);

            if (ggod == null)
            {
                UserAccountData d = new UserAccountData();

                d.FirstName           = "GRID";
                d.LastName            = "SERVICES";
                d.PrincipalID         = UUID_GRID_GOD;
                d.ScopeID             = UUID.Zero;
                d.Data                = new Dictionary <string, string>();
                d.Data["Email"]       = string.Empty;
                d.Data["Created"]     = Util.UnixTimeSinceEpoch().ToString();
                d.Data["UserLevel"]   = "240";
                d.Data["UserFlags"]   = "0";
                d.Data["ServiceURLs"] = string.Empty;

                m_Database.Store(d);
            }

            if (m_RootInstance == null)
            {
                m_RootInstance = this;

                // In case there are several instances of this class in the same process,
                // the console commands are only registered for the root instance
                if (MainConsole.Instance != null)
                {
                    MainConsole.Instance.Commands.AddCommand("Users", false,
                                                             "create user",
                                                             "create user [<first> [<last> [<pass> [<email> [<user id> [<model>]]]]]]",
                                                             "Create a new user", HandleCreateUser);

                    MainConsole.Instance.Commands.AddCommand("Users", false,
                                                             "reset user password",
                                                             "reset user password [<first> [<last> [<password>]]]",
                                                             "Reset a user password", HandleResetUserPassword);

                    MainConsole.Instance.Commands.AddCommand("Users", false,
                                                             "reset user email",
                                                             "reset user email [<first> [<last> [<email>]]]",
                                                             "Reset a user email address", HandleResetUserEmail);

                    MainConsole.Instance.Commands.AddCommand("Users", false,
                                                             "set user level",
                                                             "set user level [<first> [<last> [<level>]]]",
                                                             "Set user level. If >= 200 and 'allow_grid_gods = true' in OpenSim.ini, "
                                                             + "this account will be treated as god-moded. "
                                                             + "It will also affect the 'login level' command. ",
                                                             HandleSetUserLevel);

                    MainConsole.Instance.Commands.AddCommand("Users", false,
                                                             "show account",
                                                             "show account <first> <last>",
                                                             "Show account details for the given user", HandleShowAccount);
                }
            }
        }
        public UserAccountData[] GetUsers(UUID scopeID, string query)
        {
//            m_log.DebugFormat(
//                "[NULL USER ACCOUNT DATA]: Called GetUsers with scope [{0}], query [{1}]", scopeID, query);
            
            string[] words = query.Split(new char[] { ' ' });

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length < 3)
                {
                    if (i != words.Length - 1)
                        Array.Copy(words, i + 1, words, i, words.Length - i - 1);
                    Array.Resize(ref words, words.Length - 1);
                }
            }

            if (words.Length == 0)
                return new UserAccountData[0];

            if (words.Length > 2)
                return new UserAccountData[0];

            List<string> lst = new List<string>(m_DataByName.Keys);
            if (words.Length == 1)
            {
                lst = lst.FindAll(delegate(string s) { return s.StartsWith(words[0]); });
            }
            else
            {
                lst = lst.FindAll(delegate(string s) { return s.Contains(words[0]) || s.Contains(words[1]); });
            }

            if (lst == null || (lst != null && lst.Count == 0))
                return new UserAccountData[0];

            UserAccountData[] result = new UserAccountData[lst.Count];
            int n = 0;
            foreach (string key in lst)
                result[n++] = m_DataByName[key];

            return result;
        }