예제 #1
0
        public void EventFactory_GetDoorEventJson()
        {
            SecurityEvent door = EventMonitor.Events.EventFactory.GetByJSON("{\"Type\":\"Door\", \"Date\":\"2014-02-01 10:01:02\", \"open\": true}");

            Assert.IsTrue(door is SecurityEvent);
            Assert.IsTrue(door is Door);
        }
예제 #2
0
        public void EventFactory_GetAlarmEventJson()
        {
            SecurityEvent alarm = EventMonitor.Events.EventFactory.GetByJSON("{\"Type\":\"alarm\", \"Date\":\"2014-02-01 10:01:05\", \"name\":\"fire\", \"floor\":\"1\", \"room\":\"101\"}");

            Assert.IsTrue(alarm is SecurityEvent);
            Assert.IsTrue(alarm is Alarm);
        }
예제 #3
0
        public void EventFactory_GetImageEventJson()
        {
            SecurityEvent image = EventMonitor.Events.EventFactory.GetByJSON("{\"Type\":\"img\", \"Date\":\"2014-02-01 10:01:02\", \"bytes\": \"ab39szh6\", \"size\": 8}");

            Assert.IsTrue(image is SecurityEvent);
            Assert.IsTrue(image is Image);
        }
        /// <summary>
        /// Performs the actual logging of a security event
        /// </summary>
        /// <param name="projectName">The name of the project.</param>
        /// <param name="userName">The name of the user.</param>
        /// <param name="eventType">The type of event.</param>
        /// <param name="eventRight">The right of the event.</param>
        /// <param name="message">Any security message.</param>
        protected override void DoLogEvent(string projectName, string userName, SecurityEvent eventType, SecurityRight eventRight, string message)
        {
            // Generate the log entry
            XmlDocument auditXml = new XmlDocument();
            XmlElement  xmlRoot  = auditXml.CreateElement("event");

            auditXml.AppendChild(xmlRoot);
            AddXmlElement(auditXml, xmlRoot, "dateTime", DateTime.Now.ToString("o", CultureInfo.CurrentCulture));
            if (!string.IsNullOrEmpty(projectName))
            {
                AddXmlElement(auditXml, xmlRoot, "project", projectName);
            }
            if (!string.IsNullOrEmpty(userName))
            {
                AddXmlElement(auditXml, xmlRoot, "user", userName);
            }
            AddXmlElement(auditXml, xmlRoot, "type", eventType.ToString());
            if (eventRight != SecurityRight.Inherit)
            {
                AddXmlElement(auditXml, xmlRoot, "outcome", eventRight.ToString());
            }
            if (!string.IsNullOrEmpty(message))
            {
                AddXmlElement(auditXml, xmlRoot, "message", message);
            }

            // Write the entry
            string auditLog = executionEnvironment.EnsurePathIsRooted(this.auditFile);

            lock (this)
            {
                File.AppendAllText(auditLog, auditXml.OuterXml.Replace(Environment.NewLine, " ") + Environment.NewLine);
            }
        }
예제 #5
0
 public void Notify(SecurityEvent securityEvent)
 {
     _observers.AsParallel().WithMergeOptions(ParallelMergeOptions.NotBuffered).ForAll(eventSubscriber =>
     {
         eventSubscriber.Update(securityEvent);
     });
 }
 public override void Update(SecurityEvent securityEvent)
 {
     Communication.LoggingService.Instance().LogSecurityEvent(new List <SecurityEvent>()
     {
         securityEvent
     });
 }
예제 #7
0
        public void GetSecurities()
        {
            List <Security> securities = new List <Security>();// TryToLoadSecurities();

            /*  if (securities != null)
             * {
             *    SecurityEvent?.Invoke(securities);
             *    SendLogMessage("Securities downloaded. Count: " + securities.Count, LogMessageType.System);
             *    return;
             * }*/

            SendLogMessage("Securities downloading...", LogMessageType.System);

            List <string> engines = GetEngines();

            List <string> markets = GetMarkets(engines);

            List <string> classes = GetClasses(markets);

            securities = GetSecurities(classes);

            securities = CreateFuturesSection(securities);

            SecurityEvent?.Invoke(securities);

            SendLogMessage("Securities downloaded. Count: " + securities.Count, LogMessageType.System);

            //SaveSecurities(securities);
        }
