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 }); } }
public void After(EntityOperation operation, EntityOperationContext context, EntityOperationResult result) { if (!result.Success) return; if (!operation.IsEntity(User.ENTITY)) return; var update = operation as EntityUpdate; if (update == null) return; if (context.Get<bool>(CTXKEY_USER_PASSWORDRECOVERY)) { var user = new User(_repository.Read(new EntityQuery2(update.Entity, update.Id.Value) { AllProperties = true })); var template = _templateService.Get(new Guid(NotificationTemplates.USER_PASSWORDRECOVERY)); string subject = null, body = null; Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase); templateContext.Add("User", user); _templateService.Render(template, templateContext, out subject, out body); //TODO: async execution _notificationService.SendEmail(user.Email, subject, body, null); } if (context.Get<bool>(CTXKEY_USER_CREATION)) { var user = new User(_repository.Read(new EntityQuery2(update.Entity, update.Id.Value) { AllProperties = true })); var pwd = context.Get<string>(CTXKEY_PASSWORD_UPDATE); user.SetData<String>("Password", pwd); var template = _templateService.Get(new Guid(NotificationTemplates.USER_CREATED)); string subject = null, body = null; Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase); templateContext.Add("User", user); _templateService.Render(template, templateContext, out subject, out body); //TODO: async execution _notificationService.SendEmail(user.Email, subject, body, null); if (update.ContainsProperty("IsActive") && update.Get<bool>("IsActive")) SendUserActivationEmail(user); } else if (update.ContainsProperty("IsActive") && update.Get<bool>("IsActive")) { var user = new User(_repository.Read(new EntityQuery2(update.Entity, update.Id.Value) { AllProperties = true })); SendUserActivationEmail(user); } else if (context.Get<int>(CTXKEY_UPDATE_PROFILE) > 0) { if (update.ContainsRelation("UserGroup", "UserGroup") || update.ContainsProperty("FacultyNumber") || update.ContainsProperty("CardNumber")) { var user = new User(context.Get<int>(CTXKEY_UPDATE_PROFILE)); user.IsActive = false; _repository.Update(user); _securityService.Logout(); result.Data.Add("account_warning_logged_out", true); } if (update.ContainsProperty("Email")) { _securityService.UpdateCurrentUserEmail(update.Get<string>("Email")); result.Data.Add("account_event_email_changed", update.Get<string>("Email")); } } }
private void SendUserActivationEmail(User user) { var templ = _templateService.Get(new Guid(NotificationTemplates.USER_ACTIVATED)); string subject = null, body = null; Dictionary<string, Entity> ctx = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase); ctx.Add("User", user); _templateService.Render(templ, ctx, out subject, out body); _notificationService.SendEmail(user.Email, subject, body, null); }
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)); } } }
public void Dispose() { _user = null; }
public SystemSecurityContext(User user) { if (_user == null) _user = user; }
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; }
public void UpdateCurrentUserEmail(string email) { var authCookie = System.Web.HttpContext.Current.Request.Cookies["NbuLib"]; if (authCookie != null) { var ticket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value); bool isPersistent = ticket.IsPersistent; string newEmail = email; System.Web.Security.FormsAuthentication.SignOut(); System.Web.Security.FormsAuthentication.SetAuthCookie(newEmail, isPersistent); _currentUser = GetCurrentUser(newEmail); System.Web.HttpContext.Current.Items[KEY_REQUEST_CACHE] = _currentUser; } }
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; }
private bool HasAccessInternal(User user, IEnumerable<NbuLibrary.Core.Domain.FileAccess> fileAccesses, FileAccessType accessType, Guid? token) { if (fileAccesses == null) return false; foreach (var a in fileAccesses) { if (a.Type != accessType) continue; else if (accessType == FileAccessType.Token && a.Token.HasValue && token.HasValue && token.Value == a.Token.Value && (!a.Expire.HasValue || a.Expire.Value > DateTime.Now)) { return true; } else if (accessType == FileAccessType.Temporary && (!a.Expire.HasValue || a.Expire.Value > DateTime.Now)) { return true; } else if (accessType == FileAccessType.Owner || accessType == FileAccessType.Full || accessType == FileAccessType.Read) return true; } return false; }
private bool HasAccessInternal(User user, IEnumerable<NbuLibrary.Core.Domain.FileAccess> fileAccesses, Guid? token) { if (user.UserType == UserTypes.Admin) return true; else if (_securityService.HasModulePermission(user, FilesModule.Id, Permissions.ManageAll)) return true; foreach (var fa in fileAccesses) { if (fa.User.Id != user.Id) continue; if (fa.Type == FileAccessType.Owner || fa.Type == FileAccessType.Full || fa.Type == FileAccessType.Read) return true; else if (fa.Type == FileAccessType.Temporary && fa.Expire.HasValue && fa.Expire.Value > DateTime.Now) return true; else if (fa.Type == FileAccessType.Token && token.HasValue && fa.Token.HasValue && token.Value == fa.Token.Value) { if (fa.Expire.HasValue) return fa.Expire > DateTime.Now; else return true; } } return false; }
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); }
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 }
private void GiveFileAccessForIssue(Entity issue, User user) { foreach (var fileAttach in issue.GetManyRelations(File.ENTITY, Roles.Content)) { if (!_fileService.HasAccess(user, fileAttach.Entity.Id)) _fileService.GrantAccess(fileAttach.Entity.Id, FileAccessType.Read, user); } }
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); } }
public void _GenerateDemoData() { using (GetService <ISecurityService>().BeginSystemContext()) { var repo = GetService <IEntityRepository>(); var userGroupLibAll = new NbuLibrary.Core.Domain.UserGroup() { Name = "Библиотечно-информационни услуги", UserType = Core.Domain.UserTypes.Librarian }; var userGroupLibMyMag = new NbuLibrary.Core.Domain.UserGroup() { Name = "Моите списания", UserType = Core.Domain.UserTypes.Librarian }; var userGroupStudents = new NbuLibrary.Core.Domain.UserGroup() { Name = "Студент", UserType = Core.Domain.UserTypes.Customer }; var userGroupEmpl = new NbuLibrary.Core.Domain.UserGroup() { Name = "Служител", UserType = Core.Domain.UserTypes.Customer }; var userGroupProfs = new NbuLibrary.Core.Domain.UserGroup() { Name = "Преподавател", UserType = Core.Domain.UserTypes.Customer }; var userGroupOutWithCard = new NbuLibrary.Core.Domain.UserGroup() { Name = "Външен (с читателска карта)", UserType = Core.Domain.UserTypes.Customer }; var userGroupOutNoCard = new NbuLibrary.Core.Domain.UserGroup() { Name = "Външен (без читателска карта)", UserType = Core.Domain.UserTypes.Customer }; repo.Search(new EntityQuery2("UserGroup")).ToList().ForEach(e => repo.Delete(e, true)); repo.Create(userGroupLibAll); repo.Create(userGroupLibMyMag); repo.Create(userGroupStudents); repo.Create(userGroupEmpl); repo.Create(userGroupProfs); repo.Create(userGroupOutWithCard); repo.Create(userGroupOutNoCard); var userLib1 = new NbuLibrary.Core.Domain.User() { UserType = Core.Domain.UserTypes.Librarian, Email = "*****@*****.**", Password = "******", FirstName = "Петър", LastName = "Димитров", UserGroup = userGroupLibAll }; var userLib2 = new NbuLibrary.Core.Domain.User() { UserType = Core.Domain.UserTypes.Librarian, Email = "*****@*****.**", Password = "******", FirstName = "Радост", LastName = "Иванова", UserGroup = userGroupLibAll }; var userLib3 = new NbuLibrary.Core.Domain.User() { UserType = Core.Domain.UserTypes.Librarian, Email = "*****@*****.**", Password = "******", FirstName = "Иван", LastName = "Георгиев", UserGroup = userGroupLibMyMag }; var qAllUsersWithoutAdmin = new EntityQuery2("User"); qAllUsersWithoutAdmin.WhereAnyOf("UserType", new object[] { 0, 1 }); //Assert.AreEqual(0, repo.Search(qAllUsersWithoutAdmin).Count()); repo.Search(qAllUsersWithoutAdmin).ToList().ForEach(e => repo.Delete(e, true)); //GetService<IEntityOperationService>().Update(new EntityUpdate(userLib1)); repo.Create(userLib1); repo.Attach(userLib1, new Relation(UserGroup.DEFAULT_ROLE, userLib1.UserGroup)); repo.Create(userLib2); repo.Attach(userLib2, new Relation(UserGroup.DEFAULT_ROLE, userLib2.UserGroup)); repo.Create(userLib3); repo.Attach(userLib3, new Relation(UserGroup.DEFAULT_ROLE, userLib3.UserGroup)); List <User> customers = new List <User>(); int count = 100; string[] fnames = new[] { "Иван", "Петър", "Кристиян", "Йордан", "Георги", "Симеон", "Александър", "Димитър", "Добромир", "Божидар", "Тодор", "Теодор", "Борис", "Борислав", "Цветан" }; string[] lnames = new[] { "Димитров", "Иванов", "Петров", "Йорданов", "Георгиев", "Симеонов", "Александров", "Кирилов", "Тодоров", "Бориславов", "Караиванов", "Ножаров", "Ковачев" }; UserGroup[] customerGroups = new[] { userGroupOutNoCard, userGroupOutWithCard, userGroupProfs, userGroupStudents, userGroupEmpl }; Random r = new Random(1);//fixed seed so that we have identical values generated for (int i = 0; i < count; i++) { string email = GenerateEmail(r); string password = email.Substring(0, email.IndexOf('.')); UserGroup group = customerGroups[r.Next(customerGroups.Length)]; var user = new User() { UserType = UserTypes.Customer, UserGroup = group, Email = email, Password = password, PhoneNumber = GeneratePhone(r), FirstName = fnames[r.Next(fnames.Length)], MiddleName = lnames[r.Next(lnames.Length)], LastName = lnames[r.Next(lnames.Length)], IsActive = r.Next(3) < 2, FacultyNumber = GenerateFacultyNumber(r, group), CardNumber = group == userGroupOutWithCard?GenerateCardNumber(r) : null }; customers.Add(user); } customers.ForEach(e => { repo.Create(e); repo.Attach(e, new Relation(UserGroup.DEFAULT_ROLE, e.UserGroup)); }); } }