public object DoWork(object state)
        {
            EntityQuery2 q = new EntityQuery2(Notification.ENTITY);
            q.WhereIs("Method", ReplyMethods.ByEmail);
            q.WhereIs("EmailSent", false);
            q.WhereLessThen("EmailRetries", 6);
            q.Paging = new Paging(1, 5);
            q.Include(User.ENTITY, Roles.Recipient);
            q.Include(File.ENTITY, Roles.Attachment);
            q.AllProperties = true;
            var pending = _repository.Search(q).Select(e => new Notification(e));
            foreach (var notif in pending)
            {
                try
                {
                    _notificationService.SendEmail(notif.Recipient.Email, notif.Subject, notif.Body, notif.Attachments);
                }
                catch (Exception)
                {
                    _repository.Update(new Notification(notif.Id) { EmailRetries = notif.EmailRetries + 1 });
                    continue;
                }
                var upd = new Notification(notif.Id) { EmailSent = true };
                _repository.Update(upd);
            }

            return state;
        }
Exemplo n.º 2
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity(Notification.ENTITY))
            {
                var relToSender = query.GetRelatedQuery(User.ENTITY, Roles.Sender);
                if (relToSender != null)
                {
                    var id = relToSender.GetSingleId();
                    if (id.HasValue && id.Value == _securityService.CurrentUser.Id)
                    {
                        return(InspectionResult.Allow);
                    }
                }
                var relToRecipient = query.GetRelatedQuery(User.ENTITY, Roles.Recipient);
                if (relToRecipient != null)
                {
                    var id = relToRecipient.GetSingleId();
                    if (id.HasValue && id.Value == _securityService.CurrentUser.Id)
                    {
                        return(InspectionResult.Allow);
                    }
                }

                if (relToRecipient == null)
                {
                    query.Include(User.ENTITY, Roles.Recipient);
                }
                if (relToSender != null)
                {
                    query.Include(User.ENTITY, Roles.Sender);
                }
            }

            return(InspectionResult.None);
        }
Exemplo n.º 3
0
        private void SendIssueToSubscribers(EntityUpdate update)
        {
            var issueQuery = new EntityQuery2(EntityConsts.Issue, update.Id.Value);

            issueQuery.AllProperties = true;
            issueQuery.Include(EntityConsts.Magazine, Roles.Issue);
            issueQuery.Include(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content);
            var issue            = _repository.Read(issueQuery);
            var magazine         = issue.GetSingleRelation(EntityConsts.Magazine, Roles.Issue).Entity;
            var subscribersQuery = new EntityQuery2(User.ENTITY);
            var relQuery         = new RelationQuery(EntityConsts.Magazine, Roles.Subscriber, magazine.Id);

            relQuery.RelationRules.Add(new Condition("IsActive", Condition.Is, true));
            subscribersQuery.WhereRelated(relQuery);
            subscribersQuery.AllProperties = true;
            var subscribers = _repository.Search(subscribersQuery).Select(e => new User(e));

            var contents = issue.GetManyRelations(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content).Select(r => new File(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.NEW_ISSUE));

            string subject = null, body = null;
            Dictionary <string, Entity> templateContext = new Dictionary <string, Entity>(StringComparer.InvariantCultureIgnoreCase);

            templateContext.Add("Magazine", magazine);
            templateContext.Add("Issue", issue);

            _templateService.Render(template, templateContext, out subject, out body);


            _notificationService.SendNotification(true, subscribers, subject, body, contents, new Relation[] { new Relation(Notification.ROLE, issue) });
        }
