Example #1
0
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable<Entity> entities)
        {
            if (query.IsForEntity(Inquery.EntityType)
                && _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
            {
                if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                    return InspectionResult.Allow;
                else if (_securityService.CurrentUser.UserType == UserTypes.Customer)
                {
                    bool isMe = false;
                    foreach (var e in entities)
                    {
                        isMe = false;
                        var rel = e.GetSingleRelation(User.ENTITY, RelationConsts.Customer);
                        if (rel != null && rel.Entity.Id == _securityService.CurrentUser.Id)
                            isMe = true;
                        if (!isMe)
                            break;
                    }

                    if (isMe)
                        return InspectionResult.Allow;
                }
            }

            return InspectionResult.None;
        }
        public InspectionResult Inspect(EntityOperation operation)
        {
            if (operation.IsEntity(User.ENTITY))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserManagement))
                    return InspectionResult.Allow;

                if(operation is EntityUpdate)
                {
                    var update = operation as EntityUpdate;
                    if (update.ContainsProperty("RecoveryCode"))
                        return InspectionResult.Deny; //Only users with UserManagement permission can access this property
                }

                if (operation.Id.HasValue && _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserActivation))
                {
                    EntityQuery2 query = new EntityQuery2("User", operation.Id.Value);
                    query.AddProperty("isActive");
                    var e = _repository.Read(query);
                    if (e.GetData<bool>("IsActive") == false)
                        return InspectionResult.Allow;
                }
                else if (operation is EntityUpdate)
                {
                    var update = operation as EntityUpdate;
                    if (update.Id.HasValue
                        && update.Id.Value == _securityService.CurrentUser.Id
                        && !update.ContainsProperty("IsActive"))//TODO: allowing the user to edit his data and relations
                        return InspectionResult.Allow;
                }
            }

            return InspectionResult.None;
        }
Example #3
0
        public void Before(Services.tmp.EntityOperation operation, EntityOperationContext context)
        {
            if (operation.IsEntity(Payment.ENTITY) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsCreate())
                {
                    List <int> usersToAttach = new List <int>();
                    foreach (var attach in update.RelationUpdates.Where(ru => ru.Operation == Services.tmp.RelationOperation.Attach))
                    {
                        var em          = _domainService.Domain.Entities[attach.Entity];
                        var customerRel = em.Relations[em.Name, User.ENTITY, Payment.ROLE_CUSTOMER];
                        if (customerRel != null && customerRel.TypeFor(User.ENTITY) == RelationType.OneToMany)
                        {
                            var q = new EntityQuery2(User.ENTITY);
                            q.WhereRelated(new RelationQuery(em.Name, customerRel.Role, attach.Id.Value));
                            var cust = _repository.Read(q);
                            if (cust != null)
                            {
                                usersToAttach.Add(cust.Id);
                            }
                        }
                    }

                    foreach (var id in usersToAttach)
                    {
                        update.Attach(User.ENTITY, Payment.ROLE_CUSTOMER, id);
                    }
                }
            }
        }
        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;
        }
Example #5
0
        public void Initialize()
        {
            try
            {
                var q = new EntityQuery2(User.ENTITY);
                q.WhereIs("Email", _systemUserEmail);
                using (var dbContext = _dbService.GetDatabaseContext(true))
                {
                    var e = _entityRepository.Search(q).SingleOrDefault();
                    if (e == null)
                    {
                        User admin = new User()
                        {
                            FirstName = "Build in",
                            LastName  = "Administrator",
                            Email     = _systemUserEmail,
                            Password  = _systemUserEmail,
                            UserType  = UserTypes.Admin,
                            IsActive  = true
                        };

                        SHA1 sha1 = SHA1.Create();
                        admin.Password = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(admin.Password)));

                        _entityRepository.Create(admin);
                        dbContext.Complete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not create build-in-administrator user.", ex);
            }
        }
Example #6
0
        public Domain.File GetFile(int fileId)
        {
            var q = new EntityQuery2(File.ENTITY, fileId);

            q.AllProperties = true;
            return(new File(_repository.Read(q)));
        }