예제 #8
0
        private List <SecurityEvent> MapSecEvents(IEnumerable <AuditProxy> audits)
        {
            var list = new List <SecurityEvent>();

            foreach (var item in audits)
            {
                var secEvent = new SecurityEvent();

                string found = null;
                ActionFieldsLibrary.ActionMapper.TryGetValue(item.Action, out found);
                var action = found ?? item.Action.ToString();

                secEvent.DeviceTime       = item.InDateTime;
                secEvent.EventName        = EventPrefix + action;
                secEvent.EventDescription = item.Comment;
                secEvent.EventCategory    = item.ObjectName;
                secEvent.UserName         = item.UserBrief == null?item.UserId.ToString() : item.UserBrief;

                secEvent.HostIP   = _settings.Server;
                secEvent.HostName = item.HostInfoName;

                secEvent.ExtraParams.Add("EventID", item.AuditId.ToString());
                secEvent.ExtraParams.Add("ObjectID", item.ObjectId.ToString());

                list.Add(secEvent);
            }

            return(list);
        }
예제 #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                Random random             = new Random();
                List <SecurityEvent> list = new List <SecurityEvent>();

                for (int i = 0; i < 100000; i++)
                {
                    var securityEvent = new SecurityEvent()
                    {
                        PhysicalLocation = "Some Where " + i,
                        DetectorId       = i,
                        EventDescription = "Help " + i,
                        DetectorType     = (EnumsDedectorType)random.Next(0, 1),
                    };

                    list.Add(securityEvent);
                    //   Task task = new Task(() => EventProducer.Instance().LogSecurityEvent(securityEvent));
                    //    task.Start();
                }


                list.AsParallel().ForAll(se => EventProducer.Instance().LogSecurityEvent(se));
            });
        }
예제 #10
0
        /// <summary>
        /// получены инструменты с сервера
        /// </summary>
        /// <param name="products"></param>
        private void ClientReceivedSecurities(RootProducts products)
        {
            List <Security> securities = new List <Security>();

            foreach (var product in products.Data)
            {
                var newSec = new Security();

                newSec.Name          = product.Symbol;
                newSec.NameClass     = product.QuoteAsset;
                newSec.NameFull      = product.Symbol;
                newSec.NameId        = product.Symbol;
                newSec.Decimals      = product.TickSize.DecimalsCount();
                newSec.SecurityType  = SecurityType.CurrencyPair;
                newSec.State         = product.Status == "Normal" ? SecurityStateType.Activ : SecurityStateType.Close;
                newSec.Lot           = 1;
                newSec.PriceStep     = product.TickSize.ToDecimal();
                newSec.PriceStepCost = newSec.PriceStep;
                newSec.Go            = product.MinNotional.ToDecimal();

                securities.Add(newSec);
            }

            SecurityEvent?.Invoke(securities);
        }
예제 #11
0
 private T GetValue()
 {
     if (hashBuffer != GetChecksum())
     {
         SecurityEvent.CallMemoryHacked();
         OnHackedInstance.TryInvoke();
     }
     return(value);
 }
 /// <summary>
 /// Sends a security event to the audit loggers.
 /// </summary>
 /// <param name="projectName">The name of the project.</param>
 /// <param name="userName">The name of the user.</param>
 /// <param name="eventType">The type of event.</param>
 /// <param name="eventRight">The right of the event.</param>
 /// <param name="message">Any security message.</param>
 public virtual void LogEvent(string projectName, string userName, SecurityEvent eventType, SecurityRight eventRight, string message)
 {
     if (loggers != null)
     {
         foreach (IAuditLogger logger in loggers)
         {
             logger.LogEvent(projectName, userName, eventType, eventRight, message);
         }
     }
 }
예제 #13
0
        private void _btn_fire_Click(object sender, EventArgs e)
        {
            var securityEvent = new SecurityEvent()
            {
                PhysicalLocation = "Upper Floor",
                DetectorId       = 1,
                EventDescription = "Fire Fire !!!!",
                DetectorType     = EnumsDedectorType.Fire
            };

            EventProducer.Instance().LogSecurityEvent(securityEvent);
        }
예제 #14
0
 public void LogSecurityEvent(SecurityEvent securityEvent)
 {
     try
     {
         using (var client = new LoggingServiceClient())
         {
             client.LogSecurityEvent(securityEvent);
         }
     }
     catch (Exception)
     {
     }
 }