Exemplo n.º 4
0
        public void Before(Core.Services.tmp.EntityOperation operation, EntityOperationContext context)
        {
            if (operation.IsEntity(EntityConsts.BibliographicListQuery))
            {
                if (operation is EntityUpdate)
                {
                    var update = operation as EntityUpdate;
                    if (update.IsCreate() && _securityService.CurrentUser.UserType == UserTypes.Customer)
                    {
                        update.Attach(User.ENTITY, Roles.Customer, _securityService.CurrentUser.Id);
                    }
                    else if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                    {
                        bool attach = false;
                        int? fileId = null;
                        if (update.IsCreate())
                        {
                            attach = true;
                        }
                        else
                        {
                            var q = new EntityQuery2(EntityConsts.BibliographicListQuery, update.Id.Value);
                            q.Include(User.ENTITY, Roles.ProcessedBy);
                            q.Include(File.ENTITY, Roles.File);
                            var e    = _repository.Read(q);
                            var user = e.GetSingleRelation(User.ENTITY, Roles.ProcessedBy);
                            if (user == null)
                            {
                                attach = true;
                            }
                            else if (user.Entity.Id != _securityService.CurrentUser.Id)
                            {
                                update.Detach(User.ENTITY, Roles.ProcessedBy, user.Id);
                                attach = true;
                            }

                            var file = e.GetSingleRelation(File.ENTITY, Roles.File);
                            if (file != null)
                            {
                                fileId = file.Entity.Id;
                            }
                        }

                        if (attach)
                        {
                            update.Attach(User.ENTITY, Roles.ProcessedBy, _securityService.CurrentUser.Id);
                            if (fileId.HasValue)
                            {
                                var librarian = _securityService.CurrentUser;
                                using (_securityService.BeginSystemContext())
                                {
                                    _fileService.GrantAccess(fileId.Value, FileAccessType.Full, librarian);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        public void After(Core.Services.tmp.EntityOperation operation, EntityOperationContext context, EntityOperationResult result)
        {
            if (!result.Success)
            {
                return;
            }

            var update = operation as EntityUpdate;

            if (operation.IsEntity(EntityConsts.BibliographicListQuery) && update != null && update.ContainsProperty("Status") && update.Get <QueryStatus>("Status") == QueryStatus.Completed)
            {
                var q = new EntityQuery2(EntityConsts.BibliographicListQuery, update.Id.Value)
                {
                    AllProperties = true
                };
                q.Include(User.ENTITY, Roles.Customer);
                var    biblListQuery = _repository.Read(q);
                var    user = new User(biblListQuery.GetSingleRelation(User.ENTITY, Roles.Customer).Entity);
                var    template = _templateService.Get(new Guid(NotificationTemplates.QUERY_COMPLETED));
                string subject = null, body = null;
                Dictionary <string, Entity> templateContext = new Dictionary <string, Entity>(StringComparer.InvariantCultureIgnoreCase);
                templateContext.Add("Customer", user);
                templateContext.Add("Query", biblListQuery);

                _templateService.Render(template, templateContext, out subject, out body);
                var withEmail = biblListQuery.GetData <ReplyMethods>("ReplyMethod") == ReplyMethods.ByEmail;
                _notificationService.SendNotification(withEmail, new User[] { user }, subject, body, null, new Relation[] { new Relation(Notification.ROLE, biblListQuery) });
            }
            else if (operation.IsEntity(Payment.ENTITY) && update != null && update.ContainsProperty("Status") && update.Get <PaymentStatus>("Status") == PaymentStatus.Paid)
            {
                var q = new EntityQuery2(EntityConsts.BibliographicListQuery);
                q.AddProperties("Number");
                q.WhereRelated(new RelationQuery(Payment.ENTITY, Roles.Payment, update.Id.Value));
                q.Include(User.ENTITY, Roles.Customer);
                q.Include(File.ENTITY, Roles.File);
                var biblListQuery = _repository.Read(q);
                if (biblListQuery != null)
                {
                    var file = new File(biblListQuery.GetSingleRelation(File.ENTITY, Roles.File).Entity);
                    var user = new User(biblListQuery.GetSingleRelation(User.ENTITY, Roles.Customer).Entity);

                    var template = _templateService.Get(new Guid(NotificationTemplates.PAYMENT_COMPLETED));

                    string subject = null, body = null;
                    Dictionary <string, Entity> templateContext = new Dictionary <string, Entity>(StringComparer.InvariantCultureIgnoreCase);
                    templateContext.Add("Customer", user);
                    templateContext.Add("Query", biblListQuery);

                    _templateService.Render(template, templateContext, out subject, out body);

                    var withEmail = biblListQuery.GetData <ReplyMethods>("ReplyMethod") == ReplyMethods.ByEmail;
                    _notificationService.SendNotification(withEmail, new User[] { user }, subject, body, new File[] { file }, new Relation[] { new Relation(Notification.ROLE, biblListQuery) });
                    //_fileService.GrantAccess(file.Id, FileAccessType.Read, new User(biblQuery.GetSingleRelation(User.ENTITY, Roles.Customer).Entity));
                }
            }
        }
Exemplo n.º 6
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity("Arguments") && _securityService.HasModulePermission(_securityService.CurrentUser, BiblRefModule.Id, Permissions.Use))
            {
                return(InspectionResult.Allow);
            }
            if (query.IsForEntity(EntityConsts.BibliographicDocument) ||
                query.IsForEntity(EntityConsts.BibliographicQuery) ||
                query.IsForEntity(EntityConsts.Bibliography) ||
                query.IsForEntity(EntityConsts.Language))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, BiblRefModule.Id, Permissions.Use))
                {
                    if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                    {
                        return(InspectionResult.Allow);
                    }
                    else if (_securityService.CurrentUser.UserType == UserTypes.Customer && query.IsForEntity(EntityConsts.BibliographicQuery))
                    {
                        var relToMe = query.GetRelatedQuery(User.ENTITY, Roles.Customer);
                        if (relToMe != null && relToMe.GetSingleId().HasValue&& relToMe.GetSingleId().Value == _securityService.CurrentUser.Id)
                        {
                            return(InspectionResult.Allow);
                        }
                        else if (!query.HasInclude(User.ENTITY, Roles.Customer))
                        {
                            query.Include(User.ENTITY, Roles.Customer);
                        }
                    }
                    else
                    {
                        return(InspectionResult.Allow);
                    }
                }
            }
            else if (query.IsForEntity(Payment.ENTITY) &&
                     _securityService.CurrentUser.UserType == UserTypes.Librarian &&
                     _securityService.HasModulePermission(_securityService.CurrentUser, BiblRefModule.Id, Permissions.Use))
            {
                if (query.GetRelatedQuery(EntityConsts.BibliographicQuery, Roles.Payment) != null)
                {
                    return(InspectionResult.Allow);
                }
                else if (!query.HasInclude(EntityConsts.BibliographicQuery, Roles.Payment))
                {
                    query.Include(EntityConsts.BibliographicQuery, Roles.Payment);
                }
            }

            return(InspectionResult.None);
        }
Exemplo n.º 7
0
        public InspectionResult Inspect(EntityOperation operation)
        {
            if (operation.IsEntity(Notification.ENTITY) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsCreate())
                {
                    return(InspectionResult.Allow);
                }
                else if (update.PropertyUpdates.Count == 1 && (update.ContainsProperty("Received") || update.ContainsProperty("Archived")))
                {
                    EntityQuery2 q = new EntityQuery2(Notification.ENTITY, update.Id.Value);
                    q.Include(User.ENTITY, Roles.Recipient);
                    var recipient = _repository.Read(q).GetSingleRelation(User.ENTITY, Roles.Recipient);
                    if (recipient != null && recipient.Entity.Id == _securityService.CurrentUser.Id)
                    {
                        return(InspectionResult.Allow);
                    }
                }
                else if (update.PropertyUpdates.Count == 1 && update.ContainsProperty("ArchivedSent"))
                {
                    EntityQuery2 q = new EntityQuery2(Notification.ENTITY, update.Id.Value);
                    q.Include(User.ENTITY, Roles.Sender);
                    var sender = _repository.Read(q).GetSingleRelation(User.ENTITY, Roles.Sender);
                    if (sender != null && sender.Entity.Id == _securityService.CurrentUser.Id)
                    {
                        return(InspectionResult.Allow);
                    }
                }
            }

            return(InspectionResult.None);
        }
Exemplo n.º 8
0
        private User GetCurrentUser(string email)
        {
            EntityQuery2 query = new EntityQuery2(User.ENTITY);

            query.AllProperties = true;
            query.Include(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE);
            query.WhereIs("email", email);
            var e = _repository.Read(query);

            if (e == null)
            {
                return(null);
            }
            var user = new User(e);

            if (user.UserGroup != null)
            {
                var q2 = new EntityQuery2(UserGroup.ENTITY, user.UserGroup.Id);
                q2.AllProperties = true;
                q2.Include(ModulePermission.ENTITY, ModulePermission.DEFAULT_ROLE);
                user.UserGroup = new UserGroup(_repository.Read(q2));
            }

            return(user);
        }
Exemplo n.º 9
0
        public void GrantAccess(int fileId, FileAccessType accessType, User toUser, DateTime?expires = null, Guid?token = null)
        {
            var access = new FileAccess()
            {
                Type = accessType,
                User = toUser
            };

            if (expires.HasValue)
            {
                access.Expire = expires.Value;
            }
            if (token.HasValue)
            {
                access.Token = token.Value;
            }

            var q = new EntityQuery2(File.ENTITY, fileId);

            q.Include(User.ENTITY, Roles.Access);
            var file = new File(_repository.Read(q));

            if (_securityService.CurrentUser.UserType == UserTypes.Admin || HasAccessInternal(_securityService.CurrentUser, file.Access, FileAccessType.Owner, null) || HasAccessInternal(_securityService.CurrentUser, file.Access, FileAccessType.Full, null))
            {
                if (!HasAccessInternal(toUser, file.Access, token)) //TODO: FileService - upgrade access
                {
                    _repository.Attach(file, access);
                }
            }
            else
            {
                throw new UnauthorizedAccessException("You don't have permissions to grant/deny permissions on that file.");//TODO: UnauthorizedAccessException
            }
        }
Exemplo n.º 10
0
        public bool HasAccess(User user, int fileId, FileAccessType accessType, Guid?token = null)
        {
            if (user.UserType == UserTypes.Admin)
            {
                return(true);
            }
            else if (_securityService.HasModulePermission(user, FilesModule.Id, Permissions.ManageAll))
            {
                return(true);
            }

            var q = new EntityQuery2(File.ENTITY, fileId);

            q.Include(User.ENTITY, Roles.Access);
            var relQuery = new RelationQuery(User.ENTITY, Roles.Access, user.Id);

            relQuery.RelationRules.Add(new Condition("Type", Condition.Is, accessType));
            q.WhereRelated(relQuery);

            var e = _repository.Read(q);

            if (e == null)
            {
                return(false);
            }

            var file = new File(e);

            if (file.Access == null)
            {
                return(false);
            }

            return(HasAccessInternal(user, file.Access, token));
        }
Exemplo n.º 11
0
        public void Delete(Entity entity, bool recursive = false)
        {
            var em = _domainService.Domain.Entities[entity.Name];

            if (entity.Id <= 0)
            {
                throw new ArgumentException("entity.Id must be positive integer");
            }


            if (recursive)
            {
                EntityQuery2 getAllRels = new EntityQuery2(em.Name, entity.Id);
                foreach (var rel in em.Relations)
                {
                    getAllRels.Include(rel.GetOther(em.Name).Name, rel.Role);
                }
                var e = Read(getAllRels);
                foreach (var rel in em.Relations)
                {
                    var relType = rel.TypeFor(em.Name);
                    var other   = rel.GetOther(em.Name);
                    if (relType == RelationType.OneToOne || relType == RelationType.ManyToOne)
                    {
                        var item = e.GetSingleRelation(other.Name, rel.Role);
                        if (item != null)
                        {
                            Detach(e, item);
                        }
                    }
                    else
                    {
                        var items = e.GetManyRelations(other.Name, rel.Role);
                        foreach (var item in items)
                        {
                            Detach(e, item);
                        }
                    }
                }
            }
            using (var ctx = _dbService.GetDatabaseContext(true))
            {
                SqlCommand cmd = new SqlCommand(string.Format("DELETE [{0}] WHERE ID = @Id", em.Name), ctx.Connection);
                cmd.Parameters.AddWithValue("Id", entity.Id);
                try
                {
                    cmd.ExecuteNonQuery();
                    ctx.Complete();
                }
                catch (SqlException sex)
                {
                    throw WrapSqlException(sex, em);
                }
            }
        }
Exemplo n.º 12
0
        public IDisposable BeginSystemContext()
        {
            EntityQuery2 query = new EntityQuery2(User.ENTITY);

            query.AllProperties = true;
            query.Include(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE);
            query.WhereIs("email", _systemUserEmail);
            var e = _repository.Read(query);

            return(new SystemSecurityContext(new User(e)));
        }
Exemplo n.º 13
0
        public LoginResult Login(string username, string password, bool persistent)
        {
            SHA1 sha1     = SHA1.Create();
            var  pwdBytes = Encoding.UTF8.GetBytes(password);
            var  hash     = Convert.ToBase64String(sha1.ComputeHash(pwdBytes));

            EntityQuery2 query = new EntityQuery2(User.ENTITY);

            query.AllProperties = true;
            query.Include(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE);
            query.WhereIs("email", username);
            //query.WhereIs("password", hash);
            var e = _repository.Read(query);

            if (e == null)
            {
                return(LoginResult.InvalidCredentials);
            }
            User user = new User(e);

            if (user.FailedLoginsCount.HasValue && user.FailedLoginsCount.Value > 3 && user.LastFailedLogin.HasValue && user.LastFailedLogin.Value.Add(TimeSpan.FromHours(4)) > DateTime.Now)
            {
                return(LoginResult.UserLocked);
            }

            if (!user.Password.Equals(hash, StringComparison.InvariantCultureIgnoreCase))
            {
                user.LastFailedLogin = DateTime.Now;
                if (user.FailedLoginsCount.HasValue)
                {
                    user.FailedLoginsCount = user.FailedLoginsCount.Value + 1;
                }
                else
                {
                    user.FailedLoginsCount = 1;
                }

                var upd = new User(user.Id);
                upd.FailedLoginsCount = user.FailedLoginsCount;
                upd.LastFailedLogin   = user.LastFailedLogin;
                _repository.Update(upd);
                return(LoginResult.InvalidCredentials);
            }

            if (!user.IsActive)
            {
                return(LoginResult.UserInactive);
            }


            System.Web.Security.FormsAuthentication.SetAuthCookie(user.Email, persistent);
            return(LoginResult.Success);
        }
Exemplo n.º 14
0
        public bool HasAccess(Domain.User user, int fileId, Guid?token = null)
        {
            if (user.UserType == UserTypes.Admin)
            {
                return(true);
            }

            var q = new EntityQuery2(File.ENTITY, fileId);

            q.Include(User.ENTITY, Roles.Access);
            var file = new File(_repository.Read(q));

            return(HasAccessInternal(user, file.Access, token));
        }
Exemplo n.º 15
0
        public object DoWork(object state)
        {
            EntityQuery2 q = new EntityQuery2(Notification.ENTITY);

            q.WhereIs("Method", ReplyMethods.ByEmail);
            q.WhereIs("EmailSent", false);
            q.WhereLessThen("EmailRetries", 6);
            q.Paging = new Paging(1, 5);
            q.Include(User.ENTITY, Roles.Recipient);
            q.Include(File.ENTITY, Roles.Attachment);
            q.AllProperties = true;
            var pending = _repository.Search(q).Select(e => new Notification(e));

            foreach (var notif in pending)
            {
                try
                {
                    _notificationService.SendEmail(notif.Recipient.Email, notif.Subject, notif.Body, notif.Attachments);
                }
                catch (Exception)
                {
                    _repository.Update(new Notification(notif.Id)
                    {
                        EmailRetries = notif.EmailRetries + 1
                    });
                    continue;
                }
                var upd = new Notification(notif.Id)
                {
                    EmailSent = true
                };
                _repository.Update(upd);
            }

            return(state);
        }
Exemplo n.º 16
0
        public System.IO.Stream GetFileContent(int fileId, Guid?token = null)
        {
            var q = new EntityQuery2(File.ENTITY, fileId);

            q.AddProperties("ContentPath");
            q.Include(User.ENTITY, Roles.Access);
            var file = new File(_repository.Read(q));

            if (HasAccessInternal(_securityService.CurrentUser, file.Access, token))
            {
                return(new System.IO.FileStream(System.IO.Path.Combine(_permPath, file.ContentPath), System.IO.FileMode.Open));
            }
            else
            {
                throw new UnauthorizedAccessException("You don't have permissions to access this file.");
            }
        }
Exemplo n.º 17
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity(Payment.ENTITY))
            {
                var cust = query.GetRelatedQuery(User.ENTITY, Payment.ROLE_CUSTOMER);
                if (cust != null && cust.GetSingleId().HasValue&& cust.GetSingleId().Value == _securityService.CurrentUser.Id)
                {
                    return(InspectionResult.Allow);
                }
                else if (!query.HasInclude(User.ENTITY, Payment.ROLE_CUSTOMER))
                {
                    query.Include(User.ENTITY, Payment.ROLE_CUSTOMER);
                }
            }

            return(InspectionResult.None);
        }