Example #7
0
        public void Before(EntityOperation operation, EntityOperationContext context)
        {
            var update = operation as EntityUpdate;

            if (update != null)
            {
                if (operation.IsEntity(EntityConsts.Issue))
                {
                    if (update.IsCreate() && !update.ContainsProperty("Year"))
                    {
                        update.Set("Year", DateTime.Now.Year);
                    }

                    if (update.ContainsProperty("Sent"))//TODO: mymagazines issue send (sent flag used)
                    {
                        context.Set <bool>(CTXKEY_SEND_ISSUE, true);
                    }
                }
                else if (operation.IsEntity(EntityConsts.Magazine) && update.ContainsProperty("IsActive") && update.Id.HasValue)
                {
                    if (update.Get <bool>("IsActive") == false)
                    {
                        var q = new EntityQuery2(EntityConsts.Magazine, update.Id.Value);
                        q.AddProperty("IsActive");
                        var magazine = _repository.Read(q);
                        context.Set <bool>(CTXKEY_ISACTIVEOLD, magazine.GetData <bool>("IsActive"));
                    }
                }
            }
        }
        private string InstallModulesPermissions(IModule module)
        {
            StringBuilder info = new StringBuilder();

            info.Append("<ul>");
            ModulePermission mp = new ModulePermission()
            {
                Available = module.Requirements.Permissions != null?module.Requirements.Permissions.ToArray() : new string[0],
                                ModuleID   = module.Id,
                                ModuleName = module.Name
            };
            var q = new EntityQuery2(ModulePermission.ENTITY);

            q.AddProperty("Available");
            q.WhereIs("moduleId", module.Id);
            using (var dbContext = _dbService.GetDatabaseContext(true))
            {
                var ex = _repository.Read(q);
                if (ex == null)
                {
                    _repository.Create(mp.Entity);
                    foreach (var p in mp.Available)
                    {
                        info.AppendFormat("<li>{0} - added.</li>", p);
                    }
                }
                else if (ex.GetData <string>("Available") != mp.Entity.GetData <string>("Available"))
                {
                    var      oldRaw = ex.GetData <string>("Available");
                    string[] old    = null;
                    if (string.IsNullOrEmpty(oldRaw))
                    {
                        old = new string[0];
                    }
                    else
                    {
                        old = oldRaw.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    }
                    ex.SetData <string>("Available", mp.Entity.GetData <string>("Available"));
                    _repository.Update(ex);
                    foreach (var p in mp.Available)
                    {
                        if (!old.Contains(p))
                        {
                            info.AppendFormat("<li>{0} - added.</li>", p);
                        }
                    }
                    foreach (var p in old)
                    {
                        if (!mp.Available.Contains(p))
                        {
                            info.AppendFormat("<li>{0} - removed.</li>", p);
                        }
                    }
                }
                dbContext.Complete();
            }
            info.Append("</ul>");
            return(info.ToString());
        }
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable <Entity> entities)
        {
            if (query.IsForEntity(Inquery.EntityType) &&
                _securityService.HasModulePermission(_securityService.CurrentUser, AskTheLibModule.Id, Permissions.Use))
            {
                if (_securityService.CurrentUser.UserType == UserTypes.Librarian)
                {
                    return(InspectionResult.Allow);
                }
                else if (_securityService.CurrentUser.UserType == UserTypes.Customer)
                {
                    bool isMe = false;
                    foreach (var e in entities)
                    {
                        isMe = false;
                        var rel = e.GetSingleRelation(User.ENTITY, RelationConsts.Customer);
                        if (rel != null && rel.Entity.Id == _securityService.CurrentUser.Id)
                        {
                            isMe = true;
                        }
                        if (!isMe)
                        {
                            break;
                        }
                    }

                    if (isMe)
                    {
                        return(InspectionResult.Allow);
                    }
                }
            }

            return(InspectionResult.None);
        }
Example #10
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) });
        }
Example #11
0
        public void After(EntityOperation operation, EntityOperationContext context, EntityOperationResult result)
        {
            if (operation.IsEntity(Notification.ENTITY) &&
                operation is EntityUpdate &&
                context.Get <bool>(CTXKEY_CREATENOTIFICATION) &&
                result.Success)
            {
                var update = operation as EntityUpdate;
                var method = ReplyMethods.ByNotification;//default
                if (update.ContainsProperty("Method"))
                {
                    method = update.Get <ReplyMethods>("Method");
                }



                var recipientUpdate = update.GetRelationUpdate(User.ENTITY, Roles.Recipient);
                var attachments     = update.GetMultipleRelationUpdates(NbuLibrary.Core.Domain.File.ENTITY, Roles.Attachment);
                if (attachments != null)
                {
                    foreach (var att in attachments)
                    {
                        _fileService.GrantAccess(att.Id.Value, FileAccessType.Read, new User(recipientUpdate.Id.Value));
                    }
                }

                var recipientQuery = new EntityQuery2(User.ENTITY, recipientUpdate.Id.Value);
                recipientQuery.AddProperty("Email");
                var recipient = _repository.Read(recipientQuery);
                var to        = recipient.GetData <string>("Email");
                var body      = update.Get <string>("Body");
                var subject   = update.Get <string>("Subject");
            }
        }
