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 #2
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());
                    }
                }
            }
        }
        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());
        }
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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));
        }
Example #11
0
        public ActionResult RecoverPassword(PasswordRecoveryModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (_securityService.BeginSystemContext())
            {
                var q = new EntityQuery2("User");
                q.WhereIs("Email", model.Email);
                q.WhereIs("RecoveryCode", model.RecoveryCode);
                q.WhereIs("IsActive", true);
                Entity user = _entityService.Query(q).SingleOrDefault();
                if (user == null)
                {
                    ModelState.AddModelError("", "Грешен имейл или код за възстановяване. Започнете процеса по възстановяване (през забравена парола) отново или позвънете на тел. 02 8110296.");
                    return(View(model));
                }
                else
                {
                    var update = new EntityUpdate(user.Name, user.Id);
                    update.Set("Password", model.Password);
                    var result = _entityService.Update(update);
                    if (result.Success)
                    {
                        return(View("RecoverPassword_Success"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Възникна грешка при смяна на паролата. Започнете процеса по възстановяване (през забравена парола) отново или позвънете на тел. 02 8110296.");
                        return(View(model));
                    }
                }
            }
        }
Example #12
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);
        }
Example #13
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);
        }
Example #14
0
        public ActionResult Register(RegisterGroupModel model)
        {
            using (_securityService.BeginSystemContext())
            {
                var query = new EntityQuery2(UserGroup.ENTITY);
                query.AllProperties = true;
                query.WhereIs("UserType", UserTypes.Customer);
                model.AvailableGroups = _entityService.Query(query).Select(e => new UserGroup(e));
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            else
            {
                var selectedGroup = model.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
                    }));
                }
            }
        }
        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 #16
0
 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();
 }
Example #17
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 #18
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 #19
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 #20
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 #21
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 #22
0
        public ActionResult RecoverPassword(PasswordRecoveryModel model)
        {
            if (!ModelState.IsValid)
                return View(model);

            using (_securityService.BeginSystemContext())
            {
                var q = new EntityQuery2("User");
                q.WhereIs("Email", model.Email);
                q.WhereIs("RecoveryCode", model.RecoveryCode);
                q.WhereIs("IsActive", true);
                Entity user = _entityService.Query(q).SingleOrDefault();
                if (user == null)
                {
                    ModelState.AddModelError("", "Грешен имейл или код за възстановяване. Започнете процеса по възстановяване (през забравена парола) отново или позвънете на тел. 02 8110296.");
                    return View(model);
                }
                else
                {
                    var update = new EntityUpdate(user.Name, user.Id);
                    update.Set("Password", model.Password);
                    var result = _entityService.Update(update);
                    if(result.Success)
                    {
                        return View("RecoverPassword_Success");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Възникна грешка при смяна на паролата. Започнете процеса по възстановяване (през забравена парола) отново или позвънете на тел. 02 8110296.");
                        return View(model);
                    }
                }
            }
        }
Example #23
0
        public void Test_EntityRepo_Count()
        {
            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

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

                Assert.AreEqual(2, res.Count());
                Assert.AreEqual(2, repository.Count(query));

                //greater then
                EntityQuery2 q = new EntityQuery2("book");
                q.WhereGreaterThen("price", 19.0m);
                Assert.AreEqual(3, repository.Search(q).Count());
                Assert.AreEqual(3, repository.Count(q));

                //less then
                q = new EntityQuery2("book");
                q.WhereLessThen("price", 20.0m);
                Assert.AreEqual(2, repository.Search(q).Count());
                Assert.AreEqual(2, repository.Count(q));

                //is boolean
                q = new EntityQuery2("author");
                q.WhereIs("isalive", false);
                var r = repository.Search(q);
                Assert.AreEqual(1, r.Count());
                Assert.AreEqual(1, repository.Count(q));

                //is string (ignore case)
                q = new EntityQuery2("author");
                q.WhereIs("lastname", "jordan");
                r = repository.Search(q);
                Assert.AreEqual(1, r.Count());
                Assert.AreEqual(1, repository.Count(q));

                //starts with
                q = new EntityQuery2("author");
                q.WhereStartsWith("firstname", "ra");
                r = repository.Search(q);
                Assert.AreEqual(1, r.Count());
                Assert.AreEqual(1, repository.Count(q));

                //ends with
                q = new EntityQuery2("book");
                q.WhereEndsWith("title", "world");
                r = repository.Search(q);
                Assert.AreEqual(1, r.Count());
                Assert.AreEqual(1, repository.Count(q));

                //less then
                q = new EntityQuery2("book");
                q.WhereAnyOf("id", new object[] { fb1.Id, jb1.Id, jb2.Id });
                Assert.AreEqual(3, repository.Search(q).Count());
                Assert.AreEqual(3, repository.Count(q));

                //between decimal
                q = new EntityQuery2("book");
                q.WhereBetween("price", 19.0m, 22.0m);
                Assert.AreEqual(2, repository.Search(q).Count());
                Assert.AreEqual(2, repository.Count(q));

                //between datetime
                q = new EntityQuery2("author");
                q.WhereBetween("born", new DateTime(1948, 1, 1), new DateTime(1949, 1, 1));
                r = repository.Search(q);
                Assert.AreEqual(1, r.Count());
                Assert.AreEqual(1, repository.Count(q));

                q = new EntityQuery2("author");
                q.WhereBetween("born", new DateTime(1948, 1, 1), new DateTime(1949, 1, 1));
                q.WhereIs("isalive", true);
                Assert.AreEqual(0, repository.Search(q).Count());
                Assert.AreEqual(0, repository.Count(q));

                q = new EntityQuery2("author");
                q.WhereBetween("born", new DateTime(1960, 1, 1), new DateTime(1970, 1, 1));
                q.WhereIs("isalive", true);
                q.WhereStartsWith("firstname", "ra");
                Assert.AreEqual(1, repository.Search(q).Count());
                Assert.AreEqual(1, repository.Count(q));
            }
        }
Example #24
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);
 }
Example #25
0
        public ActionResult Register(RegisterGroupModel model)
        {
            using (_securityService.BeginSystemContext())
            {
                var query = new EntityQuery2(UserGroup.ENTITY);
                query.AllProperties = true;
                query.WhereIs("UserType", UserTypes.Customer);
                model.AvailableGroups = _entityService.Query(query).Select(e => new UserGroup(e));
            }

            if (!ModelState.IsValid)
            {
                return View(model);
            }
            else
            {
                var selectedGroup = model.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 });
            }
        }