Exemplo n.º 18
0
 public InspectionResult InspectQuery(EntityQuery2 query)
 {
     if (query.IsForEntity("Arguments") && _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
     {
         return(InspectionResult.Allow);
     }
     else if (query.IsForEntity(Inquery.EntityType))
     {
         if (_securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
         {
             if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
             {
                 return(InspectionResult.Allow);
             }
             else if (_securityService.CurrentUser.UserType == UserTypes.Customer)
             {
                 var relTo = query.GetRelatedQuery(User.ENTITY, RelationConsts.Customer);
                 if (relTo != null && relTo.GetSingleId().HasValue&& relTo.GetSingleId().Value == _securityService.CurrentUser.Id)
                 {
                     return(InspectionResult.Allow);
                 }
                 else if (!query.HasInclude(User.ENTITY, RelationConsts.Customer))
                 {
                     query.Include(User.ENTITY, RelationConsts.Customer);
                 }
             }
         }
     }
     else if (query.IsForEntity(User.ENTITY))
     {
         if (_securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use) &&
             _securityService.CurrentUser.UserType == UserTypes.Librarian)
         {
             return(InspectionResult.Allow);
         }
     }
     else if (query.IsForEntity(Notification.ENTITY) &&
              _securityService.CurrentUser.UserType == UserTypes.Librarian &&
              _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use) &&
              query.GetRelatedQuery(Inquery.EntityType, RelationConsts.Inquery) != null)
     {
         return(InspectionResult.Allow);
     }
     return(InspectionResult.None);
 }
Exemplo n.º 19
0
        public InspectionResult Inspect(Core.Services.tmp.EntityOperation operation)
        {
            if ((operation.IsEntity(EntityConsts.BibliographicQuery) ||
                 operation.IsEntity(EntityConsts.Bibliography)) &&
                _securityService.HasModulePermission(_securityService.CurrentUser, BiblRefModule.Id, Permissions.Use))
            {
                if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                {
                    return(InspectionResult.Allow);
                }
                else if (operation is EntityUpdate)
                {
                    var update = operation as EntityUpdate;
                    if (update.IsCreate())
                    {
                        return(InspectionResult.Allow);
                    }
                    else if (update.IsEntity(EntityConsts.BibliographicQuery))
                    {
                        var q = new EntityQuery2(User.ENTITY, _securityService.CurrentUser.Id);
                        q.WhereRelated(new RelationQuery(EntityConsts.BibliographicQuery, Roles.Customer, update.Id.Value));
                        if (_repository.Read(q) != null)
                        {
                            return(InspectionResult.Allow);
                        }
                    }
                    else if (update.IsEntity(EntityConsts.Bibliography))
                    {
                        var q = new EntityQuery2(EntityConsts.BibliographicQuery);
                        q.WhereIs("ForNew", true);
                        q.WhereRelated(new RelationQuery(EntityConsts.Bibliography, Roles.Query, update.Id.Value));
                        q.WhereRelated(new RelationQuery(User.ENTITY, Roles.Customer, _securityService.CurrentUser.Id));
                        q.Include(EntityConsts.Bibliography, Roles.Query);

                        if (_repository.Read(q) != null)
                        {
                            return(InspectionResult.Allow);
                        }
                    }
                }
            }

            return(InspectionResult.None);
        }
Exemplo n.º 20
0
 public InspectionResult InspectQuery(EntityQuery2 query)
 {
     if (query.IsForEntity(EntityConsts.Magazine) ||
         query.IsForEntity(EntityConsts.Issue) ||
         query.IsForEntity(EntityConsts.MagazineCategory) ||
         (query.IsForEntity(User.ENTITY) && _securityService.CurrentUser.UserType == UserTypes.Librarian))
     {
         if (_securityService.HasModulePermission(_securityService.CurrentUser, MyMagazinesModule.Id, Permissions.Use))
         {
             return(InspectionResult.Allow);//TODO: MyMagazines inspect query
         }
     }
     else if (query.IsForEntity(Notification.ENTITY) &&
              _securityService.CurrentUser.UserType == UserTypes.Librarian &&
              _securityService.HasModulePermission(_securityService.CurrentUser, MyMagazinesModule.Id, Permissions.Use))
     {
         query.Include(EntityConsts.Issue, Notification.ROLE);
     }
     return(InspectionResult.None);
 }
Exemplo n.º 21
0
        private void SendMagazineNotActiveToSubscribers(EntityUpdate update)
        {
            var magazineQuery = new EntityQuery2(EntityConsts.Magazine, update.Id.Value);

            magazineQuery.AllProperties = true;
            magazineQuery.Include(User.ENTITY, Roles.Subscriber);

            var magazine = _repository.Read(magazineQuery);

            var subscribers = magazine.GetManyRelations(User.ENTITY, Roles.Subscriber).Select(r => new User(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.DEACTIVATED_MAGAZINE));

            string subject = null, body = null;
            Dictionary <string, Entity> templateContext = new Dictionary <string, Entity>(StringComparer.InvariantCultureIgnoreCase);

            templateContext.Add("Magazine", magazine);
            _templateService.Render(template, templateContext, out subject, out body);
            _notificationService.SendNotification(true, subscribers, subject, body, null, new Relation[] { new Relation(Notification.ROLE, magazine) });
        }
Exemplo n.º 22
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity("Arguments") && _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
                return InspectionResult.Allow;
            else if (query.IsForEntity(Inquery.EntityType))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
                {
                    if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                        return InspectionResult.Allow;
                    else if (_securityService.CurrentUser.UserType == UserTypes.Customer)
                    {
                        var relTo = query.GetRelatedQuery(User.ENTITY, RelationConsts.Customer);
                        if (relTo != null && relTo.GetSingleId().HasValue && relTo.GetSingleId().Value == _securityService.CurrentUser.Id)
                            return InspectionResult.Allow;
                        else if (!query.HasInclude(User.ENTITY, RelationConsts.Customer))
                            query.Include(User.ENTITY, RelationConsts.Customer);

                    }
                }
            }
            else if (query.IsForEntity(User.ENTITY))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use)
                    && _securityService.CurrentUser.UserType == UserTypes.Librarian)
                {
                    return InspectionResult.Allow;
                }
            }
            else if (query.IsForEntity(Notification.ENTITY)
                && _securityService.CurrentUser.UserType == UserTypes.Librarian
                && _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use)
                && query.GetRelatedQuery(Inquery.EntityType, RelationConsts.Inquery) != null)
            {
                return InspectionResult.Allow;
            }
            return InspectionResult.None;
        }