Example #12
0
        public ActionResult ForgottenPassword(string email)
        {
            using (_securityService.BeginSystemContext())
            {
                var q = new EntityQuery2("User");
                q.WhereIs("Email", email);
                q.WhereIs("IsActive", true);
                Entity user = _entityService.Query(q).SingleOrDefault();
                if (user == null)
                {
                    ModelState.AddModelError("email", string.Format("В системата няма активен потребител с имейл \"{0}\". За помощ: тел. 02 8110296.", email));
                    return(View());
                }
                else
                {
                    var recoveryCode = Guid.NewGuid().ToString();

                    var update = new EntityUpdate(user.Name, user.Id);
                    update.Set("RecoveryCode", recoveryCode);
                    var result = _entityService.Update(update);
                    if (result.Success)
                    {
                        return(View("ForgottenPassword_Success", (object)email));
                    }
                    else
                    {
                        ModelState.AddModelError("email", "Възникна грешка при стартиране на процеса по възстановяване на забравена парола. За помощ: тел. 02 8110296.");
                        return(View());
                    }
                }
            }
        }
Example #13
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
            }
        }
Example #14
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);
        }
Example #15
0
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable <Entity> entities)
        {
            if (query.IsForEntity(Notification.ENTITY))
            {
                bool relatedToMe = true;
                foreach (var en in entities)
                {
                    relatedToMe = false;
                    var sender = en.GetSingleRelation(User.ENTITY, Roles.Sender);
                    if (sender != null && sender.Entity.Id == _securityService.CurrentUser.Id)
                    {
                        relatedToMe = true;
                        continue;
                    }

                    var rec = en.GetSingleRelation(User.ENTITY, Roles.Recipient);
                    if (rec != null && rec.Entity.Id == _securityService.CurrentUser.Id)
                    {
                        relatedToMe = true;
                        continue;
                    }

                    if (!relatedToMe)
                    {
                        break;
                    }
                }

                if (relatedToMe)
                {
                    return(InspectionResult.Allow);
                }
            }
            return(InspectionResult.None);
        }
Example #16
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));
        }
Example #17
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);
        }
Example #18
0
        public void Initialize()
        {
            try
            {
                var q = new EntityQuery2(User.ENTITY);
                q.WhereIs("Email", _systemUserEmail);
                using (var dbContext = _dbService.GetDatabaseContext(true))
                {
                    var e = _entityRepository.Search(q).SingleOrDefault();
                    if (e == null)
                    {
                        User admin = new User()
                        {
                            FirstName = "Build in",
                            LastName = "Administrator",
                            Email = _systemUserEmail,
                            Password = _systemUserEmail,
                            UserType = UserTypes.Admin,
                            IsActive = true
                        };

                        SHA1 sha1 = SHA1.Create();
                        admin.Password = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(admin.Password)));

                        _entityRepository.Create(admin);
                        dbContext.Complete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not create build-in-administrator user.", ex);
            }
        }
Example #19
0
        public InspectionResult Inspect(Core.Services.tmp.EntityOperation operation)
        {
            if (operation.IsEntity(EntityConsts.BibliographicListQuery) &&
                _securityService.HasModulePermission(_securityService.CurrentUser, BiblListModule.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.BibliographicListQuery))
                    {
                        var q = new EntityQuery2(User.ENTITY, _securityService.CurrentUser.Id);
                        q.WhereRelated(new RelationQuery(EntityConsts.BibliographicListQuery, Roles.Customer, update.Id.Value));
                        if (_repository.Read(q) != null)
                        {
                            return(InspectionResult.Allow);
                        }
                    }
                }
            }

            return(InspectionResult.None);
        }
Example #20
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);
        }
