Beispiel #1
0
        public UserData(string userName, bool validateUserExists = false) : base(new ActivityContext(new ActivityPrincipal(new ActivityIdentity(userName))))
        {
            System.Diagnostics.Debug.WriteLine("UserData({0}, {1})", userName, validateUserExists.ToString());
            var val = UserDefinition.Parse(userName);

            if (val == null)
            {
                throw new ArgumentException("UserName does not meet expectations");
            }

            if (validateUserExists)
            {
                VoatIdentityUser user = null;
                if (!String.IsNullOrWhiteSpace(userName))
                {
                    using (var repo = VoatUserManager.Create())
                    {
                        user = repo.FindByName(userName);
                    }
                }
                if (user == null)
                {
                    throw new VoatNotFoundException("User doesn't exist");
                }
            }
            _userNameInit = userName;
        }
Beispiel #2
0
        public UserData(string userName, bool validateUserExists = false)
        {
            System.Diagnostics.Debug.Print("UserData({0}, {1})", userName, validateUserExists.ToString());

            var val = UserDefinition.Parse(userName);

            if (val == null)
            {
                throw new ArgumentException("UserName does not meet expectations");
            }

            if (validateUserExists)
            {
                VoatUser user = null;
                if (!String.IsNullOrWhiteSpace(userName))
                {
                    using (var repo = new UserManager <VoatUser>(new UserStore <VoatUser>(new ApplicationDbContext())))
                    {
                        user = repo.FindByName(userName);
                    }
                }
                if (user == null)
                {
                    throw new VoatNotFoundException("User doesn't exist");
                }
            }
            this._userName = userName;
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     ViewBag.Context = new MessageContextViewModel()
     {
         ViewerContext = UserDefinition.Parse(User.Identity.Name)
     };
     base.OnActionExecuting(filterContext);
 }
        public void TestUserDefintionParse_BugFix2()
        {
            var name  = "i-am-me";
            var input = $"@{name}";
            var d     = UserDefinition.Parse(input);

            Assert.AreEqual(d.Name, name);
        }
        public void TestUserDefintionParse_BugFix1()
        {
            var name  = "API-Words";
            var input = $"{name}";
            var d     = UserDefinition.Parse(input);

            Assert.AreEqual(d.Name, name);
        }
        public void TestUserDefintionParse4()
        {
            var name  = "Test";
            var input = $"b/{name}";
            var d     = UserDefinition.Parse(input);

            Assert.AreEqual(null, d);
        }
        public void TestUserDefintionParse2()
        {
            var name  = "Test";
            var input = $"u/{name}";
            var d     = UserDefinition.Parse(input);

            Assert.AreEqual(d.Name, name);
            Assert.AreEqual(d.Type, IdentityType.User);
        }
        public void TestSubverseDefintionParse1()
        {
            var name  = "Test";
            var input = $"v/{name}";
            var d     = UserDefinition.Parse(input);

            Assert.AreEqual(d.Name, name);
            Assert.AreEqual(d.Type, IdentityType.Subverse);
        }