Exemplo n.º 23
0
        public InspectionResult Inspect(Core.Services.tmp.EntityOperation operation)
        {
            if ((operation.IsEntity(EntityConsts.BibliographicQuery)
                || operation.IsEntity(EntityConsts.Bibliography))
                && _securityService.HasModulePermission(_securityService.CurrentUser, BiblRefModule.Id, Permissions.Use))
            {
                if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                    return InspectionResult.Allow;
                else if (operation is EntityUpdate)
                {
                    var update = operation as EntityUpdate;
                    if (update.IsCreate())
                        return InspectionResult.Allow;
                    else if (update.IsEntity(EntityConsts.BibliographicQuery))
                    {
                        var q = new EntityQuery2(User.ENTITY, _securityService.CurrentUser.Id);
                        q.WhereRelated(new RelationQuery(EntityConsts.BibliographicQuery, Roles.Customer, update.Id.Value));
                        if (_repository.Read(q) != null)
                            return InspectionResult.Allow;
                    }
                    else if(update.IsEntity(EntityConsts.Bibliography))
                    {
                        var q = new EntityQuery2(EntityConsts.BibliographicQuery);
                        q.WhereIs("ForNew", true);
                        q.WhereRelated(new RelationQuery(EntityConsts.Bibliography, Roles.Query, update.Id.Value));
                        q.WhereRelated(new RelationQuery(User.ENTITY, Roles.Customer, _securityService.CurrentUser.Id));
                        q.Include(EntityConsts.Bibliography, Roles.Query);

                        if (_repository.Read(q) != null)
                            return InspectionResult.Allow;

                    }
                }
            }

            return InspectionResult.None;
        }
Exemplo n.º 24
0
 public IDisposable BeginSystemContext()
 {
     EntityQuery2 query = new EntityQuery2(User.ENTITY);
     query.AllProperties = true;
     query.Include(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE);
     query.WhereIs("email", _systemUserEmail);
     var e = _repository.Read(query);
     return new SystemSecurityContext(new User(e));
 }
Exemplo n.º 25
0
        private User GetCurrentUser(string email)
        {
            EntityQuery2 query = new EntityQuery2(User.ENTITY);
            query.AllProperties = true;
            query.Include(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE);
            query.WhereIs("email", email);
            var e = _repository.Read(query);
            if (e == null)
                return null;
            var user = new User(e);
            if (user.UserGroup != null)
            {
                var q2 = new EntityQuery2(UserGroup.ENTITY, user.UserGroup.Id);
                q2.AllProperties = true;
                q2.Include(ModulePermission.ENTITY, ModulePermission.DEFAULT_ROLE);
                user.UserGroup = new UserGroup(_repository.Read(q2));
            }

            return user;
        }
Exemplo n.º 26
0
        public void Test_EntityRepo_SearchRelated()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                #region prepare data
                var jordan = new Author()
                {
                    FirstName = "Robert",
                    LastName = "Jordan",
                    IsAlive = false,
                    Born = new DateTime(1948, 10, 17),
                    Rating = 10.0m
                };

                var feist = new Author()
                {
                    FirstName = "Raymond",
                    LastName = "Feist",
                    IsAlive = true,
                    Born = new DateTime(1963, 2, 14),
                    Rating = 6.7m
                };

                var fb1 = new Book()
                {
                    Title = "The Apprentice",
                    Price = 19.90m
                };

                var fb2 = new Book()
                {
                    Title = "The Magician",
                    Price = 17.10m
                };

                var jb1 = new Book()
                {
                    Title = "The Shadow is Rising",
                    Price = 21.15m
                };
                var jb2 = new Book()
                {
                    Title = "The Eye of the World",
                    Price = 25.80m
                };

                repository.Create(jordan);
                repository.Create(feist);
                repository.Create(fb1);
                repository.Create(fb2);
                repository.Create(jb1);
                repository.Create(jb2);
                repository.Attach(feist, new Relation("author", fb1));
                repository.Attach(feist, new Relation("author", fb2));
                repository.Attach(jordan, new Relation("author", jb1));
                repository.Attach(jordan, new Relation("author", jb2));
                #endregion

                EntityQuery2 query = new EntityQuery2("book");
                query.AllProperties = true;
                var fq = new RelationQuery("author", "author", feist.Id);
                query.RelatedTo.Add(fq);
                var res = repository.Search(query);
                Assert.AreEqual(2, res.Count());
                Assert.IsNotNull(res.First(b => b.GetData<string>("title") == fb1.Title));
                Assert.IsNotNull(res.First(b => b.GetData<string>("title") == fb2.Title));

                query.Include("author", "author");
                res = repository.Search(query);
                Assert.AreEqual(2, res.Count());
                Assert.IsNotNull(res.First(b => b.GetData<string>("title") == fb1.Title));
                Assert.IsNotNull(res.First(b => b.GetData<string>("title") == fb2.Title));
            }
        }
Exemplo n.º 27
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity(Notification.ENTITY))
            {
                var relToSender = query.GetRelatedQuery(User.ENTITY, Roles.Sender);
                if (relToSender != null)
                {
                    var id = relToSender.GetSingleId();
                    if (id.HasValue && id.Value == _securityService.CurrentUser.Id)
                        return InspectionResult.Allow;
                }
                var relToRecipient = query.GetRelatedQuery(User.ENTITY, Roles.Recipient);
                if (relToRecipient != null)
                {
                    var id = relToRecipient.GetSingleId();
                    if (id.HasValue && id.Value == _securityService.CurrentUser.Id)
                        return InspectionResult.Allow;
                }

                if (relToRecipient == null)
                {
                    query.Include(User.ENTITY, Roles.Recipient);
                }
                if (relToSender != null)
                {
                    query.Include(User.ENTITY, Roles.Sender);
                }
            }

            return InspectionResult.None;
        }
Exemplo n.º 28
0
        public void After(EntityOperation operation, EntityOperationContext context, EntityOperationResult result)
        {
            if (!result.Success)
            {
                return;
            }

            if (operation.IsEntity(EntityConsts.Issue) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (context.Get <bool>(CTXKEY_SEND_ISSUE))
                {
                    SendIssueToSubscribers(operation as EntityUpdate);
                }

                if (update.ContainsRelation(File.ENTITY, Roles.Content))
                {
                    var filesAttached = update.GetMultipleRelationUpdates(File.ENTITY, Roles.Content).Where(fu => fu.Operation == RelationOperation.Attach);
                    if (filesAttached.Count() > 0)
                    {
                        var issue = update.ToEntity();
                        var q     = new EntityQuery2(EntityConsts.Magazine);
                        q.WhereRelated(new RelationQuery(EntityConsts.Issue, Roles.Issue, issue.Id));
                        q.Include(User.ENTITY, Roles.Subscriber);
                        var mag         = _repository.Read(q);
                        var subscribers = mag.GetManyRelations(User.ENTITY, Roles.Subscriber).Select(r => new User(r.Entity));
                        foreach (var subscriber in subscribers)
                        {
                            foreach (var fileUpdate in filesAttached)
                            {
                                if (!_fileService.HasAccess(subscriber, fileUpdate.Id.Value))
                                {
                                    _fileService.GrantAccess(fileUpdate.Id.Value, FileAccessType.Read, subscriber);
                                }
                            }
                        }
                    }
                }
            }
            else if (operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsEntity(User.ENTITY) && update.ContainsRelation(EntityConsts.Magazine, Roles.Subscriber))
                {
                    var rus = update.GetMultipleRelationUpdates(EntityConsts.Magazine, Roles.Subscriber).Where(ru => ru.Operation == RelationOperation.Attach);
                    foreach (var ru in rus)
                    {
                        var q = new EntityQuery2(EntityConsts.Issue);
                        q.WhereRelated(new RelationQuery(EntityConsts.Magazine, Roles.Issue, ru.Id.Value));
                        q.Include(File.ENTITY, Roles.Content);
                        var issues = _repository.Search(q);
                        foreach (var issue in issues)
                        {
                            //The user cannot give himself an access to file - only owner or administrator can.
                            using (_securityService.BeginSystemContext())
                            {
                                GiveFileAccessForIssue(issue, new User(update.ToEntity()));
                            }
                        }
                    }
                }
                else if (update.IsEntity(EntityConsts.Magazine) && update.ContainsRelation(User.ENTITY, Roles.Subscriber))
                {
                    var rus = update.GetMultipleRelationUpdates(User.ENTITY, Roles.Subscriber).Where(ru => ru.Operation == RelationOperation.Attach);

                    if (rus.Count() > 0)
                    {
                        var q = new EntityQuery2(EntityConsts.Issue);
                        q.WhereRelated(new RelationQuery(EntityConsts.Magazine, Roles.Issue, update.Id.Value));
                        q.Include(File.ENTITY, Roles.Content);
                        var issues = _repository.Search(q);
                        foreach (var ru in rus)
                        {
                            foreach (var issue in issues)
                            {
                                GiveFileAccessForIssue(issue, new User(ru.Id.Value));
                            }
                        }
                    }
                }
                else if (update.IsEntity(EntityConsts.Magazine) && update.ContainsProperty("IsActive"))
                {
                    var isActiveNew = update.Get <bool>("IsActive");
                    if (isActiveNew == false && context.Get <bool>(CTXKEY_ISACTIVEOLD))
                    {
                        SendMagazineNotActiveToSubscribers(update);
                    }
                }
            }
        }