예제 #15
0
        /// <summary>
        /// пришел список инструментов биржи
        /// </summary>
        private void ClientOnUpdatedSecurities(List <Instrument> securities)
        {
            if (_securities == null)
            {
                _securities = new List <Security>();
            }

            for (int sec = 0; sec < securities.Count; sec++)
            {
                var lmaxSec = securities[sec];

                if (_securities.Find(s => s.Name == lmaxSec.Name.Replace("/", "-")) != null)
                {
                    _securities.Add(
                        new Security
                    {
                        Name          = lmaxSec.Name.Replace("/", "-") + "_2",
                        NameId        = lmaxSec.Id.ToString(),
                        NameClass     = lmaxSec.Contract.Currency,
                        Lot           = lmaxSec.OrderBook.QuantityIncrement,
                        PriceStep     = lmaxSec.OrderBook.PriceIncrement,
                        PriceStepCost = lmaxSec.OrderBook.PriceIncrement,
                    });

                    if (lmaxSec.OrderBook.PriceIncrement < 1)
                    {
                        _securities.Last().Decimals =
                            lmaxSec.OrderBook.PriceIncrement.ToString(CultureInfo.InvariantCulture).Split('.')[1].Length;
                    }
                    continue;
                }
                _securities.Add(
                    new Security
                {
                    Name          = lmaxSec.Name.Replace("/", "-"),
                    NameId        = lmaxSec.Id.ToString(),
                    NameClass     = lmaxSec.Contract.Currency,
                    Lot           = lmaxSec.OrderBook.QuantityIncrement,
                    PriceStep     = lmaxSec.OrderBook.PriceIncrement,
                    PriceStepCost = lmaxSec.OrderBook.PriceIncrement
                });

                if (lmaxSec.OrderBook.PriceIncrement < 1)
                {
                    _securities.Last().Decimals =
                        lmaxSec.OrderBook.PriceIncrement.ToString(CultureInfo.InvariantCulture).Split('.')[1].Length;
                }
            }

            SecurityEvent?.Invoke(_securities);
        }
        /// <summary>
        /// Brokerages can send portfolio updates which should include average price of holdings and the
        /// quantity of holdings, we'll trust this information as truth and just set the portfolio with it
        /// </summary>
        private void HandleSecurityHoldingUpdated(SecurityEvent holding)
        {
            // how close are we?
            var securityHolding = _algorithm.Portfolio[holding.Symbol];
            var deltaQuantity   = securityHolding.Quantity - holding.Quantity;
            var deltaAvgPrice   = securityHolding.AveragePrice - holding.AveragePrice;

            if (deltaQuantity != 0 || deltaAvgPrice != 0)
            {
                Log.Trace(string.Format("BrokerageTransactionHandler.HandleSecurityHoldingUpdated(): {0} DeltaQuantity: {1} DeltaAvgPrice: {2}", holding.Symbol, deltaQuantity, deltaAvgPrice));
            }

            securityHolding.SetHoldings(holding.AveragePrice, holding.Quantity);
        }
예제 #17
0
        public void EventFactory_GetMalformedEventJson()
        {
            SecurityEvent malformed = null;

            try
            {
                malformed = EventMonitor.Events.EventFactory.GetByJSON("malformed");
            }
            catch
            {
                // Can't find a good way to test for thrown exception.
                Assert.IsNull(malformed);
            }
        }
예제 #18
0
 /// <summary>
 /// Logs a security event.
 /// </summary>
 /// <param name="projectName">The name of the project.</param>
 /// <param name="userName">The name of the user.</param>
 /// <param name="eventType">The type of event.</param>
 /// <param name="eventRight">The right of the event.</param>
 /// <param name="message">Any security message.</param>
 public virtual void LogEvent(string projectName, string userName, SecurityEvent eventType, SecurityRight eventRight, string message)
 {
     if ((eventRight == SecurityRight.Allow) && this.logSuccessfulEvents)
     {
         DoLogEvent(projectName, userName, eventType, eventRight, message);
     }
     else if ((eventRight == SecurityRight.Deny) && this.logFailureEvents)
     {
         DoLogEvent(projectName, userName, eventType, eventRight, message);
     }
     else if (eventRight == SecurityRight.Inherit)
     {
         DoLogEvent(projectName, userName, eventType, eventRight, message);
     }
 }
 /// <summary>
 /// Logs a security event.
 /// </summary>
 /// <param name="projectName">The name of the project.</param>
 /// <param name="userName">The name of the user.</param>
 /// <param name="eventType">The type of event.</param>
 /// <param name="eventRight">The right of the event.</param>
 /// <param name="message">Any security message.</param>
 public virtual void LogEvent(string projectName, string userName, SecurityEvent eventType, SecurityRight eventRight, string message)
 {
     if ((eventRight == SecurityRight.Allow) && this.logSuccessfulEvents)
     {
         DoLogEvent(projectName, userName, eventType, eventRight, message);
     }
     else if ((eventRight == SecurityRight.Deny) && this.logFailureEvents)
     {
         DoLogEvent(projectName, userName, eventType, eventRight, message);
     }
     else if (eventRight == SecurityRight.Inherit)
     {
         DoLogEvent(projectName, userName, eventType, eventRight, message);
     }
 }