Beispiel #9
0
        protected void Application_Start()
        {
            var formatters = GlobalConfiguration.Configuration.Formatters;

            formatters.Remove(formatters.XmlFormatter);

            LiveConfigurationManager.Reload(ConfigurationManager.AppSettings);
            LiveConfigurationManager.Start();

            //forces Rules Engine to load
            var x = VoatRulesEngine.Instance;
            //forces thumbgenerator to initialize
            var p = ThumbGenerator.DestinationPathThumbs;

            if (!Settings.SignalRDisabled)
            {
                Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver.Register(typeof(Microsoft.AspNet.SignalR.Hubs.IJavaScriptMinifier), () => new HubMinifier());
            }
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //register global error handler
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new VoatExceptionLogger());

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            ModelMetadataProviders.Current = new CachedDataAnnotationsModelMetadataProvider();

            JsonConvert.DefaultSettings = () => { return(JsonSettings.GetSerializationSettings()); };

            #region Hook Events

            EventHandler <MessageReceivedEventArgs> updateNotificationCount = delegate(object s, MessageReceivedEventArgs e)
            {
                if (!Settings.SignalRDisabled)
                {
                    var userDef = UserDefinition.Parse(e.TargetUserName);
                    if (userDef.Type == IdentityType.User)
                    {
                        //get count of unread notifications
                        var q = new QueryMessageCounts(userDef.Name, userDef.Type, MessageTypeFlag.All, MessageState.Unread);
                        var unreadNotifications = q.Execute().Total;
                        // send SignalR realtime notification to recipient
                        var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                        hubContext.Clients.User(e.TargetUserName).setNotificationsPending(unreadNotifications);
                    }
                }
            };
            EventNotification.Instance.OnMessageReceived      += updateNotificationCount;
            EventNotification.Instance.OnMentionReceived      += updateNotificationCount;
            EventNotification.Instance.OnCommentReplyReceived += updateNotificationCount;

            EventNotification.Instance.OnVoteReceived += (s, e) =>
            {
                if (!Settings.SignalRDisabled)
                {
                    var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                    switch (e.ReferenceType)
                    {
                    case Domain.Models.ContentType.Submission:
                        hubContext.Clients.User(e.TargetUserName).voteChange(1, e.ChangeValue);
                        break;

                    case Domain.Models.ContentType.Comment:
                        hubContext.Clients.User(e.TargetUserName).voteChange(2, e.ChangeValue);
                        break;
                    }
                }
            };

            //TODO: Fuzzy can't wait for this feature!
            EventNotification.Instance.OnHeadButtReceived    += (s, e) => { };
            EventNotification.Instance.OnChatMessageReceived += (s, e) => { };

            #endregion


            //BLOCK: Temp Log ThreadPool Stats
            timer = new Timer(new TimerCallback(o => {
                int workerThreads;
                int completionPortThreads;
                int maxWorkerThreads;
                int maxCompletionPortThreads;

                ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
                ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads);

                var data = new
                {
                    InUse   = maxWorkerThreads - workerThreads,
                    InUseIO = maxCompletionPortThreads - completionPortThreads,
                    AvailableWorkerThreads = workerThreads,
                    AvailableIOThreads     = completionPortThreads,
                    MaxWorkerThreads       = maxWorkerThreads,
                    MaxIOThreads           = maxCompletionPortThreads
                };


                var logEntry = new LogInformation
                {
                    Origin   = Settings.Origin.ToString(),
                    Type     = LogType.Debug,
                    UserName = null,
                    Message  = "ThreadPool Stats",
                    Category = "Monitor",
                    Data     = data
                };

                EventLogger.Instance.Log(logEntry);
            }), null, TimeSpan.Zero, TimeSpan.FromSeconds(15));


            // USE ONLY FOR DEBUG: clear all sessions used for online users count
            // SessionTracker.RemoveAllSessions();
        }
        protected override async Task <CommandResponse> ExecuteStage(CommandStage stage, CommandResponse previous)
        {
            var commandResponse = CommandResponse.FromStatus(Status.Success);

            switch (stage)
            {
            case CommandStage.OnAuthorization:
                if (!User.IsInAnyRole(new[] { UserRole.GlobalAdmin, UserRole.Admin, UserRole.DelegateAdmin, UserRole.GlobalBans }))
                {
                    commandResponse = CommandResponse.FromStatus(Status.Denied, "Permissions not granted");
                }
                break;

            case CommandStage.OnValidation:
                if (_banList == null || _banList.Count() == 0)
                {
                    commandResponse = CommandResponse.FromStatus(Status.Invalid, "Banlist can not be null or empty");
                }
                else
                {
                    foreach (var banItem in _banList)
                    {
                        switch (banItem.Type)
                        {
                        case BanType.Domain:
                            //check full url first
                            var match = Regex.Match(banItem.Name, CONSTANTS.HTTP_LINK_REGEX, RegexOptions.IgnoreCase);
                            if (match.Success)
                            {
                                banItem.Name = match.Groups["domain"].Value;
                            }
                            else
                            {
                                //check partial
                                match = Regex.Match(banItem.Name, CONSTANTS.HOST_AND_PATH_LINK_REGEX, RegexOptions.IgnoreCase);
                                if (!match.Success)
                                {
                                    commandResponse = CommandResponse.FromStatus(Status.Invalid, $"Domain {banItem.Name} is not valid");
                                }
                                else
                                {
                                    banItem.Name = match.Groups["domain"].Value;
                                }
                            }

                            break;

                        case BanType.User:
                            var result = UserDefinition.Parse(banItem.Name);
                            if (result == null)
                            {
                                commandResponse = CommandResponse.FromStatus(Status.Invalid, $"UserName {banItem.Name} is not valid");
                            }
                            else
                            {
                                var originalName = UserHelper.OriginalUsername(result.Name);
                                if (String.IsNullOrEmpty(originalName))
                                {
                                    commandResponse = CommandResponse.FromStatus(Status.Invalid, $"User {banItem.Name} does not exist");
                                }
                                banItem.Name = originalName;
                            }
                            break;
                        }
                    }
                }
                break;
                //case CommandStage.OnExecuted:
                //    if (!User.IsInAnyRole(new[] { UserRole.GlobalAdmin, UserRole.Admin, UserRole.DelegateAdmin, UserRole.GlobalBans }))
                //    {
                //        commandResponse = CommandResponse.FromStatus(Status.Denied, "Permissions not granted");
                //    }
                //    break;
            }

            return(commandResponse);
        }