Exemplo n.º 29
0
        public void Before(Core.Services.tmp.EntityOperation operation, EntityOperationContext context)
        {
            if (operation.IsEntity(EntityConsts.BibliographicListQuery))
            {
                if (operation is EntityUpdate)
                {
                    var update = operation as EntityUpdate;
                    if (update.IsCreate() && _securityService.CurrentUser.UserType == UserTypes.Customer)
                        update.Attach(User.ENTITY, Roles.Customer, _securityService.CurrentUser.Id);
                    else if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                    {
                        bool attach = false;
                        int? fileId = null;
                        if (update.IsCreate())
                            attach = true;
                        else
                        {
                            var q = new EntityQuery2(EntityConsts.BibliographicListQuery, update.Id.Value);
                            q.Include(User.ENTITY, Roles.ProcessedBy);
                            q.Include(File.ENTITY, Roles.File);
                            var e = _repository.Read(q);
                            var user = e.GetSingleRelation(User.ENTITY, Roles.ProcessedBy);
                            if (user == null)
                                attach = true;
                            else if (user.Entity.Id != _securityService.CurrentUser.Id)
                            {
                                update.Detach(User.ENTITY, Roles.ProcessedBy, user.Id);
                                attach = true;
                            }

                            var file = e.GetSingleRelation(File.ENTITY, Roles.File);
                            if (file != null)
                                fileId = file.Entity.Id;
                        }

                        if (attach)
                        {
                            update.Attach(User.ENTITY, Roles.ProcessedBy, _securityService.CurrentUser.Id);
                            if (fileId.HasValue)
                            {
                                var librarian = _securityService.CurrentUser;
                                using (_securityService.BeginSystemContext())
                                {
                                    _fileService.GrantAccess(fileId.Value, FileAccessType.Full, librarian);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 30
0
        public bool HasAccess(Domain.User user, int fileId, Guid? token = null)
        {
            if (user.UserType == UserTypes.Admin)
                return true;

            var q = new EntityQuery2(File.ENTITY, fileId);
            q.Include(User.ENTITY, Roles.Access);
            var file = new File(_repository.Read(q));
            return HasAccessInternal(user, file.Access, token);
        }
Exemplo n.º 31
0
        public bool HasAccess(User user, int fileId, FileAccessType accessType, Guid? token = null)
        {
            if (user.UserType == UserTypes.Admin)
                return true;
            else if (_securityService.HasModulePermission(user, FilesModule.Id, Permissions.ManageAll))
                return true;

            var q = new EntityQuery2(File.ENTITY, fileId);
            q.Include(User.ENTITY, Roles.Access);
            var relQuery = new RelationQuery(User.ENTITY, Roles.Access, user.Id);
            relQuery.RelationRules.Add(new Condition("Type", Condition.Is, accessType));
            q.WhereRelated(relQuery);

            var e = _repository.Read(q);
            if (e == null)
                return false;

            var file = new File(e);
            if (file.Access == null)
                return false;

            return HasAccessInternal(user, file.Access, token);
        }
Exemplo n.º 32
0
 public System.IO.Stream GetFileContent(int fileId, Guid? token = null)
 {
     var q = new EntityQuery2(File.ENTITY, fileId);
     q.AddProperties("ContentPath");
     q.Include(User.ENTITY, Roles.Access);
     var file = new File(_repository.Read(q));
     if (HasAccessInternal(_securityService.CurrentUser, file.Access, token))
     {
         return new System.IO.FileStream(System.IO.Path.Combine(_permPath, file.ContentPath), System.IO.FileMode.Open);
     }
     else
         throw new UnauthorizedAccessException("You don't have permissions to access this file.");
 }
Exemplo n.º 33
0
        public void GrantAccess(int fileId, FileAccessType accessType, User toUser, DateTime? expires = null, Guid? token = null)
        {
            var access = new FileAccess()
            {
                Type = accessType,
                User = toUser
            };
            if (expires.HasValue)
                access.Expire = expires.Value;
            if (token.HasValue)
                access.Token = token.Value;

            var q = new EntityQuery2(File.ENTITY, fileId);
            q.Include(User.ENTITY, Roles.Access);
            var file = new File(_repository.Read(q));

            if (_securityService.CurrentUser.UserType == UserTypes.Admin || HasAccessInternal(_securityService.CurrentUser, file.Access, FileAccessType.Owner, null) || HasAccessInternal(_securityService.CurrentUser, file.Access, FileAccessType.Full, null))
            {
                if (!HasAccessInternal(toUser, file.Access, token)) //TODO: FileService - upgrade access
                    _repository.Attach(file, access);
            }
            else
                throw new UnauthorizedAccessException("You don't have permissions to grant/deny permissions on that file.");//TODO: UnauthorizedAccessException
        }
Exemplo n.º 34
0
        public void Test_EntityRepo_AttachDetach()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                #region prepare data
                var jordan = new Author()
                {
                    FirstName = "Robert",
                    LastName = "Jordan",
                    IsAlive = false,
                    Born = new DateTime(1948, 10, 17),
                    Rating = 10.0m
                };

                var feist = new Author()
                {
                    FirstName = "Raymond",
                    LastName = "Feist",
                    IsAlive = true,
                    Born = new DateTime(1963, 2, 14),
                    Rating = 6.7m
                };

                var fb1 = new Book()
                {
                    Title = "The Apprentice",
                    Price = 19.90m
                };

                var fb2 = new Book()
                {
                    Title = "The Magician",
                    Price = 17.10m
                };

                repository.Create(jordan);
                repository.Create(feist);
                repository.Create(fb1);
                repository.Create(fb2);

                #endregion

                repository.Attach(feist, new Relation("author", fb1));
                var rel2 = new Relation("author", fb2);
                var writtenOn = new DateTime(1996, 4, 25);
                rel2.SetData<DateTime>("WrittenOn", writtenOn);
                repository.Attach(feist, rel2);

                var q = new EntityQuery2("author", feist.Id);
                q.AddProperties("FirstName", "lastname", "isalive", "born", "rating");
                q.Include("book", "author");
                var e = repository.Read(q);
                Assert.AreEqual(2, e.GetManyRelations("book", "author").Count());

                var bq = new EntityQuery2("book");
                bq.Include("author", "author");
                var bes = repository.Search(bq);
                foreach (var be in bes)
                {
                    Assert.AreEqual(1, be.RelationsData.Count);
                    Assert.AreEqual(feist.Id, be.GetSingleRelation("author", "author").Entity.Id);
                    if (be.Id == fb2.Id)
                        Assert.AreEqual(writtenOn, be.GetSingleRelation("author", "author").GetData<DateTime>("writtenon"));
                }

                repository.Detach(feist, new Relation("author", fb1));
                e = repository.Read(q);
                Assert.AreEqual(1, e.GetManyRelations("book", "author").Count());

                repository.Attach(fb1, new Relation("author", feist));
                e = repository.Read(q);
                Assert.AreEqual(2, e.GetManyRelations("book", "author").Count());
                repository.Detach(fb1, new Relation("author", feist));
                e = repository.Read(q);
                Assert.AreEqual(1, e.GetManyRelations("book", "author").Count());

                bool ex = false;
                try { repository.Attach(fb2, new Relation("author", jordan)); }
                catch (Exception) { ex = true; }
                Assert.IsTrue(ex, "Exception not thrown when attaching two authors to single book");
            }
        }
Exemplo n.º 35
0
        public void Test_EntityRepo_Create()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                #region prepare data
                var jordan = new Author()
                {
                    FirstName = "Robert",
                    LastName = "Jordan",
                    IsAlive = false,
                    Born = new DateTime(1948, 10, 17),
                    Rating = 10.0m
                };

                var feist = new Author()
                {
                    FirstName = "Raymond",
                    LastName = "Feist",
                    Born = new DateTime(1963, 2, 14),
                    Rating = 6.7m
                };

                var fb1 = new Book()
                {
                    Title = "The Apprentice",
                    Price = 19.90m
                };

                var fb2 = new Book()
                {
                    Title = "The Magician",
                    Price = 17.10m,
                    Genre = Genre.Fantasy
                };
                #endregion

                repository.Create(jordan);
                repository.Create(feist);
                repository.Create(fb1);
                repository.Create(fb2);
                repository.Attach(feist, new Relation("author", fb1));
                repository.Attach(feist, new Relation("author", fb2));
                fb1.Genre = Genre.Mistery; //default value
                feist.IsAlive = true;//default value

                var q = new EntityQuery2("author", feist.Id);
                q.AddProperties("FirstName", "lastname", "isalive", "born", "rating");
                q.Include("book", "author");
                var e = repository.Read(q);
                var created = new Author(e);
                Assert.AreEqual(feist.FirstName, created.FirstName);
                Assert.AreEqual(feist.LastName, created.LastName);
                Assert.AreEqual(feist.Born, created.Born);
                Assert.AreEqual(feist.IsAlive, created.IsAlive);
                Assert.AreEqual(feist.Rating, created.Rating);
                Assert.AreEqual(2, e.GetManyRelations("book", "author").Count());//repository.Detach(feist, new Relation("author", fb1));
                var eb1 = e.GetManyRelations("book", "author").First();
                Book b = new Book(eb1.Entity);
                Assert.AreEqual(fb1.Genre, b.Genre);
            }
        }
Exemplo n.º 36
0
        public void Test_EntityRepo_Paging()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                #region prepare data

                int aCnt = 20;
                int bCnt = 3;
                for (int i = 0; i < aCnt; i++)
                {
                    var a = new Author()
                    {
                        FirstName = "Fname" + i,
                        LastName = "Lname" + i,
                        Born = DateTime.Now.AddYears(-20).AddDays(i),
                        NumberOfAwards = i / 3
                    };
                    repository.Create(a);
                    for (int j = 0; j < bCnt; j++)
                    {
                        var b = new Book()
                        {
                            Title = string.Format("Book_{0}_{1}", i, j),
                            Genre = Genre.SciFi,
                            Price = 10.0m + j,
                            ISBN = string.Format("{0}_{1}", a.LastName, j)
                        };
                        repository.Create(b);
                        repository.Attach(b, new Relation("author", a));
                    }
                }

                Assert.AreEqual(aCnt, repository.Search(new EntityQuery2("author")).Count());
                Assert.AreEqual(aCnt * bCnt, repository.Search(new EntityQuery2("book")).Count());

                #endregion

                var query = new EntityQuery2("Author");
                query.AddProperties("FirstName", "LastName");
                query.Include("book", "author");
                query.Paging = new Paging(1, 10);
                var res = repository.Search(query);
                Assert.AreEqual(10, res.Count());
                int idx = 0;
                foreach (var r in res)
                {
                    Assert.AreEqual("Fname" + idx, r.GetData<string>("firstname"));
                    var books = r.GetManyRelations("book", "author");
                    int bidx = 0;
                    foreach (var b in books)
                    {
                        Assert.AreEqual(string.Format("Book_{0}_{1}", idx, bidx++), b.Entity.GetData<string>("title"));
                    }
                    idx++;
                }

                //assert second page
                query.Paging.Page++;
                res = repository.Search(query);
                Assert.AreEqual(10, res.Count());
                foreach (var r in res)
                {
                    Assert.AreEqual("Fname" + idx, r.GetData<string>("firstname"));
                    var books = r.GetManyRelations("book", "author");
                    int bidx = 0;
                    foreach (var b in books)
                    {
                        Assert.AreEqual(string.Format("Book_{0}_{1}", idx, bidx++), b.Entity.GetData<string>("title"));
                    }
                    idx++;
                }
            }
        }
Exemplo n.º 37
0
        private void SendIssueToSubscribers(EntityUpdate update)
        {
            var issueQuery = new EntityQuery2(EntityConsts.Issue, update.Id.Value);
            issueQuery.AllProperties = true;
            issueQuery.Include(EntityConsts.Magazine, Roles.Issue);
            issueQuery.Include(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content);
            var issue = _repository.Read(issueQuery);
            var magazine = issue.GetSingleRelation(EntityConsts.Magazine, Roles.Issue).Entity;
            var subscribersQuery = new EntityQuery2(User.ENTITY);
            var relQuery = new RelationQuery(EntityConsts.Magazine, Roles.Subscriber, magazine.Id);
            relQuery.RelationRules.Add(new Condition("IsActive", Condition.Is, true));
            subscribersQuery.WhereRelated(relQuery);
            subscribersQuery.AllProperties = true;
            var subscribers = _repository.Search(subscribersQuery).Select(e => new User(e));

            var contents = issue.GetManyRelations(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content).Select(r => new File(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.NEW_ISSUE));

            string subject = null, body = null;
            Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase);
            templateContext.Add("Magazine", magazine);
            templateContext.Add("Issue", issue);

            _templateService.Render(template, templateContext, out subject, out body);

            _notificationService.SendNotification(true, subscribers, subject, body, contents, new Relation[] { new Relation(Notification.ROLE, issue) });
        }