Example #21
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);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #22
0
        public ActionResult FinishResigration(RegisterViewModel model)
        {
            User user = new User()
            {
                Email = model.Email,
                Password = model.Password,
                FirstName = model.FirstName,
                MiddleName = model.MiddleName,
                LastName = model.LastName,
                FacultyNumber = model.FacultyNumber,
                CardNumber = model.CardNumber,
                PhoneNumber = model.PhoneNumber,
                UserType = UserTypes.Customer
            };
            var update = new EntityUpdate(user);
            update.Attach(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE, model.UserGroup);
            EntityOperationResult result = null;
            using (_securityService.BeginSystemContext())
            {
                result = _entityService.Update(update);
            }

            if (result.Success)
                return View("RegisterComplete");
            else
            {
                IEnumerable<UserGroup> availableGroups = null;
                using (_securityService.BeginSystemContext())
                {
                    var query = new EntityQuery2(UserGroup.ENTITY);
                    query.AllProperties = true;
                    query.WhereIs("UserType", UserTypes.Customer);
                    availableGroups = _entityService.Query(query).Select(e => new UserGroup(e));
                }

                if (result.Errors == null || result.Errors.Count == 0)
                    ModelState.AddModelError("", "Unexpected error occured. Please, try again. If there is still a problem, contact the administrator.");
                else
                {
                    foreach (var err in result.Errors)
                    {
                        ModelState.AddModelError("", err.Message);
                    }
                }

                var selectedGroup = availableGroups.Single(g => g.Id == model.UserGroup);
                if (selectedGroup.Name.Equals("Студенти", StringComparison.InvariantCultureIgnoreCase)
                    || selectedGroup.Name.Equals("Преподаватели", StringComparison.InvariantCultureIgnoreCase))
                {
                    return View("RegisterStudent", new RegisterStudentViewModel() { UserGroup = model.UserGroup, UserGroupName = selectedGroup.Name });
                }
                else if (selectedGroup.Name.Equals("Външни", StringComparison.InvariantCultureIgnoreCase))
                    return View("RegisterExternal", new RegisterExternalViewModel() { UserGroup = model.UserGroup, UserGroupName = selectedGroup.Name });
                else
                    return View("RegisterOther", new RegisterViewModel() { UserGroup = model.UserGroup, UserGroupName = selectedGroup.Name });
            }
        }
Example #23
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));
 }
Example #24
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));
                }
            }
        }
Example #25
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);
                }
            }
        }
Example #26
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)));
        }
Example #27
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);
        }
Example #28
0
        public ActionResult Register()
        {
            var model = new RegisterGroupModel();
            var query = new EntityQuery2(UserGroup.ENTITY);

            query.AllProperties = true;
            query.WhereIs("UserType", UserTypes.Customer);
            using (_securityService.BeginSystemContext())
            {
                model.AvailableGroups = _entityService.Query(query).Select(e => new UserGroup(e));
            }
            return(View(model));
        }
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (_securityService.HasModulePermission(_securityService.CurrentUser, NomenclatureModule.Id, Permissions.Manage))
            {
                var em = _domainService.Domain.Entities[query.Entity];
                if (em.IsNomenclature)
                {
                    return(InspectionResult.Allow);
                }
            }

            return(InspectionResult.None);
        }
Example #30
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);
        }
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity(User.ENTITY))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserManagement))
                {
                    return(InspectionResult.Allow);
                }
                else if (query.GetRuleByProperty("Id") != null && Convert.ToInt32(query.GetRuleByProperty("Id").Values[0]) == _securityService.CurrentUser.Id)
                {
                    return(InspectionResult.Allow);
                }

                if (query.HasProperty("RecoveryCode"))
                {
                    return(InspectionResult.Deny); //Only users with UserManagement permission can access this property
                }
                bool hasUserActivationPermission = _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserActivation);
                var  isActiveRule = query.Rules.Find(r => r.IsForProperty("IsActive"));
                if (isActiveRule != null &&
                    isActiveRule.Values.Count() == 1 &&
                    Convert.ToBoolean(isActiveRule.Values.Single()) == false &&
                    hasUserActivationPermission)
                {
                    return(InspectionResult.Allow);
                }

                if (hasUserActivationPermission && !query.HasProperty("IsActive"))
                {
                    query.AddProperty("IsActive");
                }
            }
            else if (query.IsForEntity(UserGroup.ENTITY))
            {
                if (_securityService.CurrentUser.UserType == UserTypes.Librarian ||
                    _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserGroupManagement) ||
                    _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserActivation))
                {
                    return(InspectionResult.Allow);
                }
                else if (query.GetRuleByProperty("UserType") != null &&
                         (UserTypes)Convert.ToInt32(query.GetRuleByProperty("UserType").Values[0]) == _securityService.CurrentUser.UserType &&
                         !query.HasInclude("User", "UserGroup"))
                {
                    return(InspectionResult.Allow);
                }
            }

            return(InspectionResult.None);
        }