예제 #20
0
        /// <summary>
        /// Brokerages can send portfolio updates which should include average price of holdings and the
        /// quantity of holdings, we'll trust this information as truth and just set the portfolio with it
        /// </summary>
        private void HandleSecurityHoldingUpdated(SecurityEvent holding)
        {
            // how close are we?
            var securityHolding = _algorithm.Portfolio[new Symbol(holding.Symbol)];
            var deltaQuantity   = securityHolding.Quantity - holding.Quantity;
            var deltaAvgPrice   = securityHolding.AveragePrice - holding.AveragePrice;

            if (deltaQuantity != 0 || deltaAvgPrice != 0)
            {
                Log.Trace(string.Format("BrokerageTransactionHandler.HandleSecurityHoldingUpdated(): {0} DeltaQuantity: {1} DeltaAvgPrice: {2}", holding.Symbol, deltaQuantity, deltaAvgPrice));
            }

            // we don't actually want to do this, this data can be delayed
            //securityHolding.SetHoldings(holding.AveragePrice, holding.Quantity);
        }
        public void Notify(SecurityEvent securityEvent)
        {
            switch (securityEvent.DetectorType)
            {
            case Enums.DedectorType.Fire:
                _notifiers[Enums.SubscriberType.Fire].Notify(securityEvent);
                break;

            case Enums.DedectorType.Security:
                _notifiers[Enums.SubscriberType.Security].Notify(securityEvent);
                break;

            default:
                Console.WriteLine("Not defined yet");
                break;
            }
        }
예제 #22
0
파일: Brokerage.cs 프로젝트: tuddman/Lean
        /// <summary>
        /// Event invocator for the PortfolioChanged event
        /// </summary>
        /// <param name="e">The PortfolioEvent</param>
        protected virtual void OnPortfolioChanged(SecurityEvent e)
        {
            try
            {
                Log.Trace("Brokerage.OnPortfolioChanged(): " + e);

                var handler = SecurityHoldingUpdated;
                if (handler != null)
                {
                    handler(this, e);
                }
            }
            catch (Exception error)
            {
                Log.Error("Brokerage.OnPortfolioChanged(): Caught Error: " + error.Message);
            }
        }
예제 #23
0
        /// <summary>
        /// Given a file path will wait until the file is free, open the file, grab the contents,
        /// and create a SecurityEvent.
        /// </summary>
        /// <param name="path">Path to the file that contains the JSON for the SecurityEvent.</param>
        /// <returns>True if successful, false otherwise.</returns>
        public static bool Process(string path)
        {
            FileStream stream = null;

            byte[] buffer = null;

            try
            {
                if (File.Exists(path))
                {
                    while (true)
                    {
                        try
                        {
                            stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                            buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, buffer.Length);

                            break;
                        }
                        catch (IOException)
                        {
                            System.Diagnostics.Debug.WriteLine("File is locked. Waiting 5ms. File: " + path);
                            System.Threading.Thread.Sleep(5);
                        }
                        finally
                        {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                        }
                    }

                    SecurityEvent myEvent = EventMonitor.Events.EventFactory.GetByJSON(Encoding.ASCII.GetString(buffer));
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Could not read file {0}. Message: {1}", path, ex.Message));
            }

            return(false);
        }
예제 #24
0
            public static SecurityEvent ToSecurityEvent(RuleEvenPlus rep)
            {
                SecurityEvent se = new SecurityEvent();

                se.Description = rep.Desc;
                se.EventGuid   = rep.Guid;
                se.Name        = rep.Name;

                if (rep.Actions != null && rep.Actions.Count > 0)
                {
                    foreach (RuleActionPlus rap in rep.Actions)
                    {
                        se.SecurityActions.Add(ToSecurityAction(rap));
                    }
                }

                return(se);
            }
예제 #25
0
        public void LogEventSendsEventToLogger()
        {
            string        projectName = "Test Project";
            string        userName    = "******";
            SecurityEvent eventType   = SecurityEvent.ForceBuild;
            SecurityRight eventRight  = SecurityRight.Allow;
            string        message     = "A message";

            IAuditLogger logger = mocks.Create <IAuditLogger>(MockBehavior.Strict).Object;

            Mock.Get(logger).Setup(_logger => _logger.LogEvent(projectName, userName, eventType, eventRight, message)).Verifiable();

            manager.AuditLoggers = new IAuditLogger[] {
                logger
            };
            manager.Initialise();
            manager.LogEvent(projectName, userName, eventType, eventRight, message);
        }
        public void LogEventSendsEventToLogger()
        {
            string        projectName = "Test Project";
            string        userName    = "******";
            SecurityEvent eventType   = SecurityEvent.ForceBuild;
            SecurityRight eventRight  = SecurityRight.Allow;
            string        message     = "A message";

            IAuditLogger logger = mocks.CreateMock <IAuditLogger>();

            Expect.Call(delegate { logger.LogEvent(projectName, userName, eventType, eventRight, message); });

            mocks.ReplayAll();
            manager.AuditLoggers = new IAuditLogger[] {
                logger
            };
            manager.Initialise();
            manager.LogEvent(projectName, userName, eventType, eventRight, message);
        }