Exemplo n.º 38
0
        public InspectionResult Inspect(EntityOperation operation)
        {
            if (operation.IsEntity("Inquery"))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
                {
                    if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                        return InspectionResult.Allow;
                    else if (_securityService.CurrentUser.UserType == UserTypes.Customer)
                    {
                        if (operation is EntityUpdate && (operation as EntityUpdate).IsCreate())
                            return InspectionResult.Allow;
                        else if (operation is EntityUpdate)
                        {
                            var update = operation as EntityUpdate;
                            if (update.ContainsRelation(User.ENTITY, RelationConsts.Customer))
                                return InspectionResult.Deny;

                            var q = new EntityQuery2(Inquery.EntityType, update.Id.Value);
                            q.AddProperties("Status");
                            q.Include(User.ENTITY, RelationConsts.Customer);
                            var inquery = _repository.Read(q);

                            if (inquery.GetData<QueryStatus>("Status") != QueryStatus.New)
                                return InspectionResult.Deny;

                            if (update.ContainsProperty("Status")
                                && update.Get<QueryStatus>("Status") != QueryStatus.Canceled)
                                return InspectionResult.Deny;

                            var customer = inquery.GetSingleRelation(User.ENTITY, RelationConsts.Customer);
                            if (customer != null && customer.Entity.Id == _securityService.CurrentUser.Id)
                                return InspectionResult.Allow;
                        }
                    }
                }
            }
            else if (operation.IsEntity(Notification.ENTITY) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsCreate()
                    && update.ContainsRelation(Inquery.EntityType, RelationConsts.Inquery)
                    && _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use)
                    && _securityService.CurrentUser.UserType == UserTypes.Librarian)
                {
                    return InspectionResult.Allow;
                }
            }
            return InspectionResult.None;
        }
Exemplo n.º 39
0
        public void After(EntityOperation operation, EntityOperationContext context, EntityOperationResult result)
        {
            if (!result.Success)
                return;

            if (operation.IsEntity(EntityConsts.Issue) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (context.Get<bool>(CTXKEY_SEND_ISSUE))
                {
                    SendIssueToSubscribers(operation as EntityUpdate);
                }

                if (update.ContainsRelation(File.ENTITY, Roles.Content))
                {
                    var filesAttached = update.GetMultipleRelationUpdates(File.ENTITY, Roles.Content).Where(fu => fu.Operation == RelationOperation.Attach);
                    if (filesAttached.Count() > 0)
                    {
                        var issue = update.ToEntity();
                        var q = new EntityQuery2(EntityConsts.Magazine);
                        q.WhereRelated(new RelationQuery(EntityConsts.Issue, Roles.Issue, issue.Id));
                        q.Include(User.ENTITY, Roles.Subscriber);
                        var mag = _repository.Read(q);
                        var subscribers = mag.GetManyRelations(User.ENTITY, Roles.Subscriber).Select(r => new User(r.Entity));
                        foreach (var subscriber in subscribers)
                        {
                            foreach (var fileUpdate in filesAttached)
                            {
                                if (!_fileService.HasAccess(subscriber, fileUpdate.Id.Value))
                                    _fileService.GrantAccess(fileUpdate.Id.Value, FileAccessType.Read, subscriber);
                            }
                        }
                    }
                }
            }
            else if (operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsEntity(User.ENTITY) && update.ContainsRelation(EntityConsts.Magazine, Roles.Subscriber))
                {
                    var rus = update.GetMultipleRelationUpdates(EntityConsts.Magazine, Roles.Subscriber).Where(ru => ru.Operation == RelationOperation.Attach);
                    foreach (var ru in rus)
                    {
                        var q = new EntityQuery2(EntityConsts.Issue);
                        q.WhereRelated(new RelationQuery(EntityConsts.Magazine, Roles.Issue, ru.Id.Value));
                        q.Include(File.ENTITY, Roles.Content);
                        var issues = _repository.Search(q);
                        foreach (var issue in issues)
                        {
                            //The user cannot give himself an access to file - only owner or administrator can.
                            using (_securityService.BeginSystemContext())
                            {
                                GiveFileAccessForIssue(issue, new User(update.ToEntity()));
                            }
                        }
                    }
                }
                else if (update.IsEntity(EntityConsts.Magazine) && update.ContainsRelation(User.ENTITY, Roles.Subscriber))
                {
                    var rus = update.GetMultipleRelationUpdates(User.ENTITY, Roles.Subscriber).Where(ru => ru.Operation == RelationOperation.Attach);

                    if (rus.Count() > 0)
                    {
                        var q = new EntityQuery2(EntityConsts.Issue);
                        q.WhereRelated(new RelationQuery(EntityConsts.Magazine, Roles.Issue, update.Id.Value));
                        q.Include(File.ENTITY, Roles.Content);
                        var issues = _repository.Search(q);
                        foreach (var ru in rus)
                        {
                            foreach (var issue in issues)
                                GiveFileAccessForIssue(issue, new User(ru.Id.Value));
                        }
                    }
                }
                else if (update.IsEntity(EntityConsts.Magazine) && update.ContainsProperty("IsActive"))
                {
                    var isActiveNew = update.Get<bool>("IsActive");
                    if (isActiveNew == false && context.Get<bool>(CTXKEY_ISACTIVEOLD))
                    {
                        SendMagazineNotActiveToSubscribers(update);
                    }
                }
            }
        }