Example #32
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));
        }
Example #33
0
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable <Entity> entities)
        {
            if (query.IsForEntity(NbuLibrary.Core.Domain.File.ENTITY))
            {
                foreach (var e in entities)
                {
                    if (_fileService.HasAccess(_securityService.CurrentUser, e.Id))
                    {
                        return(InspectionResult.Allow);
                    }
                }
            }

            return(InspectionResult.None);
        }
Example #34
0
 public InspectionResult InspectResult(EntityQuery2 query, IEnumerable <Entity> entity)
 {
     if (CurrentUser == null)
     {
         return(InspectionResult.Deny);
     }
     else if (CurrentUser.UserType == UserTypes.Admin)
     {
         return(InspectionResult.Allow);
     }
     else
     {
         return(InspectionResult.None);
     }
 }
Example #35
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.");
            }
        }
Example #36
0
        public int Count(EntityQuery2 query)
        {
            using (var dbContext = _dbService.GetDatabaseContext(false))
            {
                int allow = 0;
                foreach (var inspector in _queryInspectors)
                {
                    var result = inspector.InspectQuery(query);
                    if (result == InspectionResult.Allow)
                        allow++;
                    else if (result == InspectionResult.Deny)
                        return 0;
                }

                return _repository.Count(query);
            }
        }
Example #37
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);
        }
Example #38
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;
        }
        public InspectionResult InspectQuery(EntityQuery2 query)
        {
            if (query.IsForEntity(User.ENTITY))
            {
                if (_securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserManagement))
                    return InspectionResult.Allow;
                else if (query.GetRuleByProperty("Id") != null && Convert.ToInt32(query.GetRuleByProperty("Id").Values[0]) == _securityService.CurrentUser.Id)
                    return InspectionResult.Allow;

                if (query.HasProperty("RecoveryCode"))
                    return InspectionResult.Deny; //Only users with UserManagement permission can access this property

                bool hasUserActivationPermission = _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserActivation);
                var isActiveRule = query.Rules.Find(r => r.IsForProperty("IsActive"));
                if (isActiveRule != null
                    && isActiveRule.Values.Count() == 1
                    && Convert.ToBoolean(isActiveRule.Values.Single()) == false
                    && hasUserActivationPermission)
                    return InspectionResult.Allow;

                if (hasUserActivationPermission && !query.HasProperty("IsActive"))
                    query.AddProperty("IsActive");
            }
            else if (query.IsForEntity(UserGroup.ENTITY))
            {
                if (_securityService.CurrentUser.UserType == UserTypes.Librarian
                    || _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserGroupManagement)
                    || _securityService.HasModulePermission(_securityService.CurrentUser, AccountModule.Id, Permissions.UserActivation))
                    return InspectionResult.Allow;
                else if (query.GetRuleByProperty("UserType") != null
                    && (UserTypes)Convert.ToInt32(query.GetRuleByProperty("UserType").Values[0]) == _securityService.CurrentUser.UserType
                    && !query.HasInclude("User", "UserGroup"))
                    return InspectionResult.Allow;
            }

            return InspectionResult.None;
        }
        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;
        }
Example #41
0
 public IEnumerable<Entity> Search(EntityQuery2 query)
 {
     return _entityService.Query(query);
 }
Example #42
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.");
 }
Example #43
0
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable<Entity> entities)
        {
            if (query.IsForEntity(EntityConsts.BibliographicListQuery)
                && _securityService.CurrentUser.UserType == UserTypes.Customer
                && _securityService.HasModulePermission(_securityService.CurrentUser, BiblListModule.Id, Permissions.Use)
                && query.HasInclude(User.ENTITY, Roles.Customer))
            {
                bool isMe = true;
                foreach (var e in entities)
                {
                    var rel = e.GetSingleRelation(User.ENTITY, Roles.Customer);
                    if (rel == null || rel.Entity.Id != _securityService.CurrentUser.Id)
                    {
                        isMe = false;
                        break;
                    }
                }
                if (isMe)
                    return InspectionResult.Allow;
            }
            else if (query.IsForEntity(Payment.ENTITY) && query.HasInclude(EntityConsts.BibliographicListQuery, Roles.Payment))
            {
                bool ok = true;
                foreach (var e in entities)
                {
                    var rel = e.GetSingleRelation(EntityConsts.BibliographicListQuery, Roles.Payment);
                    if (rel == null)
                    {
                        ok = false;
                        break;
                    }
                }
                if (ok)
                    return InspectionResult.Allow;
            }

            return InspectionResult.None;
        }