예제 #27
0
            public static RuleEvenPlus FromSecurityEvent(SecurityEvent se)
            {
                RuleEvenPlus rep = new RuleEvenPlus();

                rep.Desc = se.Description;
                rep.Guid = se.EventGuid;
                rep.Name = se.Name;

                if (se.SecurityActions.Count > 0)
                {
                    rep.Actions = new List <RuleActionPlus>();

                    foreach (SecurityAction sa in se.SecurityActions)
                    {
                        rep.Actions.Add(FromSecurityAction(sa));
                    }
                }

                return(rep);
            }
예제 #28
0
        /// <summary>
        /// Performs the actual logging of a security event
        /// </summary>
        /// <param name="projectName">The name of the project.</param>
        /// <param name="userName">The name of the user.</param>
        /// <param name="eventType">The type of event.</param>
        /// <param name="eventRight">The right of the event.</param>
        /// <param name="message">Any security message.</param>
        protected override void DoLogEvent(string projectName, string userName, SecurityEvent eventType, SecurityRight eventRight, string message)
        {
            // Generate the log entry
            XmlDocument auditXml = new XmlDocument();
            XmlElement xmlRoot = auditXml.CreateElement("event");
            auditXml.AppendChild(xmlRoot);
            AddXmlElement(auditXml, xmlRoot, "dateTime", DateTime.Now.ToString("o", CultureInfo.CurrentCulture));
            if (!string.IsNullOrEmpty(projectName)) AddXmlElement(auditXml, xmlRoot, "project", projectName);
            if (!string.IsNullOrEmpty(userName)) AddXmlElement(auditXml, xmlRoot, "user", userName);
            AddXmlElement(auditXml, xmlRoot, "type", eventType.ToString());
            if (eventRight != SecurityRight.Inherit) AddXmlElement(auditXml, xmlRoot, "outcome", eventRight.ToString());
            if (!string.IsNullOrEmpty(message)) AddXmlElement(auditXml, xmlRoot, "message", message);

            // Write the entry
			string auditLog = executionEnvironment.EnsurePathIsRooted(this.auditFile);
            lock (this)
            {
                File.AppendAllText(auditLog, auditXml.OuterXml.Replace(Environment.NewLine, " ") + Environment.NewLine);
            }
        }
        public RawSecurityDescriptor ShowDialog(IntPtr hWnd, SecurityPageType pageType = SecurityPageType.BasicPermissions, SecurityPageActivation pageAct = SecurityPageActivation.ShowDefault)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("ShowDialog: {0} {1}", pageType, pageAct));
            SecurityEventArg sd = null;
            SecurityEvent fn = delegate(SecurityEventArg e) { sd = e; };

            try
            {
                OnSetSecurity += fn;
                if (System.Environment.OSVersion.Version.Major == 5 || (pageType == SecurityPageType.BasicPermissions && pageAct == SecurityPageActivation.ShowDefault))
                {
                    if (!NativeMethods.EditSecurity(hWnd, this))
                    {
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    }
                }
                else
                {
                    uint uPage = (uint)pageType & ((uint)pageAct << 16);
                    NativeMethods.EditSecurityAdvanced(hWnd, this, uPage);
                }
                if (sd != null)
                {
                    string sddl = NativeMethods.SecurityDescriptorPtrToSDLL(sd.SecurityDesciptor, sd.Parts);
                    if (!string.IsNullOrEmpty(sddl))
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("ShowDialog: Return: {0}", sddl));
                        return(new RawSecurityDescriptor(sddl));
                    }
                }
            }
            finally
            {
                OnSetSecurity -= fn;
            }
            System.Diagnostics.Debug.WriteLine(string.Format("ShowDialog: Return: null"));
            return(null);
        }
예제 #30
0
        internal async Task <ObservableCollection <SecurityEvent> > GetLastEventsFor(string homeId, string personId)
        {
            ObservableCollection <SecurityEvent> events = new ObservableCollection <SecurityEvent>();

            foreach (Home home in Homes)
            {
                if (home.Id == homeId)
                {
                    NextEvents nextEvents = await _aPICommands.GetLastEventOf(homeId, personId).ConfigureAwait(false);

                    if (nextEvents != null)
                    {
                        foreach (HomeData.Event rawEvent in nextEvents.Body.Events)
                        {
                            SecurityEvent newEvent = Home.CreateNewSecurityEvent(rawEvent);
                            events.Add(newEvent);
                        }
                        return(events);
                    }
                }
            }
            return(events);
        }
예제 #31
0
        public void GetSecurities()
        {
            SendLogMessage("Securities downloading...", LogMessageType.System);

            string requestString =
                "http://mfd.ru/export/";

            string response = GetRequest(requestString);

            string[] lines = response.Split('\n');

            List <string> classes = GetClasses(lines);

            List <Security> securities = new List <Security>();

            for (int i = 0; i < classes.Count; i++)
            {
                securities.AddRange(GetAllSecuritiesToClass(classes[i]));
            }

            SecurityEvent?.Invoke(securities);

            SendLogMessage("Securities downloaded. Count: " + securities.Count, LogMessageType.System);
        }