Exemplo n.º 40
0
 public InspectionResult InspectQuery(EntityQuery2 query)
 {
     if (query.IsForEntity(EntityConsts.Magazine)
         || query.IsForEntity(EntityConsts.Issue)
         || query.IsForEntity(EntityConsts.MagazineCategory)
         || (query.IsForEntity(User.ENTITY) && _securityService.CurrentUser.UserType == UserTypes.Librarian))
     {
         if (_securityService.HasModulePermission(_securityService.CurrentUser, MyMagazinesModule.Id, Permissions.Use))
         {
             return InspectionResult.Allow;//TODO: MyMagazines inspect query
         }
     }
     else if (query.IsForEntity(Notification.ENTITY)
         && _securityService.CurrentUser.UserType == UserTypes.Librarian
         && _securityService.HasModulePermission(_securityService.CurrentUser, MyMagazinesModule.Id, Permissions.Use))
     {
         query.Include(EntityConsts.Issue, Notification.ROLE);
     }
     return InspectionResult.None;
 }
Exemplo n.º 41
0
        public void After(Core.Services.tmp.EntityOperation operation, EntityOperationContext context, EntityOperationResult result)
        {
            if (!result.Success)
                return;

            var update = operation as EntityUpdate;
            if (operation.IsEntity(EntityConsts.BibliographicListQuery) && update != null && update.ContainsProperty("Status") && update.Get<QueryStatus>("Status") == QueryStatus.Completed)
            {
                var q = new EntityQuery2(EntityConsts.BibliographicListQuery, update.Id.Value) { AllProperties = true };
                q.Include(User.ENTITY, Roles.Customer);
                var biblListQuery = _repository.Read(q);
                var user = new User(biblListQuery.GetSingleRelation(User.ENTITY, Roles.Customer).Entity);
                var template = _templateService.Get(new Guid(NotificationTemplates.QUERY_COMPLETED));
                string subject = null, body = null;
                Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase);
                templateContext.Add("Customer", user);
                templateContext.Add("Query", biblListQuery);

                _templateService.Render(template, templateContext, out subject, out body);
                var withEmail = biblListQuery.GetData<ReplyMethods>("ReplyMethod") == ReplyMethods.ByEmail;
                _notificationService.SendNotification(withEmail, new User[] { user }, subject, body, null, new Relation[] { new Relation(Notification.ROLE, biblListQuery) });
            }
            else if (operation.IsEntity(Payment.ENTITY) && update != null && update.ContainsProperty("Status") && update.Get<PaymentStatus>("Status") == PaymentStatus.Paid)
            {
                var q = new EntityQuery2(EntityConsts.BibliographicListQuery);
                q.AddProperties("Number");
                q.WhereRelated(new RelationQuery(Payment.ENTITY, Roles.Payment, update.Id.Value));
                q.Include(User.ENTITY, Roles.Customer);
                q.Include(File.ENTITY, Roles.File);
                var biblListQuery = _repository.Read(q);
                if (biblListQuery != null)
                {
                    var file = new File(biblListQuery.GetSingleRelation(File.ENTITY, Roles.File).Entity);
                    var user = new User(biblListQuery.GetSingleRelation(User.ENTITY, Roles.Customer).Entity);

                    var template = _templateService.Get(new Guid(NotificationTemplates.PAYMENT_COMPLETED));

                    string subject = null, body = null;
                    Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase);
                    templateContext.Add("Customer", user);
                    templateContext.Add("Query", biblListQuery);

                    _templateService.Render(template, templateContext, out subject, out body);

                    var withEmail = biblListQuery.GetData<ReplyMethods>("ReplyMethod") == ReplyMethods.ByEmail;
                    _notificationService.SendNotification(withEmail, new User[] { user }, subject, body, new File[] { file }, new Relation[] { new Relation(Notification.ROLE, biblListQuery) });
                    //_fileService.GrantAccess(file.Id, FileAccessType.Read, new User(biblQuery.GetSingleRelation(User.ENTITY, Roles.Customer).Entity));

                }
            }
        }
Exemplo n.º 42
0
        private void SendMagazineNotActiveToSubscribers(EntityUpdate update)
        {
            var magazineQuery = new EntityQuery2(EntityConsts.Magazine, update.Id.Value);
            magazineQuery.AllProperties = true;
            magazineQuery.Include(User.ENTITY, Roles.Subscriber);

            var magazine = _repository.Read(magazineQuery);

            var subscribers = magazine.GetManyRelations(User.ENTITY, Roles.Subscriber).Select(r => new User(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.DEACTIVATED_MAGAZINE));

            string subject = null, body = null;
            Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase);
            templateContext.Add("Magazine", magazine);
            _templateService.Render(template, templateContext, out subject, out body);
            _notificationService.SendNotification(true, subscribers, subject, body, null, new Relation[] { new Relation(Notification.ROLE, magazine) });
        }
Exemplo n.º 43
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity("Arguments") && _securityService.HasModulePermission(_securityService.CurrentUser, BiblListModule.Id, Permissions.Use))
                return InspectionResult.Allow;
            if (query.IsForEntity(EntityConsts.BibliographicListQuery)
                || query.IsForEntity(EntityConsts.BibliographicListStandart))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, BiblListModule.Id, Permissions.Use))
                {
                    if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                        return InspectionResult.Allow;
                    else if (_securityService.CurrentUser.UserType == UserTypes.Customer && query.IsForEntity(EntityConsts.BibliographicListQuery))
                    {
                        var relToMe = query.GetRelatedQuery(User.ENTITY, Roles.Customer);
                        if (relToMe != null && relToMe.GetSingleId().HasValue && relToMe.GetSingleId().Value == _securityService.CurrentUser.Id)
                            return InspectionResult.Allow;
                        else if (!query.HasInclude(User.ENTITY, Roles.Customer))
                            query.Include(User.ENTITY, Roles.Customer);
                    }
                    else
                        return InspectionResult.Allow;
                }
            }
            else if (query.IsForEntity(Payment.ENTITY)
                && _securityService.CurrentUser.UserType == UserTypes.Librarian
                && _securityService.HasModulePermission(_securityService.CurrentUser, BiblListModule.Id, Permissions.Use))
            {
                if (query.GetRelatedQuery(EntityConsts.BibliographicListQuery, Roles.Payment) != null)
                    return InspectionResult.Allow;
                else if (!query.HasInclude(EntityConsts.BibliographicListQuery, Roles.Payment))
                    query.Include(EntityConsts.BibliographicListQuery, Roles.Payment);
            }

            return InspectionResult.None;
        }
Exemplo n.º 44
0
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity(Payment.ENTITY))
            {
                var cust = query.GetRelatedQuery(User.ENTITY, Payment.ROLE_CUSTOMER);
                if (cust != null && cust.GetSingleId().HasValue && cust.GetSingleId().Value == _securityService.CurrentUser.Id)
                    return InspectionResult.Allow;
                else if (!query.HasInclude(User.ENTITY, Payment.ROLE_CUSTOMER))
                    query.Include(User.ENTITY, Payment.ROLE_CUSTOMER);
            }

            return InspectionResult.None;
        }
Exemplo n.º 45
0
        public InspectionResult Inspect(EntityOperation operation)
        {
            if (operation.IsEntity(Notification.ENTITY) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsCreate())
                    return InspectionResult.Allow;
                else if (update.PropertyUpdates.Count == 1 && (update.ContainsProperty("Received") || update.ContainsProperty("Archived")))
                {
                    EntityQuery2 q = new EntityQuery2(Notification.ENTITY, update.Id.Value);
                    q.Include(User.ENTITY, Roles.Recipient);
                    var recipient = _repository.Read(q).GetSingleRelation(User.ENTITY, Roles.Recipient);
                    if (recipient != null && recipient.Entity.Id == _securityService.CurrentUser.Id)
                        return InspectionResult.Allow;
                }
                else if (update.PropertyUpdates.Count == 1 && update.ContainsProperty("ArchivedSent"))
                {
                    EntityQuery2 q = new EntityQuery2(Notification.ENTITY, update.Id.Value);
                    q.Include(User.ENTITY, Roles.Sender);
                    var sender = _repository.Read(q).GetSingleRelation(User.ENTITY, Roles.Sender);
                    if (sender != null && sender.Entity.Id == _securityService.CurrentUser.Id)
                        return InspectionResult.Allow;
                }
            }

            return InspectionResult.None;
        }