Example #44
0
 public InspectionResult InspectQuery(EntityQuery2 query)
 {
     //TODO: filequeryinspector - inspect query
     return InspectionResult.None;
 }
Example #45
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;
        }
Example #46
0
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable<Entity> entities)
        {
            if (query.IsForEntity(NbuLibrary.Core.Domain.File.ENTITY))
            {
                foreach (var e in entities)
                {
                    if (_fileService.HasAccess(_securityService.CurrentUser, e.Id))
                        return InspectionResult.Allow;
                }
            }

            return InspectionResult.None;
        }
Example #47
0
        public void Before(Services.tmp.EntityOperation operation, EntityOperationContext context)
        {
            if (operation.IsEntity(Payment.ENTITY) && operation is EntityUpdate)
            {
                var update = operation as EntityUpdate;
                if (update.IsCreate())
                {
                    List<int> usersToAttach = new List<int>();
                    foreach (var attach in update.RelationUpdates.Where(ru => ru.Operation == Services.tmp.RelationOperation.Attach))
                    {
                        var em = _domainService.Domain.Entities[attach.Entity];
                        var customerRel = em.Relations[em.Name, User.ENTITY, Payment.ROLE_CUSTOMER];
                        if (customerRel != null && customerRel.TypeFor(User.ENTITY) == RelationType.OneToMany)
                        {
                            var q = new EntityQuery2(User.ENTITY);
                            q.WhereRelated(new RelationQuery(em.Name, customerRel.Role, attach.Id.Value));
                            var cust = _repository.Read(q);
                            if (cust != null)
                                usersToAttach.Add(cust.Id);
                        }
                    }

                    foreach (var id in usersToAttach)
                    {
                        update.Attach(User.ENTITY, Payment.ROLE_CUSTOMER, id);
                    }
                }
            }
        }
Example #48
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);
        }
Example #49
0
        public InspectionResult InspectResult(EntityQuery2 query, IEnumerable<Entity> entities)
        {
            if (query.IsForEntity(Payment.ENTITY))
            {
                bool mine = true;
                foreach (var e in entities)
                {
                    var rel = e.GetSingleRelation(User.ENTITY, Payment.ROLE_CUSTOMER);
                    if (rel == null || rel.Entity.Id != _securityService.CurrentUser.Id)
                    {
                        mine = false;
                        break;
                    }
                }
                if (mine)
                    return InspectionResult.Allow;
            }

            return InspectionResult.None;
        }
Example #50
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);
        }
Example #51
0
 public Domain.File GetFile(int fileId)
 {
     var q = new EntityQuery2(File.ENTITY, fileId);
     q.AllProperties = true;
     return new File(_repository.Read(q));
 }
Example #52
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;
        }
Example #53
0
 public int Count(EntityQuery2 query)
 {
     return _entityService.Count(query);
 }
Example #54
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));

                }
            }
        }
Example #55
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;
        }
Example #56
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);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #57
0
        public IEnumerable<Entity> Query(EntityQuery2 query)
        {
            using (var dbContext = _dbService.GetDatabaseContext(false))
            {
                int allow = 0;
                foreach (var inspector in _queryInspectors)
                {
                    var result = inspector.InspectQuery(query);
                    if (result == InspectionResult.Allow)
                        allow++;
                    else if (result == InspectionResult.Deny)
                        return new Entity[0];
                }

                var queryResult = _repository.Search(query);
                //if (allow == 0)
                //{
                foreach (var inspector in _queryInspectors)
                {
                    var result = inspector.InspectResult(query, queryResult);
                    if (result == InspectionResult.Allow)
                        allow++;
                    else if (result == InspectionResult.Deny)
                        return new Entity[0];
                }
                //}

                if (allow > 0)
                    return queryResult;
                else
                    return new Entity[0];
            }
        }
Example #58
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;
        }
Example #59
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
        }
Example #60
0
 public InspectionResult InspectResult(EntityQuery2 query, IEnumerable<Entity> entity)
 {
     if (CurrentUser == null)
         return InspectionResult.Deny;
     else if (CurrentUser.UserType == UserTypes.Admin)
         return InspectionResult.Allow;
     else
         return InspectionResult.None;
 }