Beispiel #1
0
        public ProfileController(IMailService mail)
        {
            _mail = mail;
            _mu = MembershipWrapper.GetUser();

            if (_mu != null) _ua = new UserAccount(_mu.UserName);
        }
Beispiel #2
0
        public static UserAccounts GetUsersInRole(int roleID)
        {
            UserAccounts uars = null;

            // get a configured DbCommand object
            DbCommand comm = DbAct.CreateCommand();
            // set the stored procedure name
            comm.CommandText = "up_GetUsersInRole";

            ADOExtenstion.AddParameter(comm, "roleID", roleID);

            // execute the stored procedure
            DataTable dt = DbAct.ExecuteSelectCommand(comm);

            // was something returned?
            if (dt != null && dt.Rows.Count > 0)
            {
                uars = new UserAccounts();
                UserAccount art = null;
                foreach (DataRow dr in dt.Rows)
                {
                    art = new UserAccount(dr);
                    uars.Add(art);
                }
            }
            return uars;
        }
Beispiel #3
0
        public UserCreateStatus CreateAccount(string username, string password, string fullname, string email)
        {
            bool exists = Repository.FirstOrDefault(u => u.LocalCredentials != null && u.LocalCredentials.Username == username) != null;
            if (!exists)
            {
                if (!Validator.CheckPassword(password))
                    return UserCreateStatus.InsufficientPassword;

                UserAccount user = new UserAccount
                {
                    PublicIdentifier = HashHelper.ComputePublicIdentifier(typeof(UserAccount).Name, username),
                    LocalCredentials = new LocalCredentials
                    {
                        Username = username,
                        Password = HashHelper.ComputePassword(username, password)
                    },
                    Enabled = true,
                    Created = DateTime.Now,
                    Fullname = fullname,
                    Email = email,
                    UserRole = UserRole.User
                };
                Repository.Insert(user);
                return UserCreateStatus.Created;
            }
            ActivityService.UserRegistered(username);
            return UserCreateStatus.UsernameUsed;
        }
    private void SaveToken(string token, string shopName)
    {
        string isExistingShop = Request.QueryString["isES"];

        // save token in database
        DataModelEntities context = new DataModelEntities();

        if (isExistingShop == "0") // new user
        {
            UserAccount userAccount = new UserAccount();

            userAccount.User_Code = UserKey;
            userAccount.Account_Code = (int)Constant.Accounts.Shopify;
            userAccount.Application_Name = shopName;
            userAccount.Config_Value1 = token;
            userAccount.Created_Date = DateTime.Now;
            userAccount.Is_Active = true;

            context.UserAccounts.AddObject(userAccount);
        }
        else
        {
            UserAccount userAccount = context.UserAccounts.First(u => u.User_Code == UserKey && u.Is_Active == true && u.Account_Code == (int)Constant.Accounts.Shopify);
            userAccount.Application_Name = shopName;
            userAccount.Config_Value1 = token;
            userAccount.Modified_Date = DateTime.Now;
            userAccount.User_IP = Request.UserHostAddress;
        }

        context.SaveChanges();
        context = null;
    }
        /// <summary>
        /// Updates session from DB object
        /// </summary>
        /// <param name="user"></param>
        public void UpdateFrom(UserAccount user)
        {
            UpdatedOn = DateTime.UtcNow;
            UserId = user.Id;

            OnUpdate(user);
        }
Beispiel #6
0
        public Task Connect()
        {
            UserAccount ua = new UserAccount(Context.User.Identity.Name);

            ChatRoomUser cru = new ChatRoomUser();

            cru.GetChatRoomUserByUserAccountID(ua.UserAccountID);

            if (cru.ChatRoomUserID == 0)
            {
                cru.CreatedByUserID = ua.UserAccountID;
                cru.ConnectionCode = Context.ConnectionId;
                cru.Create();
            }
            else
            {
                cru.ConnectionCode = Context.ConnectionId;
                cru.UpdatedByUserID = ua.UserAccountID;
                cru.Update();
            }

            Send(@"<i style=""color:yellow;font-size:10px;font-style: italic;"">CONNECTION OPENED</i>", ua.UserAccountID);

            return Clients.joined(Context.ConnectionId, DateTime.UtcNow.ToString());
        }
 /// <summary>
 /// Posts the specified user account.
 /// </summary>
 /// <param name="userAccount">The user account.</param>
 /// <returns>
 /// The Task.
 /// </returns>
 /// <remarks>
 /// This operation allows to authenticate user account.
 /// </remarks>
 /// <response code="400">Bad request</response>
 /// <response code="401">Unauthorized</response>
 /// <response code="404">Account not found</response>
 /// <response code="500">Internal Server Error</response>
 /// <response code="200">Successful</response>
 public async Task<IHttpActionResult> Post(UserAccount userAccount)
 {
     return await this.CreateAsync<User>(async operationResult =>
     {
         await this.AuthenticateUser(operationResult, userAccount);
         return string.Empty;
     });
 }
 public void CallsUpdateOnRepository()
 {
     var repo = new Mock<IUserAccountRepository>();
     var sub = new UserAccountService(repo.Object, null, null);
     var ua = new UserAccount();
     sub.Update(ua);
     repo.Verify(x => x.Update(ua));
 }
        public List<Notification> CheckNewNotifications(UserAccount user, bool isRead)
        {
            List<Notification> notificationList =
                Translators.Notification.ToBusinessObject(
                    _dataAccessObjects.GetNotificationByJobRoleAndIsRead(
                        user.HighestPermission.ToString(), isRead));

            return notificationList;
        }
 public void Update(UserAccount item)
 {
     var other = Get(item.ID);
     if (other != item)
     {
         Remove(other);
         Add(item);
     }
 }
 /// <summary>
 ///  TODO Update Custom Session fields here
 /// </summary>
 /// <param name="user"></param>
 protected void OnUpdate(UserAccount user)
 {
     Email = user.Email;
     if (user.UserFacebookClaims != null && user.UserFacebookClaims.Any())
     {
         var social = user.UserFacebookClaims.First();
         FacebookId = social.Id;
     }
 }
Beispiel #12
0
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSearch.Text))
            {
                ua = new UserAccount(txtSearch.Text);

                LoadUserAddress(ua.UserAccountID);
            }
        }
 public ValidationResult Validate(UserAccountService service, UserAccount account, string value)
 {
     if (value.Length < 4)
     {
         return new ValidationResult("Password must be at least 4 characters long");
     }
     
     return null;
 }
        public List<Notification> CheckAllNotifications(UserAccount user)
        {
            List<Notification> notificationList =
                Translators.Notification.ToBusinessObject(
                    _dataAccessObjects.GetNotificationByJobRole(
                        user.HighestPermission.ToString()));

            return notificationList;
        }
        public void Register(string account, string password)
        {
            var userAccount = new UserAccount();
            userAccount.Account = account;
            userAccount.Password = password.ToBinary();
            userAccount.DelFlag = 0;

            UserAccountDao.Save(userAccount);
        }
Beispiel #16
0
        public ActionResult CreateForum()
        {
            if (_mu == null) return View();

            var ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));
            if (!ua.IsAdmin) return new EmptyResult();

            return View();
        }
 public override void AcceptGroupMembershipRequestFrom(UserAccount contactToAccept)
 {
     if (CanAcceptGroupMembershipRequestFrom(contactToAccept))
     {
         DomainEvents.Raise(new GroupMembershipAcceptedEvent { MembershipAcceptedBy = _requestedGroup, DateTime = DateTime.Now, MembershipRequestedBy = contactToAccept });
     }
     else
     {
         throw new InvalidOperationException("Membership cannot be accepted");
     }
 }
 public UserAccountViewModel(UserAccount user, UrlHelper url)
 {
     Name = user.Name;
     Email = user.Email;
     CreatedDateTime = user.InsertedDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
     LastSeenDateTime = user.LastSeenDateTime?.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
     IsContributor = user.IsContributor;
     IsArchivist = user.IsArchivist;
     IsAdmin = user.IsAdmin;
     EditURL = url.GetURL<UserAdminController>(c => c.EditUser(user.UserAccountId));
 }
Beispiel #19
0
 private ForumController(IForumCategoryRepository forumcategoryRepository, IMailService mail)
 {
     ViewBag.IsAdmin = false;
     _mail = mail;
     _forumcategoryRepository = forumcategoryRepository;
     _mu = MembershipWrapper.GetUser();
     if (_mu != null)
     {
         _ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));
     }
 }
 public override void AllowGroupMembershipRequestTo(UserAccount contactToAllow)
 {
     if (CanAllowGroupMembershipRequestTo(contactToAllow))
     {
         DomainEvents.Raise(new GroupMembershipAllowedEvent { MembershipAllowedBy = _requestedGroup, DateTime = DateTime.Now, MembershipAllowedTo = contactToAllow });
     }
     else
     {
         throw new InvalidOperationException("Membership cannot be allowed");
     }
 }