Exemplo n.º 46
0
        public LoginResult Login(string username, string password, bool persistent)
        {
            SHA1 sha1 = SHA1.Create();
            var pwdBytes = Encoding.UTF8.GetBytes(password);
            var hash = Convert.ToBase64String(sha1.ComputeHash(pwdBytes));

            EntityQuery2 query = new EntityQuery2(User.ENTITY);
            query.AllProperties = true;
            query.Include(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE);
            query.WhereIs("email", username);
            //query.WhereIs("password", hash);
            var e = _repository.Read(query);
            if (e == null)
                return LoginResult.InvalidCredentials;
            User user = new User(e);

            if (user.FailedLoginsCount.HasValue && user.FailedLoginsCount.Value > 3 && user.LastFailedLogin.HasValue && user.LastFailedLogin.Value.Add(TimeSpan.FromHours(4)) > DateTime.Now)
            {
                return LoginResult.UserLocked;
            }

            if (!user.Password.Equals(hash, StringComparison.InvariantCultureIgnoreCase))
            {
                user.LastFailedLogin = DateTime.Now;
                if (user.FailedLoginsCount.HasValue)
                    user.FailedLoginsCount = user.FailedLoginsCount.Value + 1;
                else
                    user.FailedLoginsCount = 1;

                var upd = new User(user.Id);
                upd.FailedLoginsCount = user.FailedLoginsCount;
                upd.LastFailedLogin = user.LastFailedLogin;
                _repository.Update(upd);
                return LoginResult.InvalidCredentials;
            }

            if (!user.IsActive)
                return LoginResult.UserInactive;

            System.Web.Security.FormsAuthentication.SetAuthCookie(user.Email, persistent);
            return LoginResult.Success;
        }
Exemplo n.º 47
0
        public void Test_EntityRepo_SearchWithRels()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                var jordan = new Author()
                {
                    FirstName = "Robert",
                    LastName = "Jordan",
                    IsAlive = false,
                    Born = new DateTime(1948, 10, 17),
                    Rating = 10.0m
                };

                var feist = new Author()
                {
                    FirstName = "Raymond",
                    LastName = "Feist",
                    IsAlive = true,
                    Born = new DateTime(1963, 2, 14),
                    Rating = 6.7m
                };

                var fb1 = new Book()
                {
                    Title = "The Apprentice",
                    Price = 19.90m
                };

                var fb2 = new Book()
                {
                    Title = "The Magician",
                    Price = 17.10m
                };

                repository.Create(jordan);
                repository.Create(feist);
                repository.Create(fb1);
                repository.Create(fb2);
                repository.Attach(feist, new Relation("author", fb1));
                repository.Attach(feist, new Relation("author", fb2));

                var query = new EntityQuery2("author");
                query.AddProperties("firstname", "lastname", "born");
                query.Include("book", "author");
                var res = repository.Search(query);

                Assert.AreEqual(2, res.Count());
                var rf = res.Single(e => e.Id == feist.Id);
                var rj = res.Single(e => e.Id == jordan.Id);

                Assert.AreEqual(1, rf.RelationsData.Count);
                var books = rf.GetManyRelations("book", "author");
                Assert.AreEqual(2, books.Count());
                foreach (var r in books)
                {
                    var orig = r.Entity.Id == fb1.Id ? fb1 : fb2;
                    foreach (var pm in dms.Domain.Entities["book"].Properties)
                    {
                        if (orig.Data.ContainsKey(pm.Name))
                            Assert.AreEqual(orig.Data[pm.Name], r.Entity.Data[pm.Name]);
                    }
                }

                Assert.AreEqual(0, rj.RelationsData.Count);
                Assert.AreEqual(0, rj.GetManyRelations("book", "author").Count());

                //TODO: rules!

                //repository.Complete();
            }
        }
Exemplo n.º 48
0
        public void Test_EntityRepo_ReadWithRel()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                var jordan = new Author()
                {
                    FirstName = "Robert",
                    LastName = "Jordan",
                    IsAlive = false,
                    Born = new DateTime(1948, 10, 17),
                    Rating = 10.0m
                };

                var feist = new Author()
                {
                    FirstName = "Raymond",
                    LastName = "Feist",
                    IsAlive = true,
                    Born = new DateTime(1963, 2, 14),
                    Rating = 6.7m
                };

                var fb1 = new Book()
                {
                    Title = "The Apprentice",
                    Price = 19.90m
                };

                var fb2 = new Book()
                {
                    Title = "The Magician",
                    Price = 17.10m
                };

                repository.Create(jordan);
                repository.Create(feist);
                repository.Create(fb1);
                repository.Create(fb2);
                repository.Attach(feist, new Relation("author", fb1));
                repository.Attach(feist, new Relation("author", fb2));

                EntityQuery2 q = new EntityQuery2("book", fb1.Id);
                q.AddProperties("title", "price");
                q.Include("author", "author");
                var e = repository.Read(q);
                Assert.AreEqual(2, e.Data.Count);
                foreach (var p in q.Properties)
                {
                    Assert.AreEqual(fb1.Data[p], e.Data[p]);
                }

                Assert.AreEqual(1, e.RelationsData.Count);
                var authorRel = e.GetSingleRelation("author", "author");
                foreach (var d in feist.Data)
                {
                    Assert.AreEqual(d.Value, authorRel.Entity.Data[d.Key]);
                }

                //repository.Complete();
            }
        }
Exemplo n.º 49
0
        public void Test_EntityOperation_Update()
        {
            var dbService = new TestDatabaseService();
            var repo = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            IEntityOperationService svc = new EntityOperationService(repo, dbService, new IEntityOperationInspector[] { new Inspector() }, new IEntityQueryInspector[] { new Inspector() }, new IEntityOperationLogic[] { new Logic() });
            EntityUpdate update = new EntityUpdate("Author");
            update.Set("FirstName", "John");
            update.Set("LastName", "Tolkin");
            update.Set("Numberofawards", 2);
            update.Set("IsAlive", false);

            EntityUpdate book = new EntityUpdate("book");
            book.Set("Title", "The Eye of the World");
            book.Set("genre", Genre.Fantasy);

            svc.Update(book);
            update.Attach("Book", "author", book.Id.Value);

            var result = svc.Update(update);
            Assert.AreEqual(true, result.Success);

            EntityQuery2 query = new EntityQuery2("Author");
            query.AddProperties("FirstName", "LastName", "IsAlive", "CreatedOn");
            query.Include("book", "author");
            var res = repo.Search(query);
            Assert.AreEqual(1, res.Count());
            var a = res.Single();
            Assert.AreEqual("John", a.GetData<string>("Firstname"));
            Assert.AreEqual("Tolkin", a.GetData<string>("LastName"));
            var created = a.GetData<DateTime>("createdon");
            Assert.AreEqual(DateTime.Now.Date, created.Date);
            var books = a.GetManyRelations("book", "author");
            Assert.AreEqual(1, books.Count());
            var b = books.Single().Entity;
            Assert.AreEqual("The Eye of the World", b.GetData<string>("title"));
            Assert.AreEqual(Genre.Fantasy, b.GetData<Genre>("genre"));
            created = b.GetData<DateTime>("createdon");
            Assert.AreEqual(DateTime.Now.Date, created.Date);

            repo.Delete(a, true);
            repo.Delete(b);
        }
Exemplo n.º 50
0
        public InspectionResult Inspect(EntityOperation operation)
        {
            if (operation.IsEntity("Inquery"))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
                {
                    if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                    {
                        return(InspectionResult.Allow);
                    }
                    else if (_securityService.CurrentUser.UserType == UserTypes.Customer)
                    {
                        if (operation is EntityUpdate && (operation as EntityUpdate).IsCreate())
                        {
                            return(InspectionResult.Allow);
                        }
                        else if (operation is EntityUpdate)
                        {
                            var update = operation as EntityUpdate;
                            if (update.ContainsRelation(User.ENTITY, RelationConsts.Customer))
                            {
                                return(InspectionResult.Deny);
                            }

                            var q = new EntityQuery2(Inquery.EntityType, update.Id.Value);
                            q.AddProperties("Status");
                            q.Include(User.ENTITY, RelationConsts.Customer);
                            var inquery = _repository.Read(q);

                            if (inquery.GetData <QueryStatus>("Status") != QueryStatus.New)
                            {
                                return(InspectionResult.Deny);
                            }

                            if (update.ContainsProperty("Status") &&
                                update.Get <QueryStatus>("Status") != QueryStatus.Canceled)
                            {
                                return(InspectionResult.Deny);
                            }

                            var customer = inquery.GetSingleRelation(User.ENTITY, RelationConsts.Customer);
                            if (customer != null && customer.Entity.Id == _securityService.CurrentUser.Id)
                            {
                                return(InspectionResult.Allow);
                            }
                        }
                    }
                }
            }
            else if (operation.IsEntity(Notification.ENTITY) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsCreate() &&
                    update.ContainsRelation(Inquery.EntityType, RelationConsts.Inquery) &&
                    _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use) &&
                    _securityService.CurrentUser.UserType == UserTypes.Librarian)
                {
                    return(InspectionResult.Allow);
                }
            }
            return(InspectionResult.None);
        }