예제 #32
0
        /// <summary>
        /// получены инструменты с сервера
        /// </summary>
        /// <param name="products"></param>
        private void ClientReceivedSecurities(List <Product> products)
        {
            List <Security> securities = new List <Security>();

            foreach (var product in products)
            {
                var newSec = new Security();

                newSec.Name          = product.baseAsset + "-" + product.quoteAsset;
                newSec.NameClass     = product.quoteAsset;
                newSec.NameFull      = product.symbol;
                newSec.NameId        = product.symbol;
                newSec.Decimals      = product.priceScale;
                newSec.SecurityType  = SecurityType.CurrencyPair;
                newSec.State         = product.status == "Normal" ? SecurityStateType.Activ : SecurityStateType.Close;
                newSec.Lot           = GetValueByDecimals(product.qtyScale);
                newSec.PriceStep     = GetValueByDecimals(product.priceScale);
                newSec.PriceStepCost = newSec.PriceStep;

                securities.Add(newSec);
            }

            SecurityEvent?.Invoke(securities);
        }
 /// <summary>
 /// Starts a new filter with the event type and inner filter.
 /// </summary>
 /// <param name="eventType"></param>
 /// <param name="innerFilter"></param>
 public EventTypeAuditFilter(SecurityEvent eventType, AuditFilterBase innerFilter)
     : base(innerFilter)
 {
     this.type = eventType;
 }
예제 #34
0
 /// <summary>
 /// Performs the actual logging of a security event
 /// </summary>
 /// <param name="projectName">The name of the project.</param>
 /// <param name="userName">The name of the user.</param>
 /// <param name="eventType">The type of event.</param>
 /// <param name="eventRight">The right of the event.</param>
 /// <param name="message">Any security message.</param>
 protected abstract void DoLogEvent(string projectName, string userName, SecurityEvent eventType, SecurityRight eventRight, string message);
 /// <summary>
 /// Filters by event type.
 /// </summary>
 /// <param name="eventType"></param>
 /// <returns></returns>
 public virtual AuditFilterBase ByEventType(SecurityEvent eventType)
 {
     return new EventTypeAuditFilter(eventType, this);
 }
예제 #36
0
 /// <summary>
 /// Filters by event type.
 /// </summary>
 /// <param name="eventType"></param>
 /// <returns></returns>
 public static AuditFilterBase ByEventType(SecurityEvent eventType)
 {
     return new EventTypeAuditFilter(eventType);
 }