Beispiel #21
0
 public void UpdateAccount(UserAccount account)
 {
     try
     {
          new UserAccountDb().UpdateAccount(account);
     }
     catch (Exception ex)
     {
         LogServer.WriteLog(ex, "DBError");
     }
 }
    void InitializeData()
    {
        UserAccount userAccount = new UserAccount (couchbaseDatabase);
        userAccount.UserEmail = userDefineKey.TemporaryEmail;
        userAccount.UserID = userDefineKey.TemporaryID;
        userAccount.UserName = userDefineKey.TemporaryUser;
        userAccount.UserToken = userDefineKey.TemporaryToken;

        string UUID = userAccount.Create ();

        PlayerPrefs.SetString (userDefineKey.UUID, UUID);
    }
            public void IsAccountVerified_SetProperly()
            {
                SecuritySettings.Instance = new SecuritySettings();
                SecuritySettings.Instance.RequireAccountVerification = true;
                var sub = new UserAccount("ten", "user", "pass", "email");
                Assert.IsFalse(sub.IsAccountVerified);

                SecuritySettings.Instance = new SecuritySettings();
                SecuritySettings.Instance.RequireAccountVerification = false;
                sub = new UserAccount("ten", "user", "pass", "email");
                Assert.IsTrue(sub.IsAccountVerified);
            }
Beispiel #24
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="userAccount"></param>
        public bool AddSimpleUser(User user, UserAccount userAccount)
        {
            var existingUser = RetrieveSimpleUser(user.Email);

            if (existingUser != null)
            {
                throw new Exception("This user with the assosiated Email Address already exists.");
            }

            if (!StringExtensions.IsValidEmail(user.Email))
            {
                throw new Exception("Email Address entered isn't valid.");
            }

            var addUser = new User
            {
                UserId = user.UserId,
                FirstName = user.FirstName,
                LastName = user.LastName,
                DateOfBirth = user.DateOfBirth,
                Address = user.Address,
                Email = user.Email,
                Company = user.Company,
                PhoneNumber = user.PhoneNumber,
            };

            var addUserAccount = new UserAccount()
            {
                IsAdmin = userAccount.IsAdmin,
                ConfirmedEmail = userAccount.ConfirmedEmail,
                IsAuthorized = userAccount.IsAuthorized,
                LastLogin = userAccount.LastLogin,
                SignupDate = userAccount.SignupDate,
                Locked = userAccount.Locked,
                LoginAttempts = userAccount.LoginAttempts,
                Username = userAccount.Username,
                Password = PasswordHash.CreateHash(userAccount.Password),
                UserAccountId = userAccount.UserAccountId,
                UserUserId = user.UserId,
            };
            try
            {
                _context.Users.Add(addUser);
                _context.UserAccounts.Add(addUserAccount);
                _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Beispiel #25
0
 public CreateArticleStatus Create(string title, string content, CultureInfo culture, UserAccount author)
 {
     Article article = new Article
     {
         Title = title,
         Content = content,
         Culture = culture.TwoLetterISOLanguageName,
         AuthorUserID = author.ID,
         Modified = DateTime.Now
     };
     Repository.Insert(article);
     return CreateArticleStatus.Created;
 }
Beispiel #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                UserAccount ua = new UserAccount(Request.QueryString["username"]);

                if (ua.UserAccountID == 0) return;

                litUserName.Text = ua.UserName;

                gvwReport.DataSource = UserAccountDetail.GetUserAffReport(ua.UserAccountID);
                gvwReport.DataBind();
            }
        }
Beispiel #27
0
        public Task Disconnect()
        {
            ChatRoomUser cru = new ChatRoomUser();

            cru.GetChatRoomUserByConnection(Context.ConnectionId);

            UserAccount ua = new UserAccount(cru.CreatedByUserID);

            cru.DeleteChatRoomUser();

            Send(@"<i style=""color:red;font-size:10px;font-style: italic;"">CONNECTION CLOSED</i>", ua.UserAccountID);

            return Clients.leave(Context.ConnectionId, DateTime.UtcNow.ToString());
        }
Beispiel #28
0
        /// <summary>
        ///     Given the username(s) and role(s), add the user to the role,
        ///     if the role the user being added to doesn't exist, the role is created,
        ///     if the username doesn't exist, they are not created
        /// </summary>
        /// <param name="usernames"></param>
        /// <param name="roleNames"></param>
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            foreach (string t in usernames)
            {
                var eu = new UserAccount(t);

                if (eu.UserAccountID <= 0) continue;

                foreach (string t1 in roleNames)
                {
                    UserAccount.AddUserToRole(eu.UserAccountID, t1);
                }
            }
        }