예제 #37
0
        /// <summary>
        /// Checks to see if a session has the required right to perform a permission.
        /// </summary>
        /// <param name="sessionToken">The session to check.</param>
        /// <param name="projectName">The project the permission is for.</param>
        /// <param name="permission">The permission being checked.</param>
        /// <param name="eventType">The event type for logging.</param>
        private void CheckSecurity(string sessionToken,
            string projectName,
            SecurityPermission permission,
            SecurityEvent? eventType)
        {
            // NASTY HACK: Bypass all security if the session override is being used
            if (sessionToken == SecurityOverride.SessionIdentifier)
            {
                return;
            }

            // Retrieve the project authorisation
            IProjectAuthorisation authorisation = null;
            bool requiresSession = securityManager.RequiresSession;
            string userName = securityManager.GetUserName(sessionToken);
            string displayName = securityManager.GetDisplayName(sessionToken, null) ?? userName;
            if (!string.IsNullOrEmpty(projectName))
            {
                IProjectIntegrator projectIntegrator = GetIntegrator(projectName);
                if ((projectIntegrator != null) &&
                    (projectIntegrator.Project != null) &&
                    (projectIntegrator.Project.Security != null))
                {
                    // The project has been found and it has security
                    authorisation = projectIntegrator.Project.Security;
                    requiresSession = authorisation.RequiresSession(securityManager);
                    // if "Guest" have some rights, the service must be able to check the
                    // rights for "Guest", but without userName it wont work.
                    if (string.IsNullOrEmpty(userName))
                        userName = authorisation.GuestAccountName;
                }
                else if ((projectIntegrator != null) &&
                    (projectIntegrator.Project != null) &&
                    (projectIntegrator.Project.Security == null))
                {
                    // The project is found, but security is missing - application error
                    string errorMessage = string.Format(CultureInfo.CurrentCulture, "Security not found for project {0}", projectName);
                    Log.Error(errorMessage);
                    if (eventType.HasValue)
                    {
                        securityManager.LogEvent(projectName,
                            userName,
                            eventType.Value,
                            SecurityRight.Deny,
                            errorMessage);
                    }
                    throw new SecurityException(errorMessage);
                }
                else
                {
                    // Couldn't find the requested project
                    string errorMessage = string.Format(CultureInfo.CurrentCulture, "project not found {0}", projectName);
                    Log.Error(errorMessage);
                    if (eventType.HasValue)
                    {
                        securityManager.LogEvent(projectName,
                            userName,
                            eventType.Value,
                            SecurityRight.Deny,
                            errorMessage);
                    }
                    throw new NoSuchProjectException(projectName);
                }
            }

            if (!requiresSession || (userName != null))
            {
                if (string.IsNullOrEmpty(projectName))
                {
                    // Checking server-level security
                    if (!securityManager.CheckServerPermission(userName, permission))
                    {
                        string info = string.Format(CultureInfo.CurrentCulture, "{2} [{0}] has been denied {1} permission at the server",
                            userName, permission, displayName);
                        Log.Warning(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Deny,
                                info);
                        }
                        throw new PermissionDeniedException(permission.ToString());
                    }
                    else
                    {
                        string info = string.Format(CultureInfo.CurrentCulture, "{2} [{0}] has been granted {1} permission at the server",
                            userName, permission, displayName);
                        Log.Debug(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Allow,
                                info);
                        }
                        return;
                    }
                }
                else
                {
                    // Checking project-level security
                    if (!authorisation.CheckPermission(securityManager,
                        userName,
                        permission,
                        securityManager.GetDefaultRight(permission)))
                    {
                        string info = string.Format(CultureInfo.CurrentCulture, "{3} [{0}] has been denied {1} permission on '{2}'",
                            userName, permission, projectName, displayName);
                        Log.Warning(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Deny,
                                info);
                        }
                        throw new PermissionDeniedException(permission.ToString());
                    }
                    else
                    {
                        Log.Debug(string.Format(CultureInfo.CurrentCulture, "{3} [{0}] has been granted {1} permission on '{2}'",
                            userName,
                            permission,
                            projectName,
                            displayName));
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Allow,
                                null);
                        }
                        return;
                    }
                }
            }
            else
            {
                SecurityRight defaultRight = securityManager.GetDefaultRight(permission);
                switch (defaultRight)
                {
                    case SecurityRight.Allow:
                        Log.Debug(string.Format(CultureInfo.CurrentCulture, "{3} [{0}] has been granted {1} permission on '{2}'",
                            userName,
                            permission,
                            projectName,
                            displayName));
                        return;
                    default:
                        // Tell the user that the session is unknown
                        var info = string.Format(CultureInfo.CurrentCulture, "Session with token '{0}' is not valid", sessionToken);
                        Log.Warning(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                null,
                                eventType.Value,
                                SecurityRight.Deny,
                                info);
                        }
                        throw new SessionInvalidException();
                }
            }
        }
예제 #38
0
        /// <summary>
        /// Encapsulates the code to process a request.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="permission"></param>
        /// <param name="eventType"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private Response RunServerRequest(ServerRequest request,
            SecurityPermission? permission,
            SecurityEvent? eventType,
            Action<ServerRequest> action)
        {
            Response response = new Response(request);
            try
            {
                // Validate the request and check the security token
                ValidateRequest(request);
                if (permission.HasValue)
                {
                    CheckSecurity(request.SessionToken,
                        null,
                        permission.Value,
                        eventType);
                }

                // Perform the actual action
                action(request);
                response.Result = ResponseResult.Success;
            }
            catch (Exception error)
            {
                // Security exceptions have already been logged, just need to log any other exception
                if (!(error is SecurityException))
                {
                    Log.Warning(error);
                }

                // Tell the caller the request failed and include the error message (but not the stack trace!)
                response.Result = ResponseResult.Failure;
                response.ErrorMessages.Add(
                    new ErrorMessage(
                        error.Message,
                        error.GetType().Name));
            }
            return response;
        }
예제 #39
0
        /// <summary>
        /// Encapsulates the code to process a request.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="permission"></param>
        /// <param name="eventType"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private Response RunProjectRequest(ProjectRequest request,
            SecurityPermission? permission,
            SecurityEvent? eventType,
            ProjectRequestAction action)
        {
            var response = new Response(request);
            try
            {
                // Validate the request and check the security token
                ValidateRequest(request);
                if (permission.HasValue)
                {
                    CheckSecurity(request.SessionToken,
                        request.ProjectName,
                        permission.Value,
                        eventType);
                }

                // Perform the actual action
                action(request, response);
                if (response.Result == ResponseResult.Unknown)
                {
                    response.Result = ResponseResult.Success;
                }
            }
            catch (Exception error)
            {
                // Log any errors to help diagnosing issues
                Log.Warning(error);
                response.Result = ResponseResult.Failure;
                response.ErrorMessages.Add(
                    new ErrorMessage(
                        error.Message,
                        error.GetType().Name));
            }
            return response;
        }
 /// <summary>
 /// Starts a new filter with the event type.
 /// </summary>
 /// <param name="eventType"></param>
 public EventTypeAuditFilter(SecurityEvent eventType)
     : this(eventType, null) { }