Beispiel #29
0
        public ActionResult DeleteComment(int commentID)
        {
            var model = new ContentComment(commentID);

            var content = new Content(model.ContentID);

            var ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));

            if (_mu == null || (model.CreatedByUserID != Convert.ToInt32(_mu.ProviderUserKey) && !ua.IsAdmin))
                return new EmptyResult();

            model.Delete();

            return RedirectToAction("Detail", new {@key = content.ContentKey});
        }
    public void FulfillOrder(int UserKey, UserAccount userAccount, string orderID, string trackingNumber, string itemID)
    {
        ShopifyAuthorizationState authState = new ShopifyAuthorizationState();
        authState.AccessToken = userAccount.Config_Value1;
        authState.ShopName = userAccount.Application_Name;

        ShopifyAPIClient api = new ShopifyAPIClient(authState, new JsonDataTranslator());

        string inputData = @"{""fulfillment"": {""tracking_number"": """ + trackingNumber + @""",""line_items"": [{id: """ + itemID + @"""}]}}";

        dynamic _inputData = new JavaScriptSerializer().DeserializeObject(inputData);

        // by default JSON string is returned
        dynamic data = new JavaScriptSerializer().DeserializeObject(api.Post("/admin/orders/" + orderID + "/fulfillments.json", _inputData).ToString());
    }
 public Task RemoveFromRoleAsync(UserAccount user, string roleName, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Beispiel #32
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            var needsDbAction = false;

            var txtUser = txtUsername.Text;
            var active  = togActiveStat.Checked;
            var txtPass = txtPassword.Text;

            if (_userObj == null)
            {
                needsDbAction = true;
            }
            else
            {
                if (!txtUser.Equals(_userObj.Username))
                {
                    _userObj.Username = txtUser;
                    needsDbAction     = true;
                }

                if (active != _userObj.Active)
                {
                    _userObj.Active = active;
                    needsDbAction   = true;
                }

                if (_passwordModified)
                {
                    _userObj.Password = UserAccount.GetPasswordHash(txtPass);
                    needsDbAction     = true;
                }
            }


            if (needsDbAction)
            {
                using (var oH = new ObjectHelper(_dbSettings, _user))
                {
                    StatusObject dbActionStatus;
                    if (_userObj == null)
                    {
                        dbActionStatus = oH.AddUserAccount(txtUser, txtPass, active);
                        if (dbActionStatus.Success)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        else
                        {
                            NotificationHelper.ShowNotification(this, NotificationHelper.NotificationType.Error,
                                                                "Failed to add this new user account. Please try again.");
                        }
                    }
                    else
                    {
                        dbActionStatus = oH.UpdateUserAccount(_userObj);
                        if (dbActionStatus.Success)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        else
                        {
                            NotificationHelper.ShowNotification(this, NotificationHelper.NotificationType.Error,
                                                                "Failed to update this user account. Please try again.");
                        }
                    }
                }
            }
            Close();
        }
        private List <UserAccount> doGetMultiUserAccounts(UUID scopeID, List <string> IDs, out bool suported)
        {
            suported = true;
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            //sendData["SCOPEID"] = scopeID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"]     = "getmultiaccounts";

            sendData["ScopeID"] = scopeID.ToString();
            sendData["IDS"]     = new List <string>(IDs);

            string reply     = string.Empty;
            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri       = m_ServerURI + "/accounts";

            // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                  uri,
                                                                  reqString,
                                                                  m_Auth);
                if (reply == null || (reply != null && reply == string.Empty))
                {
                    m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetMultiUserAccounts received null or empty reply");
                    return(null);
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
            }

            List <UserAccount> accounts = new List <UserAccount>();

            Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

            if (replyData != null)
            {
                if (replyData.ContainsKey("result"))
                {
                    if (replyData["result"].ToString() == "null")
                    {
                        return(accounts);
                    }

                    if (replyData["result"].ToString() == "Failure")
                    {
                        suported = false;
                        return(accounts);
                    }
                }

                Dictionary <string, object> .ValueCollection accountList = replyData.Values;
                //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
                foreach (object acc in accountList)
                {
                    if (acc is Dictionary <string, object> )
                    {
                        UserAccount pinfo = new UserAccount((Dictionary <string, object>)acc);
                        accounts.Add(pinfo);
                    }
                    else
                    {
                        m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetMultiUserAccounts received invalid response type {0}",
                                          acc.GetType());
                    }
                }
            }
            else
            {
                m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetMultiUserAccounts received null response");
            }

            return(accounts);
        }
Beispiel #34
0
 public void CacheAccount(UserAccount account)
 {
 }
Beispiel #35
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region EF数据库配置 (临时)

            //services.AddDbContext<BlockContext>(options =>
            //options.UseSqlServer(Configuration.GetConnectionString("BlockContext")), ServiceLifetime.Transient);

            #endregion

            #region raft网络相关配置
            services.AddMemoryCache();
            services.AddHttpClient();
            services.AddScoped <IInvokeBLL, InvokeBLL>();
            services.AddScoped <IQueryBLL, QueryBLL>();
            services.AddScoped <IIdentityProvider, IdentityProvider>();
            services.AddScoped <IAssemblyProvider, AssemblyProvider>();
            services.AddScoped <IRaftNetService, RaftNetService>();
            services.AddScoped <QMBlockServer.Service.Intetface.ITxService, QMBlockServer.Service.Imp.TxService>();
            #endregion

            #region mongoDB配置
            //区块数据
            services.Configure <BlockDatabaseSettings>(
                Configuration.GetSection(nameof(BlockDatabaseSettings)));
            services.AddSingleton <IBlockDatabaseSettings>(sp =>
                                                           sp.GetRequiredService <IOptions <BlockDatabaseSettings> >().Value);
            //历史数据库
            services.Configure <HistoryDatabaseSettings>(
                Configuration.GetSection(nameof(HistoryDatabaseSettings)));
            services.AddSingleton <IHistoryDatabaseSettings>(sp =>
                                                             sp.GetRequiredService <IOptions <HistoryDatabaseSettings> >().Value);
            //状态数据库
            services.Configure <StatusDatabaseSettings>(
                Configuration.GetSection(nameof(StatusDatabaseSettings)));
            services.AddSingleton <IStatusDatabaseSettings>(sp =>
                                                            sp.GetRequiredService <IOptions <StatusDatabaseSettings> >().Value);

            #endregion

            #region CA账号与节点账号
            var mspFile  = Configuration.GetSection("peerIdentity:MspFile").Value;
            var basepath = AppContext.BaseDirectory;
            var account  = new UserAccount();
            //如果文件存在
            var path = Path.Combine(basepath, mspFile);
            if (File.Exists(Path.Combine(basepath, mspFile)))
            {
                var mspdata = File.ReadAllText(mspFile).Trim();
                account = Newtonsoft.Json.JsonConvert.DeserializeObject <UserAccount>(mspdata);
            }

            var caAccount = new CaAccount()
            {
                Username = Configuration.GetSection("peerIdentity:ca:username").Value,
                Password = Configuration.GetSection("peerIdentity:ca:password").Value
            };
            PeerIdentity peerIdentity = new PeerIdentity()
            {
                Address     = Configuration.GetSection("peerIdentity:peerUrl").Value,
                OrgId       = Configuration.GetSection("peerIdentity:OrgId").Value,
                Certificate = account.Certificate,
                PrivateKey  = account.PrivateKey,
                Name        = account.Certificate?.TBSCertificate.Subject
            };

            services.AddSingleton <UserAccount>(account);
            services.AddSingleton <CaAccount>(caAccount);
            services.AddSingleton <PeerIdentity>(peerIdentity);

            #endregion

            #region auth身份验证与授权

            /*
             * var securityKey = string.IsNullOrEmpty(account.PrivateKey) ? "securityKey" : account.PrivateKey;  //configuration.GetSection("peerIdentity:privateKey").ToString();
             * string name = account.Certificate == null ? "name" : account.Certificate.TBSCertificate.Subject; //configuration.GetSection("peerIdentity:name").ToString();
             *
             * services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
             *      .AddJwtBearer(options =>
             *  {
             *      options.TokenValidationParameters = new TokenValidationParameters
             *      {
             *
             *          //是否验证Issuer
             *          ValidateIssuer = true,
             *          //ValidateAudience = true,
             *          //是否验证Audience
             *          //是否验证失效时间
             *          ValidateLifetime = true,
             *          //验证码有效时间
             *          ClockSkew = TimeSpan.FromSeconds(30),
             *          //是否验证SecurityKey
             *          ValidateIssuerSigningKey = true,
             *          //ValidAudience = Const.Domain,//Audience
             *          //Issuer,这两项和前面签发jwt的设置一致
             *          ValidIssuer = name,
             *          //拿到SecurityKey
             *          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey))
             *      };
             *  });
             * services.AddAuthorization(options =>
             * {
             *  options.AddPolicy("order", policy => policy.RequireClaim("EmployeeNumber"));
             * });
             */
            #endregion

            #region RabbitMQ消息队列配置
            var mq = new MQSetting();
            //Configuration.GetSection("RabbitMQ").Bind(mq);
            //var mqsetting = Configuration.Get<MQSetting>( "RabbitMQ"); .Bind<MQSetting>("RabbitMQ");
            services.AddSingleton(mq);
            #endregion

            services.AddScoped <NodePeer>();
            services.AddControllers();
        }
        public void TestWearAttachmentFromGround()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            Scene         scene = CreateTestScene();
            UserAccount   ua1   = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
            ScenePresence sp    = SceneHelpers.AddScenePresence(scene, ua1);

            SceneObjectGroup so2 = SceneHelpers.AddSceneObject(scene, "att2", sp.UUID);

            {
                SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, "att1", sp.UUID);

                m_numberOfAttachEventsFired = 0;
                scene.AttachmentsModule.AttachObject(sp, so, (uint)AttachmentPoint.Default, false, true, false);

                // Check status on scene presence
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(so.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
                Assert.That(attSo.IsAttachment);
                Assert.That(attSo.UsesPhysics, Is.False);
                Assert.That(attSo.IsTemporary, Is.False);

                // Check item status
                Assert.That(
                    sp.Appearance.GetAttachpoint(attSo.FromItemID),
                    Is.EqualTo((int)AttachmentPoint.LeftHand));

                InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
                Assert.That(attachmentItem, Is.Not.Null);
                Assert.That(attachmentItem.Name, Is.EqualTo(so.Name));

                InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
                Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));

                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(2));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
            }

            // Test wearing a different attachment from the ground.
            {
                scene.AttachmentsModule.AttachObject(sp, so2, (uint)AttachmentPoint.Default, false, true, false);

                // Check status on scene presence
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(so2.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
                Assert.That(attSo.IsAttachment);
                Assert.That(attSo.UsesPhysics, Is.False);
                Assert.That(attSo.IsTemporary, Is.False);

                // Check item status
                Assert.That(
                    sp.Appearance.GetAttachpoint(attSo.FromItemID),
                    Is.EqualTo((int)AttachmentPoint.LeftHand));

                InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
                Assert.That(attachmentItem, Is.Not.Null);
                Assert.That(attachmentItem.Name, Is.EqualTo(so2.Name));

                InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
                Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));

                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
            }

            // Test rewearing an already worn attachment from ground.  Nothing should happen.
            {
                scene.AttachmentsModule.AttachObject(sp, so2, (uint)AttachmentPoint.Default, false, true, false);

                // Check status on scene presence
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(so2.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
                Assert.That(attSo.IsAttachment);
                Assert.That(attSo.UsesPhysics, Is.False);
                Assert.That(attSo.IsTemporary, Is.False);

                // Check item status
                Assert.That(
                    sp.Appearance.GetAttachpoint(attSo.FromItemID),
                    Is.EqualTo((int)AttachmentPoint.LeftHand));

                InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID));
                Assert.That(attachmentItem, Is.Not.Null);
                Assert.That(attachmentItem.Name, Is.EqualTo(so2.Name));

                InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object);
                Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID));

                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
            }
        }
Beispiel #37
0
        public void AddUser(UUID id, string creatorData)
        {
            //m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData);

            UserData oldUser;

            lock (m_UserCache)
                m_UserCache.TryGetValue(id, out oldUser);

            if (oldUser != null)
            {
                if (creatorData == null || creatorData == String.Empty)
                {
                    //ignore updates without creator data
                    return;
                }

                //try update unknown users, but don't update anyone else
                if (oldUser.FirstName == "Unknown" && !creatorData.Contains("Unknown"))
                {
                    lock (m_UserCache)
                        m_UserCache.Remove(id);
                    m_log.DebugFormat("[USER MANAGEMENT MODULE]: Re-adding user with id {0}, creatorData [{1}] and old HomeURL {2}", id, creatorData, oldUser.HomeURL);
                }
                else
                {
                    //we have already a valid user within the cache
                    return;
                }
            }

            UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, id);

            if (account != null)
            {
                AddUser(id, account.FirstName, account.LastName);
            }
            else
            {
                UserData user = new UserData();
                user.Id = id;

                if (!string.IsNullOrEmpty(creatorData))
                {
                    //creatorData = <endpoint>;<name>

                    string[] parts = creatorData.Split(';');
                    if (parts.Length >= 1)
                    {
                        user.HomeURL = parts[0];
                        try
                        {
                            Uri uri = new Uri(parts[0]);
                            user.LastName = "@" + uri.Authority;
                        }
                        catch (UriFormatException)
                        {
                            m_log.DebugFormat("[SCENE]: Unable to parse Uri {0}", parts[0]);
                            user.LastName = "@unknown";
                        }
                    }
                    if (parts.Length >= 2)
                    {
                        user.FirstName = parts[1].Replace(' ', '.');
                    }
                }
                else
                {
                    // Temporarily add unknown user entries of this type into the cache so that we can distinguish
                    // this source from other recent (hopefully resolved) bugs that fail to retrieve a user name binding
                    // TODO: Can be removed when GUN* unknown users have definitely dropped significantly or
                    // disappeared.
                    user.FirstName = "Unknown";
                    user.LastName  = "UserUMMAU4";
                }

                AddUserInternal(user);
            }
        }
 public async Task SetNormalizedUserNameAsync(UserAccount user, string normalizedName, CancellationToken cancellationToken)
 {
 }
 public Task <string> GetNormalizedUserNameAsync(UserAccount user, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Beispiel #40
0
        OSDMap Login2(OSDMap map)
        {
            string Name     = map ["Name"].AsString();
            string Password = map ["Password"].AsString();

            var resp = new OSDMap();

            resp ["GoodLogin"] = OSD.FromBoolean(false);

            var loginService   = m_registry.RequestModuleInterface <ILoginService> ();
            var accountService = m_registry.RequestModuleInterface <IUserAccountService> ();

            if (accountService == null || CheckIfUserExists(map) ["Verified"] != true)
            {
                resp ["Error"] = OSD.FromString("AccountNotFound");
                return(resp);
            }

            UserAccount userAcct = accountService.GetUserAccount(null, Name);

            if (!userAcct.Valid)
            {
                return(resp);            // something nasty here
            }
            if (loginService.VerifyClient(userAcct.PrincipalID, Name, "UserAccount", Password))
            {
                UUID agentID = userAcct.PrincipalID;

                var agentInfo = DataPlugins.RequestPlugin <IAgentConnector> ().GetAgent(agentID);

                bool banned = ((agentInfo.Flags & IAgentFlags.TempBan) == IAgentFlags.TempBan) || ((agentInfo.Flags & IAgentFlags.PermBan) == IAgentFlags.PermBan);

                if (banned) //get ban type
                {
                    if ((agentInfo.Flags & IAgentFlags.PermBan) == IAgentFlags.PermBan)
                    {
                        resp ["Error"] = OSD.FromString("PermBan");
                    }
                    else if ((agentInfo.Flags & IAgentFlags.TempBan) == IAgentFlags.TempBan)
                    {
                        resp ["Error"] = OSD.FromString("TempBan");

                        if (agentInfo.OtherAgentInformation.ContainsKey("TemporaryBanInfo") == true)
                        {
                            resp ["BannedUntil"] = OSD.FromInteger(Util.ToUnixTime(agentInfo.OtherAgentInformation ["TemporaryBanInfo"]));
                        }
                        else
                        {
                            resp ["BannedUntil"] = OSD.FromInteger(0);
                        }
                    }
                    else
                    {
                        resp ["Error"] = OSD.FromString("UnknownBan");
                    }

                    return(resp);
                }

                resp ["GoodLogin"] = OSD.FromBoolean(true);

                resp ["UserLevel"] = OSD.FromInteger(userAcct.UserLevel);
                resp ["UUID"]      = OSD.FromUUID(agentID);
                resp ["FirstName"] = OSD.FromString(userAcct.FirstName);
                resp ["LastName"]  = OSD.FromString(userAcct.LastName);
                resp ["Email"]     = OSD.FromString(userAcct.Email);

                return(resp);
            }

            resp ["Error"] = OSD.FromString("BadPassword");
            return(resp);
        }
        public async Task <bool> IsInRoleAsync(UserAccount user, string roleName, CancellationToken cancellationToken)
        {
            var userRole = user.UserRoles.Find((role) => role.Equals(roleName));

            return(userRole != null);
        }
 public async Task <IList <string> > GetRolesAsync(UserAccount user, CancellationToken cancellationToken)
 {
     return(user.UserRoles);
 }
        public void TestTakeCopyWhenCopierIsNotOwnerWithoutPerms()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            IConfigSource config = new IniConfigSource();

            config.AddConfig("Modules");
            config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule");

            TestScene scene = new SceneHelpers().SetupScene("s1", TestHelpers.ParseTail(0x99), 1000, 1000, config);

            SceneHelpers.SetupSceneModules(scene, config, new PermissionsModule(), new BasicInventoryAccessModule());
            UserAccount ua     = UserAccountHelpers.CreateUserWithInventory(scene, TestHelpers.ParseTail(0x1));
            TestClient  client = (TestClient)SceneHelpers.AddScenePresence(scene, ua.PrincipalID).ControllingClient;

            // Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
            AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;

            sogd.Enabled = false;

            SceneObjectGroup so        = SceneHelpers.AddSceneObject(scene, "so1", TestHelpers.ParseTail(0x2));
            uint             soLocalId = so.LocalId;

            {
                // Check that object is not copied if copy base perms is missing.
                // Should not allow copy if base does not have this.
                so.RootPart.BaseMask = (uint)OpenMetaverse.PermissionMask.Transfer;
                // Must be set so anyone can copy
                so.RootPart.EveryoneMask = (uint)OpenMetaverse.PermissionMask.Copy;

                // Check that object is not copied
                List <uint> localIds = new List <uint>();
                localIds.Add(so.LocalId);

                // Specifying a UUID.Zero in this case will plop it in the Objects folder if we have perms
                scene.DeRezObjects(client, localIds, UUID.Zero, DeRezAction.TakeCopy, UUID.Zero);

                // Check that object isn't copied until we crank the sogd handle.
                SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);
                Assert.That(retrievedPart, Is.Not.Null);
                Assert.That(retrievedPart.ParentGroup.IsDeleted, Is.False);

                sogd.InventoryDeQueueAndDelete();
                // Check that object is still there.
                SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);
                Assert.That(retrievedPart2, Is.Not.Null);
                Assert.That(client.ReceivedKills.Count, Is.EqualTo(0));

                // Check that we have a copy in inventory
                InventoryItemBase item
                    = UserInventoryHelpers.GetInventoryItem(scene.InventoryService, ua.PrincipalID, "Objects/so1");
                Assert.That(item, Is.Null);
            }

            {
                // Check that object is not copied if copy trans perms is missing.
                // Should not allow copy if base does not have this.
                so.RootPart.BaseMask = (uint)OpenMetaverse.PermissionMask.Copy;
                // Must be set so anyone can copy
                so.RootPart.EveryoneMask = (uint)OpenMetaverse.PermissionMask.Copy;

                // Check that object is not copied
                List <uint> localIds = new List <uint>();
                localIds.Add(so.LocalId);

                // Specifying a UUID.Zero in this case will plop it in the Objects folder if we have perms
                scene.DeRezObjects(client, localIds, UUID.Zero, DeRezAction.TakeCopy, UUID.Zero);

                // Check that object isn't copied until we crank the sogd handle.
                SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);
                Assert.That(retrievedPart, Is.Not.Null);
                Assert.That(retrievedPart.ParentGroup.IsDeleted, Is.False);

                sogd.InventoryDeQueueAndDelete();
                // Check that object is still there.
                SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);
                Assert.That(retrievedPart2, Is.Not.Null);
                Assert.That(client.ReceivedKills.Count, Is.EqualTo(0));

                // Check that we have a copy in inventory
                InventoryItemBase item
                    = UserInventoryHelpers.GetInventoryItem(scene.InventoryService, ua.PrincipalID, "Objects/so1");
                Assert.That(item, Is.Null);
            }

            {
                // Check that object is not copied if everyone copy perms is missing.
                // Should not allow copy if base does not have this.
                so.RootPart.BaseMask = (uint)(OpenMetaverse.PermissionMask.Copy | OpenMetaverse.PermissionMask.Transfer);
                // Make sure everyone perm does not allow copy
                so.RootPart.EveryoneMask = (uint)(OpenMetaverse.PermissionMask.All & ~OpenMetaverse.PermissionMask.Copy);

                // Check that object is not copied
                List <uint> localIds = new List <uint>();
                localIds.Add(so.LocalId);

                // Specifying a UUID.Zero in this case will plop it in the Objects folder if we have perms
                scene.DeRezObjects(client, localIds, UUID.Zero, DeRezAction.TakeCopy, UUID.Zero);

                // Check that object isn't copied until we crank the sogd handle.
                SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);
                Assert.That(retrievedPart, Is.Not.Null);
                Assert.That(retrievedPart.ParentGroup.IsDeleted, Is.False);

                sogd.InventoryDeQueueAndDelete();
                // Check that object is still there.
                SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);
                Assert.That(retrievedPart2, Is.Not.Null);
                Assert.That(client.ReceivedKills.Count, Is.EqualTo(0));

                // Check that we have a copy in inventory
                InventoryItemBase item
                    = UserInventoryHelpers.GetInventoryItem(scene.InventoryService, ua.PrincipalID, "Objects/so1");
                Assert.That(item, Is.Null);
            }
        }
        public void TestRezAttachmentFromInventory()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            Scene         scene = CreateTestScene();
            UserAccount   ua1   = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
            ScenePresence sp    = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID);

            InventoryItemBase attItem = CreateAttachmentItem(scene, ua1.PrincipalID, "att", 0x10, 0x20);

            {
                scene.AttachmentsModule.RezSingleAttachmentFromInventory(
                    sp, attItem.ID, (uint)AttachmentPoint.Chest);

                // Check scene presence status
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(attItem.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
                Assert.That(attSo.IsAttachment);
                Assert.That(attSo.UsesPhysics, Is.False);
                Assert.That(attSo.IsTemporary, Is.False);
                Assert.IsFalse(attSo.Backup);

                // Check appearance status
                Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
                Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
            }

            // Test attaching an already attached attachment
            {
                scene.AttachmentsModule.RezSingleAttachmentFromInventory(
                    sp, attItem.ID, (uint)AttachmentPoint.Chest);

                // Check scene presence status
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(attItem.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.Chest));
                Assert.That(attSo.IsAttachment);
                Assert.That(attSo.UsesPhysics, Is.False);
                Assert.That(attSo.IsTemporary, Is.False);

                // Check appearance status
                Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
                Assert.That(sp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));
                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
            }
        }
Beispiel #45
0
 public string CreateUser(UserAccount account, string password)
 {
     return("");
 }
        public void TestWearAttachmentFromInventory()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            Scene         scene = CreateTestScene();
            UserAccount   ua1   = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
            ScenePresence sp    = SceneHelpers.AddScenePresence(scene, ua1.PrincipalID);

            InventoryItemBase attItem1 = CreateAttachmentItem(scene, ua1.PrincipalID, "att1", 0x10, 0x20);
            InventoryItemBase attItem2 = CreateAttachmentItem(scene, ua1.PrincipalID, "att2", 0x11, 0x21);

            {
                m_numberOfAttachEventsFired = 0;
                scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem1.ID, (uint)AttachmentPoint.Default);

                // default attachment point is currently the left hand.
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(attItem1.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
                Assert.That(attSo.IsAttachment);

                // Check appearance status
                Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
                Assert.That(sp.Appearance.GetAttachpoint(attItem1.ID), Is.EqualTo((int)AttachmentPoint.LeftHand));
                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(1));
            }

            // Test wearing a second attachment at the same position
            // Until multiple attachments at one point is implemented, this will remove the first attachment
            // This test relies on both attachments having the same default attachment point (in this case LeftHand
            // since none other has been set).
            {
                scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem2.ID, (uint)AttachmentPoint.Default);

                // default attachment point is currently the left hand.
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(attItem2.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
                Assert.That(attSo.IsAttachment);

                // Check appearance status
                Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
                Assert.That(sp.Appearance.GetAttachpoint(attItem2.ID), Is.EqualTo((int)AttachmentPoint.LeftHand));
                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
            }

            // Test wearing an already attached attachment
            {
                scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, attItem2.ID, (uint)AttachmentPoint.Default);

                // default attachment point is currently the left hand.
                Assert.That(sp.HasAttachments(), Is.True);
                List <SceneObjectGroup> attachments = sp.GetAttachments();
                Assert.That(attachments.Count, Is.EqualTo(1));
                SceneObjectGroup attSo = attachments[0];
                Assert.That(attSo.Name, Is.EqualTo(attItem2.Name));
                Assert.That(attSo.AttachmentPoint, Is.EqualTo((byte)AttachmentPoint.LeftHand));
                Assert.That(attSo.IsAttachment);

                // Check appearance status
                Assert.That(sp.Appearance.GetAttachments().Count, Is.EqualTo(1));
                Assert.That(sp.Appearance.GetAttachpoint(attItem2.ID), Is.EqualTo((int)AttachmentPoint.LeftHand));
                Assert.That(scene.GetSceneObjectGroups().Count, Is.EqualTo(1));

                // Check events
                Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(3));
            }
        }
 public Task <IdentityResult> DeleteAsync(UserAccount user, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
        public void TestSameSimulatorNeighbouringRegionsTeleportV1()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            BaseHttpServer httpServer = new BaseHttpServer(99999);

            MainServer.AddHttpServer(httpServer);
            MainServer.Instance = httpServer;

            AttachmentsModule              attModA = new AttachmentsModule();
            AttachmentsModule              attModB = new AttachmentsModule();
            EntityTransferModule           etmA    = new EntityTransferModule();
            EntityTransferModule           etmB    = new EntityTransferModule();
            LocalSimulationConnectorModule lscm    = new LocalSimulationConnectorModule();

            IConfigSource config        = new IniConfigSource();
            IConfig       modulesConfig = config.AddConfig("Modules");

            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);
            IConfig entityTransferConfig = config.AddConfig("EntityTransfer");

            // In order to run a single threaded regression test we do not want the entity transfer module waiting
            // for a callback from the destination scene before removing its avatar data.
            entityTransferConfig.Set("wait_for_callback", false);

            modulesConfig.Set("InventoryAccessModule", "BasicInventoryAccessModule");

            SceneHelpers sh     = new SceneHelpers();
            TestScene    sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000);
            TestScene    sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm);
            SceneHelpers.SetupSceneModules(
                sceneA, config, new CapabilitiesModule(), etmA, attModA, new BasicInventoryAccessModule());
            SceneHelpers.SetupSceneModules(
                sceneB, config, new CapabilitiesModule(), etmB, attModB, new BasicInventoryAccessModule());

            // FIXME: Hack - this is here temporarily to revert back to older entity transfer behaviour
            lscm.ServiceVersion = "SIMULATION/0.1";

            UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(sceneA, 0x1);

            AgentCircuitData  acd = SceneHelpers.GenerateAgentData(ua1.PrincipalID);
            TestClient        tc  = new TestClient(acd, sceneA);
            List <TestClient> destinationTestClients = new List <TestClient>();

            EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);

            ScenePresence beforeTeleportSp = SceneHelpers.AddScenePresence(sceneA, tc, acd);

            beforeTeleportSp.AbsolutePosition = new Vector3(30, 31, 32);

            InventoryItemBase attItem = CreateAttachmentItem(sceneA, ua1.PrincipalID, "att", 0x10, 0x20);

            sceneA.AttachmentsModule.RezSingleAttachmentFromInventory(
                beforeTeleportSp, attItem.ID, (uint)AttachmentPoint.Chest);

            Vector3 teleportPosition = new Vector3(10, 11, 12);
            Vector3 teleportLookAt   = new Vector3(20, 21, 22);

            m_numberOfAttachEventsFired = 0;
            sceneA.RequestTeleportLocation(
                beforeTeleportSp.ControllingClient,
                sceneB.RegionInfo.RegionHandle,
                teleportPosition,
                teleportLookAt,
                (uint)TeleportFlags.ViaLocation);

            destinationTestClients[0].CompleteMovement();

            // Check attachments have made it into sceneB
            ScenePresence afterTeleportSceneBSp = sceneB.GetScenePresence(ua1.PrincipalID);

            // This is appearance data, as opposed to actually rezzed attachments
            List <AvatarAttachment> sceneBAttachments = afterTeleportSceneBSp.Appearance.GetAttachments();

            Assert.That(sceneBAttachments.Count, Is.EqualTo(1));
            Assert.That(sceneBAttachments[0].AttachPoint, Is.EqualTo((int)AttachmentPoint.Chest));
            Assert.That(sceneBAttachments[0].ItemID, Is.EqualTo(attItem.ID));
            Assert.That(sceneBAttachments[0].AssetID, Is.EqualTo(attItem.AssetID));
            Assert.That(afterTeleportSceneBSp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));

            // This is the actual attachment
            List <SceneObjectGroup> actualSceneBAttachments = afterTeleportSceneBSp.GetAttachments();

            Assert.That(actualSceneBAttachments.Count, Is.EqualTo(1));
            SceneObjectGroup actualSceneBAtt = actualSceneBAttachments[0];

            Assert.That(actualSceneBAtt.Name, Is.EqualTo(attItem.Name));
            Assert.That(actualSceneBAtt.AttachmentPoint, Is.EqualTo((uint)AttachmentPoint.Chest));
            Assert.IsFalse(actualSceneBAtt.Backup);

            Assert.That(sceneB.GetSceneObjectGroups().Count, Is.EqualTo(1));

            // Check attachments have been removed from sceneA
            ScenePresence afterTeleportSceneASp = sceneA.GetScenePresence(ua1.PrincipalID);

            // Since this is appearance data, it is still present on the child avatar!
            List <AvatarAttachment> sceneAAttachments = afterTeleportSceneASp.Appearance.GetAttachments();

            Assert.That(sceneAAttachments.Count, Is.EqualTo(1));
            Assert.That(afterTeleportSceneASp.Appearance.GetAttachpoint(attItem.ID), Is.EqualTo((int)AttachmentPoint.Chest));

            // This is the actual attachment, which should no longer exist
            List <SceneObjectGroup> actualSceneAAttachments = afterTeleportSceneASp.GetAttachments();

            Assert.That(actualSceneAAttachments.Count, Is.EqualTo(0));

            Assert.That(sceneA.GetSceneObjectGroups().Count, Is.EqualTo(0));

            // Check events
            Assert.That(m_numberOfAttachEventsFired, Is.EqualTo(0));
        }
Beispiel #49
0
        public List <UserAccount> GetUserAccounts(List <UUID> scopeIDs, string query)
        {
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            //sendData["SCOPEID"] = scopeID.ToString();
            sendData["VERSIONMIN"] = 0.ToString();
            sendData["VERSIONMAX"] = 0.ToString();
            sendData["METHOD"]     = "getaccounts";

            sendData["ScopeID"] = GetScopeID(scopeIDs);
            sendData["query"]   = query;

            string reply     = string.Empty;
            string reqString = WebUtils.BuildQueryString(sendData);
            // MainConsole.Instance.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
            List <UserAccount> accounts = new List <UserAccount>();

            try
            {
                List <string> m_ServerURIs = m_registry.RequestModuleInterface <IConfigurationService>().FindValueOf("UserAccountServerURI");
                foreach (string m_ServerURI in m_ServerURIs)
                {
                    reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                      m_ServerURI,
                                                                      reqString);
                    if (reply == null || (reply != null && reply == string.Empty))
                    {
                        continue;
                    }

                    Dictionary <string, object> replyData = WebUtils.ParseXmlResponse(reply);

                    if (replyData != null)
                    {
                        if (replyData.ContainsKey("result") && replyData.ContainsKey("result").ToString() == "null")
                        {
                            continue;
                        }

                        Dictionary <string, object> .ValueCollection accountList = replyData.Values;
                        //MainConsole.Instance.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
                        foreach (object acc in accountList)
                        {
                            if (acc is Dictionary <string, object> )
                            {
                                UserAccount pinfo = new UserAccount();
                                pinfo.FromKVP((Dictionary <string, object>)acc);
                                pinfo.GenericData["GridURL"] = m_ServerURI.Remove(m_ServerURI.LastIndexOf('/'));
                                accounts.Add(pinfo);
                            }
                            else
                            {
                                MainConsole.Instance.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}",
                                                                 acc.GetType());
                            }
                        }
                    }
                    else
                    {
                        MainConsole.Instance.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response");
                    }
                }
            }
            catch (Exception e)
            {
                MainConsole.Instance.InfoFormat("[ACCOUNT CONNECTOR]: Exception when contacting accounts server: {0}", e.Message);
            }

            return(accounts);
        }
Beispiel #50
0
        public static void EvaluateHand(GameModel gameStatus, List <CardDeucesWild> cards, UserAccount userAccountInfo)
        {
            int[] faces = new int[13];
            int[] suits = new int[5];

            if (!gameStatus.GameOver)
            {
                userAccountInfo.Credits -= gameStatus.BetAmount;
            }

            foreach (var card in cards.Take(5).ToList())
            {
                GetCardFaceAndSuit(faces, suits, card);
            }
            RankHand(faces, suits, gameStatus, userAccountInfo);
        }
        public GatewayOrderInfoOM PrePay(string code, UserAccount account)
        {
            var codeEntity = QRCode.Deserialize(code);

            if (codeEntity.SystemPlatform != SystemPlatform.Gateway || codeEntity.QrCodeEnum != QRCodeEnum.GateWayPay)
            {
                throw new CommonException(ReasonCode.INVALID_QRCODE, MessageResources.InvalidQRCode);
            }

            var orderDetail = GetGatewayOrderDetail(codeEntity.QRCodeKey);

            if (orderDetail == null)
            {
                throw new CommonException(ReasonCode.INVALID_QRCODE, MessageResources.InvalidQRCode);
            }


            var cryptoCurrency = new CryptocurrencyDAC().GetByCode(orderDetail.Crypto);

            if (cryptoCurrency == null || cryptoCurrency?.Id == null)
            {
                throw new CommonException(ReasonCode.CRYPTO_NOT_EXISTS, "Error: Invalid Cryptocurrency");
            }

            var goDAC        = new GatewayOrderDAC();
            var gatewayOrder = goDAC.GetByTradeNo(orderDetail.Id.ToString());

            if (gatewayOrder != null)
            {
                if (gatewayOrder.Status != GatewayOrderStatus.Pending)
                {
                    throw new CommonException(ReasonCode.ORDER_HAD_COMPLETE, MessageResources.OrderComplated);
                }
            }
            else
            {
                gatewayOrder = new GatewayOrder()
                {
                    OrderNo            = IdentityHelper.OrderNo(),
                    TradeNo            = orderDetail.Id.ToString(),
                    Id                 = Guid.NewGuid(),
                    CryptoId           = cryptoCurrency.Id,
                    MerchantAccountId  = orderDetail.MerchantAccountId,
                    FiatAmount         = orderDetail.FiatAmount,
                    MerchantName       = orderDetail.MerchantName,
                    UserAccountId      = account.Id,
                    CryptoAmount       = orderDetail.CryptoAmount,
                    ActualCryptoAmount = orderDetail.ActualCryptoAmount,
                    FiatCurrency       = orderDetail.FiatCurrency,
                    Markup             = orderDetail.MarkupRate,
                    ActualFiatAmount   = orderDetail.ActualFiatAmount,
                    Status             = GatewayOrderStatus.Pending,
                    ExchangeRate       = orderDetail.ExchangeRate,
                    ExpiredTime        = orderDetail.ExpiredTime,
                    TransactionFee     = orderDetail.TransactionFee,
                    Timestamp          = DateTime.UtcNow,
                    Remark             = orderDetail.Remark
                };
                goDAC.Insert(gatewayOrder);
            }

            return(new GatewayOrderInfoOM()
            {
                Timestamp = DateTime.UtcNow.ToUnixTime().ToString(),
                OrderId = gatewayOrder.Id,
                MerchantName = gatewayOrder.MerchantName,
                CryptoCode = cryptoCurrency.Code,
                ActurlCryptoAmount = gatewayOrder.ActualCryptoAmount
            });
        }
 public void CacheAccount(UserAccount account)
 {
     m_localService.CacheAccount(account);
 }
        /// <summary>
        /// FiiiPay扫描第三方二维码支付
        /// </summary>
        /// <param name="code">二维码字符</param>
        /// <returns></returns>
        public GatewayOrderInfoOM Pay(GatewayPayIM im, UserAccount account)
        {
            new SecurityComponent().VerifyPin(account, im.Pin);

            var gatewayOrder = new GatewayOrderDAC().GetByOrderId(im.OrderId);

            if (gatewayOrder.Status != GatewayOrderStatus.Pending)
            {
                throw new CommonException(ReasonCode.ORDER_HAD_COMPLETE, MessageResources.OrderComplated);
            }
            var cryptoCurrency = new CryptocurrencyDAC().GetById(gatewayOrder.CryptoId);

            if (cryptoCurrency == null || cryptoCurrency?.Id == null)
            {
                throw new CommonException(ReasonCode.CRYPTO_NOT_EXISTS, "Error: Invalid Cryptocurrency");
            }
            var uwComponent = new UserWalletComponent();
            var userWallet  = uwComponent.GetUserWallet(gatewayOrder.UserAccountId.Value, gatewayOrder.CryptoId);

            if (userWallet == null)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }
            if (userWallet.Balance < gatewayOrder.CryptoAmount)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }
            var uwDAC  = new UserWalletDAC();
            var uwsDAC = new UserWalletStatementDAC();
            var goDAC  = new GatewayOrderDAC();

            using (var scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, new TimeSpan(0, 0, 1, 30)))
            {
                uwDAC.Decrease(userWallet.Id, gatewayOrder.ActualCryptoAmount);
                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId      = userWallet.Id,
                    Action        = UserWalletStatementAction.TansferOut,
                    Amount        = -gatewayOrder.ActualCryptoAmount,
                    Balance       = userWallet.Balance - gatewayOrder.ActualCryptoAmount,
                    FrozenAmount  = 0,
                    FrozenBalance = userWallet.FrozenBalance,
                    Timestamp     = DateTime.UtcNow
                });
                gatewayOrder.Status      = GatewayOrderStatus.Completed;
                gatewayOrder.PaymentTime = DateTime.UtcNow;
                goDAC.Update(gatewayOrder);

                new UserTransactionDAC().Insert(new UserTransaction
                {
                    Id           = Guid.NewGuid(),
                    AccountId    = userWallet.UserAccountId,
                    CryptoId     = cryptoCurrency.Id,
                    CryptoCode   = cryptoCurrency.Code,
                    Type         = UserTransactionType.Order,
                    DetailId     = gatewayOrder.Id.ToString(),
                    Status       = (byte)gatewayOrder.Status,
                    Timestamp    = DateTime.UtcNow,
                    Amount       = gatewayOrder.CryptoAmount,
                    OrderNo      = gatewayOrder.OrderNo,
                    MerchantName = gatewayOrder.MerchantName
                });
                scope.Complete();
            }
            RabbitMQSender.SendMessage("FiiiPay_Gateway_PayCompleted", gatewayOrder.TradeNo);
            return(new GatewayOrderInfoOM()
            {
                Timestamp = gatewayOrder.PaymentTime?.ToUnixTime().ToString(),
                OrderId = gatewayOrder.Id,
                MerchantName = gatewayOrder.MerchantName,
                CryptoCode = cryptoCurrency.Code,
                ActurlCryptoAmount = gatewayOrder.ActualCryptoAmount
            });
        }
 public async Task SetPasswordHashAsync(UserAccount user, string passwordHash, CancellationToken cancellationToken)
 {
     user.Password = passwordHash;
 }
        public async Task SeedData()
        {
            if (!_context.OrderStatus.Any())
            {
                var statusOptions = new[]
                {
                    new OrderStatus {
                        Name = "New",
                    },
                    new OrderStatus {
                        Name = "Hold"
                    },
                    new OrderStatus {
                        Name = "Shipped"
                    },
                    new OrderStatus {
                        Name = "Delivered"
                    },
                    new OrderStatus {
                        Name = "Closed"
                    },
                };

                _context.OrderStatus.AddRange(statusOptions);
                await _context.SaveChangesAsync();
            }

            if (!_context.PetTypes.Any())
            {
                var petTypes = new[]
                {
                    new PetType {
                        Name = "Dog"
                    },
                    new PetType {
                        Name = "Cat"
                    },
                    new PetType {
                        Name = "Fish"
                    },
                    new PetType {
                        Name = "Rabbit"
                    }
                };

                _context.PetTypes.AddRange(petTypes);
                await _context.SaveChangesAsync();
            }

            if (!_context.Users.Any() && !_context.Roles.Any())
            {
                var userAdmin = new UserAccount
                {
                    FirstName   = "Maor",
                    LastName    = "Eini",
                    Gender      = "M",
                    DateOfBirth = new DateTime(1989, 11, 24),
                    DateAdded   = DateTime.Now,
                    Email       = "*****@*****.**",
                    PhoneNumber = "0505335313",
                    UserName    = "******",
                    UserAddress = new UserAddress {
                        City = "Rishon Le Zion", BuildingNumber = "5 ", ApartmentNumber = "18", Province = "HaMerkaz", Street = "Kapah", State = "Israel", ZipCode = "7573006"
                    },
                    Orders = new HashSet <Order>(),
                    Pet    = new Pet
                    {
                        Name = "Lucas",
                        Size = "S",
                        Type = _context.PetTypes.Where(p => p.Name == "Dog").SingleOrDefault()
                    }
                };

                var userOrder = new Order
                {
                    OrderedDate     = DateTime.Now,
                    ShippedDate     = DateTime.Now,
                    Status          = _context.OrderStatus.Where(os => os.Name == "New").SingleOrDefault(),
                    TotalPrice      = 10,
                    Products        = new HashSet <OrderItem>(),
                    ShippingAddress = userAdmin.UserAddress
                };


                var ProductOne = new Product
                {
                    Manufacturer = "Nature's Variety",
                    Price        = 5,
                    Name         = "Instinct for small dogs",
                    ProductCode  = "54CD7",
                    Description  = "Instinct 5kg for small dogs. Duck.",
                    Category     = "Dog",
                    SubCategory  = "Food",
                    Image        = "/img/products/food/go.jpg"
                };

                var ProductTwo = new Product
                {
                    Manufacturer = "Nature's Variety",
                    Price        = 5,
                    Name         = "Instinct for large dogs",
                    ProductCode  = "54CD8",
                    Description  = "Instinct 12kg for large dogs. Duck.",
                    Category     = "Dog",
                    SubCategory  = "Bowls",
                    Image        = "/img/products/food/bowls.jpg"
                };

                var orderItemOne = new OrderItem
                {
                    Order   = userOrder,
                    Product = ProductOne
                };

                var orderItemTwo = new OrderItem
                {
                    Order   = userOrder,
                    Product = ProductTwo
                };

                userOrder.Products.Add(orderItemOne);
                userOrder.Products.Add(orderItemTwo);

                userAdmin.Orders.Add(userOrder);
                userAdmin.PasswordHash = new PasswordHasher <UserAccount>().HashPassword(userAdmin, "Maor123#@!");

                var userResult = await _userManager.CreateAsync(userAdmin);

                if (userResult.Succeeded)
                {
                    var adminRole = new UserRole {
                        Name = "Admin"
                    };
                    var adminResult = await _roleManager.CreateAsync(adminRole);

                    if (adminResult.Succeeded)
                    {
                        var result = await _userManager.AddToRoleAsync(userAdmin, adminRole.Name);

                        if (result.Succeeded)
                        {
                            await _context.SaveChangesAsync();
                        }
                    }
                }
            }
        }
 public async Task <bool> HasPasswordAsync(UserAccount user, CancellationToken cancellationToken)
 {
     return(true);
 }
Beispiel #57
0
        private static void RankHand(int[] faces, int[] suits, GameModel gameStatus, UserAccount userAccountInfo)
        {
            SmartEntities context = new SmartEntities();

            if (DeucesWildHandValue.Trips(faces, suits))
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - 3 OF A KIND";
                    gameStatus.WinAmount    = gameStatus.BetAmount;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Three of a Kind";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "3 OF A KIND";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.Straight || DeucesWildHandValue.RankHand(faces, suits) == HandRanking.BroadwayStraight)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - STRAIGHT";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 2;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Straight";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "STRAIGHT";
                }
            }

            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.Flush)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - FLUSH";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 2;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Flush";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "FLUSH";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.FullHouse)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - FULL HOUSE";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 3;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Full House";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "FULL HOUSE";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.Quads)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - 4 OF A KIND";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 4;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Four of a Kind";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "4 OF A KIND";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.StraightFlush)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - STRAIGHT FLUSH";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 9;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Straight Flush";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "STRAIGHT FLUSH";
                }
            }

            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.WildRoyalFlush)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.WinAmount    = gameStatus.BetAmount * 25;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.Message      = "WINNER - WILD ROYAL FLUSH";
                    gameStatus.HandName     = "Wild Royal Flush";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "WILD ROYAL FLUSH";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.FiveOfAKind)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - 5 OF A KIND";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 15;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Five of a Kind";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "5 OF A KIND";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.FourDeuces)
            {
                if (gameStatus.GameOver)
                {
                    gameStatus.Message      = "WINNER - 4 DEUCES";
                    gameStatus.WinAmount    = gameStatus.BetAmount * 200;
                    gameStatus.Credits     += gameStatus.WinAmount;
                    gameStatus.HandName     = "Five of a Kind";
                    userAccountInfo.Credits = gameStatus.Credits;
                    context.Entry(userAccountInfo).State = EntityState.Modified;
                    context.SaveChanges();
                }
                else
                {
                    gameStatus.Message = "4 DEUCES";
                }
            }
            if (DeucesWildHandValue.RankHand(faces, suits) == HandRanking.RoyalFlush)
            {
                if (gameStatus.GameOver)
                {
                    if (gameStatus.BetAmount == 5)
                    {
                        gameStatus.WinAmount    = gameStatus.BetAmount * 800;
                        gameStatus.Credits     += gameStatus.WinAmount;
                        gameStatus.Message      = "WINNER - ROYAL FLUSH";
                        gameStatus.HandName     = "Royal Flush";
                        userAccountInfo.Credits = gameStatus.Credits;
                        context.Entry(userAccountInfo).State = EntityState.Modified;
                        context.SaveChanges();
                    }
                    else
                    {
                        gameStatus.WinAmount    = gameStatus.BetAmount * 250;
                        gameStatus.Credits     += gameStatus.WinAmount;
                        gameStatus.Message      = "WINNER - ROYAL FLUSH";
                        gameStatus.HandName     = "Royal Flush";
                        userAccountInfo.Credits = gameStatus.Credits;
                        context.Entry(userAccountInfo).State = EntityState.Modified;
                        context.SaveChanges();
                    }
                }
                else
                {
                    gameStatus.Message = "ROYAL FLUSH";
                }
            }
            context.Entry(userAccountInfo).State = EntityState.Modified;
            gameStatus.Credits = (int)userAccountInfo.Credits;
            context.SaveChanges();
        }
        public void TestTakeCopyWhenCopierIsOwnerWithPerms()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            IConfigSource config = new IniConfigSource();

            config.AddConfig("Modules");
            config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule");

            TestScene scene = new SceneHelpers().SetupScene("s1", TestHelpers.ParseTail(0x99), 1000, 1000, config);

            SceneHelpers.SetupSceneModules(scene, config, new PermissionsModule(), new BasicInventoryAccessModule());
            UserAccount ua     = UserAccountHelpers.CreateUserWithInventory(scene, TestHelpers.ParseTail(0x1));
            TestClient  client = (TestClient)SceneHelpers.AddScenePresence(scene, ua.PrincipalID).ControllingClient;

            // Turn off the timer on the async sog deleter - we'll crank it by hand for this test.
            AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter;

            sogd.Enabled = false;

            SceneObjectGroup so        = SceneHelpers.AddSceneObject(scene, "so1", ua.PrincipalID);
            uint             soLocalId = so.LocalId;

//            so.UpdatePermissions(
//                ua.PrincipalID, (byte)PermissionWho.Owner, so.LocalId, (uint)OpenMetaverse.PermissionMask.Copy, 1);
//            so.UpdatePermissions(
//                ua.PrincipalID, (byte)PermissionWho.Owner, so.LocalId, (uint)OpenMetaverse.PermissionMask.Transfer, 0);
//            so.UpdatePermissions(
//                ua.PrincipalID, (byte)PermissionWho.Base, so.LocalId, (uint)OpenMetaverse.PermissionMask.Transfer, 0);
//            scene.HandleObjectPermissionsUpdate(client, client.AgentId, client.SessionId, (byte)PermissionWho.Owner, so.LocalId, (uint)OpenMetaverse.PermissionMask.Transfer, 0);

            // Ideally we might change these via client-focussed method calls as commented out above.  However, this
            // becomes very convoluted so we will set only the copy perm directly.
            so.RootPart.BaseMask = (uint)OpenMetaverse.PermissionMask.Copy;
//            so.RootPart.OwnerMask = (uint)OpenMetaverse.PermissionMask.Copy;

            List <uint> localIds = new List <uint>();

            localIds.Add(so.LocalId);

            // Specifying a UUID.Zero in this case will currently plop it in Lost and Found
            scene.DeRezObjects(client, localIds, UUID.Zero, DeRezAction.TakeCopy, UUID.Zero);

            // Check that object isn't copied until we crank the sogd handle.
            SceneObjectPart retrievedPart = scene.GetSceneObjectPart(so.LocalId);

            Assert.That(retrievedPart, Is.Not.Null);
            Assert.That(retrievedPart.ParentGroup.IsDeleted, Is.False);

            sogd.InventoryDeQueueAndDelete();

            // Check that object is still there.
            SceneObjectPart retrievedPart2 = scene.GetSceneObjectPart(so.LocalId);

            Assert.That(retrievedPart2, Is.Not.Null);
            Assert.That(client.ReceivedKills.Count, Is.EqualTo(0));

            // Check that we have a copy in inventory
            InventoryItemBase item
                = UserInventoryHelpers.GetInventoryItem(scene.InventoryService, ua.PrincipalID, "Lost And Found/so1");

            Assert.That(item, Is.Not.Null);
        }
 public Task SetUserNameAsync(UserAccount user, string userName, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Beispiel #60
0
        /// <summary>
        /// Login procedure, as copied from superclass.
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="passwd"></param>
        /// <param name="startLocation"></param>
        /// <param name="scopeID"></param>
        /// <param name="clientVersion"></param>
        /// <param name="clientIP">The very important TCP/IP EndPoint of the client</param>
        /// <returns></returns>
        /// <remarks>You need to change bits and pieces of this method</remarks>
        public new LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID,
                                       string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP)
        {
            bool success = false;
            UUID session = UUID.Random();

            try
            {
                //
                // Get the account and check that it exists
                //
                UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName);
                if (account == null)
                {
                    // Account doesn't exist. Is this a user from an external ID provider?
                    //
                    // <your code here>
                    //
                    // After verification, your code should create a UserAccount object, filled out properly.
                    // Do not store that account object persistently; we don't want to be creating local accounts
                    // for external users! Create and fill out a UserAccount object, because it has the information
                    // that the rest of the code needs.

                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: user not found");
                    return(LLFailedLoginResponse.UserProblem);
                }

                if (account.UserLevel < m_MinLoginLevel)
                {
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: login is blocked for user level {0}", account.UserLevel);
                    return(LLFailedLoginResponse.LoginBlockedProblem);
                }

                // If a scope id is requested, check that the account is in
                // that scope, or unscoped.
                //
                if (scopeID != UUID.Zero)
                {
                    if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero)
                    {
                        m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: user not found");
                        return(LLFailedLoginResponse.UserProblem);
                    }
                }
                else
                {
                    scopeID = account.ScopeID;
                }

                //
                // Authenticate this user
                //
                // Local users and external users will need completely different authentication procedures.
                // The piece of code below is for local users who authenticate with a password.
                //
                if (!passwd.StartsWith("$1$"))
                {
                    passwd = "$1$" + Util.Md5Hash(passwd);
                }
                passwd = passwd.Remove(0, 3); //remove $1$
                string token         = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
                UUID   secureSession = UUID.Zero;
                if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
                {
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: authentication failed");
                    return(LLFailedLoginResponse.UserProblem);
                }

                //
                // Get the user's inventory
                //
                // m_RequireInventory is set to false in .ini, therefore inventory is not required for login.
                // If you want to change this state of affairs and let external users have local inventory,
                // you need to think carefully about how to do that.
                //
                if (m_RequireInventory && m_InventoryService == null)
                {
                    m_log.WarnFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: inventory service not set up");
                    return(LLFailedLoginResponse.InventoryProblem);
                }
                List <InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
                if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
                {
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: unable to retrieve user inventory");
                    return(LLFailedLoginResponse.InventoryProblem);
                }

                if (inventorySkel == null)
                {
                    inventorySkel = new List <InventoryFolderBase>();
                }

                // Get active gestures
                List <InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
                m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);

                //
                // From here on, things should be exactly the same for all users
                //

                //
                // Login the presence
                //
                if (m_PresenceService != null)
                {
                    success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);
                    if (!success)
                    {
                        m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: could not login presence");
                        return(LLFailedLoginResponse.GridProblem);
                    }
                }

                //
                // Change Online status and get the home region
                //
                GridRegion   home   = null;
                GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString());
                if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null)
                {
                    home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);
                }
                if (guinfo == null)
                {
                    // something went wrong, make something up, so that we don't have to test this anywhere else
                    guinfo = new GridUserInfo();
                    guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
                }

                //
                // Find the destination region/grid
                //
                string where = string.Empty;
                Vector3       position    = Vector3.Zero;
                Vector3       lookAt      = Vector3.Zero;
                GridRegion    gatekeeper  = null;
                TeleportFlags flags       = TeleportFlags.Default;
                GridRegion    destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags);
                if (destination == null)
                {
                    m_PresenceService.LogoutAgent(session);
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: destination not found");
                    return(LLFailedLoginResponse.GridProblem);
                }

                //
                // Get the avatar
                //
                AvatarAppearance avatar = null;
                if (m_AvatarService != null)
                {
                    avatar = m_AvatarService.GetAppearance(account.PrincipalID);
                }

                //
                // Instantiate/get the simulation interface and launch an agent at the destination
                //
                string           reason   = string.Empty;
                GridRegion       dest     = null;
                AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where,
                                                              clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest);

                if (aCircuit == null)
                {
                    m_PresenceService.LogoutAgent(session);
                    m_log.InfoFormat("[DIVA LLOGIN SERVICE]: Login failed, reason: {0}", reason);
                    return(new LLFailedLoginResponse("key", reason, "false"));
                }
                // Get Friends list
                FriendInfo[] friendsList = new FriendInfo[0];
                if (m_FriendsService != null)
                {
                    friendsList = m_FriendsService.GetFriends(account.PrincipalID);
                    m_log.DebugFormat("[DIVA LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
                }

                //
                // Finally, fill out the response and return it
                //
                LLLoginResponse response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
                                                               where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP, m_MapTileURL, m_SearchURL, m_Currency);

                m_log.DebugFormat("[DIVA LLOGIN SERVICE]: All clear. Sending login response to client.");
                return(response);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[DIVA LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace);
                if (m_PresenceService != null)
                {
                    m_PresenceService.LogoutAgent(session);
                }
                return(LLFailedLoginResponse.InternalError);
            }
        }