예제 #41
0
        /// <summary>
        /// Checks to see if a session has the required right to perform a permission.
        /// </summary>
        /// <param name="sessionToken">The session to check.</param>
        /// <param name="projectName">The project the permission is for.</param>
        /// <param name="permission">The permission being checked.</param>
        /// <param name="eventType">The event type for logging.</param>
        /// <returns>The display name of the user if the permission is allowed.</returns>
        private string CheckSecurity(string sessionToken,
            string projectName,
            SecurityPermission permission,
            SecurityEvent? eventType)
        {
            // Retrieve the project authorisation
            IProjectAuthorisation authorisation = null;
            bool requiresSession = securityManager.RequiresSession;
            string userName = securityManager.GetUserName(sessionToken);
            string displayName = securityManager.GetDisplayName(sessionToken, null) ?? userName;
            if (!string.IsNullOrEmpty(projectName))
            {
                IProjectIntegrator projectIntegrator = GetIntegrator(projectName);
                if ((projectIntegrator != null) &&
                    (projectIntegrator.Project != null) &&
                    (projectIntegrator.Project.Security != null))
                {
                    // The project has been found and it has security
                    authorisation = projectIntegrator.Project.Security;
                    requiresSession = authorisation.RequiresSession(securityManager);
                }
                else if ((projectIntegrator != null) &&
                    (projectIntegrator.Project != null) &&
                    (projectIntegrator.Project.Security == null))
                {
                    // The project is found, but security is missing - application error
                    string errorMessage = string.Format("Security not found for project {0}", projectName);
                    Log.Error(errorMessage);
                    if (eventType.HasValue)
                    {
                        securityManager.LogEvent(projectName,
                            userName,
                            eventType.Value,
                            SecurityRight.Deny,
                            errorMessage);
                    }
                    throw new SecurityException(errorMessage);
                }
                else
                {
                    // Couldn't find the requested project
                    string errorMessage = string.Format("project not found {0}", projectName);
                    Log.Error(errorMessage);
                    if (eventType.HasValue)
                    {
                        securityManager.LogEvent(projectName,
                            userName,
                            eventType.Value,
                            SecurityRight.Deny,
                            errorMessage);
                    }
                    throw new NoSuchProjectException(projectName);
                }
            }

            if (!requiresSession || (userName != null))
            {
                if (string.IsNullOrEmpty(projectName))
                {
                    // Checking server-level security
                    if (!securityManager.CheckServerPermission(userName, permission))
                    {
                        string info = string.Format("{2} [{0}] has been denied {1} permission at the server",
                            userName, permission, displayName);
                        Log.Warning(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Deny,
                                info);
                        }
                        throw new PermissionDeniedException(permission.ToString());
                    }
                    else
                    {
                        string info = string.Format("{2} [{0}] has been granted {1} permission at the server",
                            userName, permission, displayName);
                        Log.Debug(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Allow,
                                info);
                        }
                        return displayName;
                    }
                }
                else
                {
                    // Checking project-level security
                    if (!authorisation.CheckPermission(securityManager,
                        userName,
                        permission,
                        securityManager.GetDefaultRight(permission)))
                    {
                        string info = string.Format("{3} [{0}] has been denied {1} permission on '{2}'",
                            userName, permission, projectName, displayName);
                        Log.Warning(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Deny,
                                info);
                        }
                        throw new PermissionDeniedException(permission.ToString());
                    }
                    else
                    {
                        Log.Debug(string.Format("{3} [{0}] has been granted {1} permission on '{2}'",
                            userName,
                            permission,
                            projectName,
                            displayName));
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                userName,
                                eventType.Value,
                                SecurityRight.Allow,
                                null);
                        }
                        return displayName;
                    }
                }
            }
            else
            {
                SecurityRight defaultRight = securityManager.GetDefaultRight(permission);
                switch (defaultRight)
                {
                    case SecurityRight.Allow:
                        Log.Debug(string.Format("{3} [{0}] has been granted {1} permission on '{2}'",
                            userName,
                            permission,
                            projectName,
                            displayName));
                        return string.Empty;
                    default:
                        // Tell the user that the session is unknown
                        var info = string.Format("Session with token '{0}' is not valid", sessionToken);
                        Log.Warning(info);
                        if (eventType.HasValue)
                        {
                            securityManager.LogEvent(projectName,
                                null,
                                eventType.Value,
                                SecurityRight.Deny,
                                info);
                        }
                        throw new SessionInvalidException();
                }
            }
        }