public IHttpActionResult UpdateSupplierPriceListFile(object obj) { try { AuthorizationUser AuUser = new AuthorizationUser(); Bis.SupplierPriceListFileMethod BisSupplierPriceList = new Bis.SupplierPriceListFileMethod(); JObject JsonObject = JObject.Parse(obj.ToString()); JsonObject.Add("IDPersonel", AuUser.ReturnIDUser(JsonObject["IDLogUser"].ToString().StringToGuid())); ViewModel.tblSupplierPriceListFile Update = JsonObject.ToObject <ViewModel.tblSupplierPriceListFile>(); bool ret = BisSupplierPriceList.UpdateSupplierPriceListFile(Update); if (ret) { return(Ok(ret)); } else { return(NotFound()); } } catch { return(NotFound()); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="loginId">登录id</param> public LoginLogHandler(string loginId) : base(LogMode.LoginLog) { AuthorizationUser currentUser = null; var current = HttpContextHelper.Current; if (current != null) { currentUser = AuthenticationHelper.Current(); } if (currentUser == null) { currentUser = new AuthorizationUser() { RealName = "匿名用户" }; } var request = current.Request; LogInfo = new LoginLog { LoginId = loginId, CreateAccountId = currentUser.AccountId, ServerHost = HttpHelper.GetServerIp(), ClientHost = HttpHelper.GetClientIp(), UserAgent = HttpHelper.UserAgent(), OsVersion = HttpHelper.GetOsVersion(), LoginTime = DateTime.Now, IpAddressName = HttpHelper.GetAddressByApi() }; }
public async Task <JsonResult> Login(string userName, string password, string code) { OperateResult <string> result = new OperateResult <string>(); string verifyCode = HttpContext.Session.GetString("VerifyCode"); if (verifyCode == null) { result.Message = "验证码已过期"; } else if (code.ToLower() != verifyCode.ToString().ToLower()) { result.Message = "验证码有误"; } else { //清除验证码 HttpContext.Session.Remove("VerifyCode"); var operateResult = _sysAccountService.Login(userName, password); AuthorizationUser auth = operateResult.Data; if (auth != null) { await AuthenticationHelper.SetAuthCookie(auth); result.Status = ResultStatus.Success; result.Data = "/Main/Home/Index"; #region 记录登录日志 LoginLogHandler loginLog = new LoginLogHandler(auth.LoginId); loginLog.WriteLog(); #endregion } result.Message = operateResult.Message; } return(Json(result)); }
private void ExecuteSecuredOperation(string userId) { string operation = "operation"; using (var s = store.OpenSession()) { AuthorizationUser user = new AuthorizationUser { Id = userId, Name = "Name" }; user.Permissions = new List <OperationPermission> { new OperationPermission { Allow = true, Operation = operation } }; s.Store(user); s.SaveChanges(); } using (var s = store.OpenSession()) { var authorizationUser = s.Load <AuthorizationUser>(userId); Assert.True(AuthorizationClientExtensions.IsAllowed(s, authorizationUser, operation)); } }
public IHttpActionResult UpdatePreparationPriceList(object obj) { AuthorizationUser AuUser = new AuthorizationUser(); Bis.PreparationPriceListMethod BisPreparationPriceList = new Bis.PreparationPriceListMethod(); try { JObject JsonObject = JObject.Parse(obj.ToString()); JsonObject.Add("IDPersonel", AuUser.ReturnIDUser(JsonObject["IDLogUser"].ToString().StringToGuid())); ViewModel.tblPreparationPriceList update = JsonObject.ToObject <ViewModel.tblPreparationPriceList>(); bool ret = BisPreparationPriceList.UpdatePreparationPriceList(update); if (ret) { return(Ok(ret)); } else { return(NotFound()); } } catch { return(NotFound()); } }
public ExecuteSqlLogHandler(string sql, string parm) : base(LogMode.SqlLog) { AuthorizationUser currentUser = null; var current = HttpContextHelper.Current; if (current != null) { currentUser = AuthenticationHelper.Current(); } if (currentUser == null) { currentUser = new AuthorizationUser() { RealName = "匿名用户" }; } LogInfo = new ExecuteSqlLog() { SqlCommand = sql, Parameter = parm, CreateAccountId = currentUser.AccountId, CreateUserName = currentUser.RealName, CreatorTime = DateTime.Now }; stopwatch.Start(); }
public static async Task InitializeDefaultAdminisrator(UserManager <AuthorizationUser> userManager, RoleManager <IdentityRole> roleManager) { string adminEmail = "*****@*****.**"; string adminPassword = "******"; string adminUserName = "******"; if (await roleManager.FindByNameAsync("admin") == null) { await roleManager.CreateAsync(new IdentityRole("admin")); } if (await roleManager.FindByNameAsync("user") == null) { await roleManager.CreateAsync(new IdentityRole("user")); } if (await userManager.FindByNameAsync(adminEmail) == null) { AuthorizationUser admin = new AuthorizationUser { Email = adminEmail, UserName = adminUserName }; IdentityResult result = await userManager.CreateAsync(admin, adminPassword); if (result.Succeeded) { await userManager.AddToRoleAsync(admin, "admin"); } } }
public void DocumentWithoutPermissionWillBeFilteredOutSilentlyWithStreaming() { var rhinosCompany = new Company { Name = "Hibernating Rhinos" }; var secretCompany = new Company { Name = "Secret Co." }; var authorizationUser = new AuthorizationUser { Id = UserId, Name = "Ayende Rahien", }; var operation = "Company/Bid"; using (var s = store.OpenSession()) { s.Store(authorizationUser); s.Store(rhinosCompany); s.Store(secretCompany); var documentAuthorization = new DocumentAuthorization(); documentAuthorization.Permissions.Add(new DocumentPermission() { Allow = true, Operation = operation, User = UserId }); s.SetAuthorizationFor(rhinosCompany, documentAuthorization); // allow Ayende Rahien s.SetAuthorizationFor(secretCompany, new DocumentAuthorization()); // deny everyone s.SaveChanges(); } using (var s = store.OpenSession()) { s.SecureFor(UserId, operation); var results = 0; using (var it = s.Advanced.Stream <Company>("companies/")) { while (it.MoveNext()) { results++; } } Assert.Equal(2, results); } }
public IHttpActionResult AddPeyvastPriceFile() { AuthorizationUser AuUser = new AuthorizationUser(); Bis.PeyvastPriceFileMethod BisPeyvastPrice = new Bis.PeyvastPriceFileMethod(); try { var File = HttpContext.Current.Request.Files["excelFileUploadPeyvastPrice"]; string FileType = File.FileName.Substring(File.FileName.LastIndexOf(".")); var IDPeyvastPriceFile = HttpContext.Current.Request["IDPeyvastPriceFile"]; var IDLogUser = HttpContext.Current.Request["IDLogUser"]; var TitlePeyvastPrice = HttpContext.Current.Request["TitlePeyvastPrice"]; var IDSupplier = HttpContext.Current.Request["IDSupplier"]; var IDCurrency = HttpContext.Current.Request["IDCurrency"]; var OrigDate = HttpContext.Current.Request["OrigDate"]; var ExcelJsonPeyvastPrice = HttpContext.Current.Request["ExcelJsonPeyvastPrice"]; ViewModel.tblPeyvastPriceFile Add = new ViewModel.tblPeyvastPriceFile(); Add.IDPeyvastPriceFile = IDPeyvastPriceFile.ToString().StringToGuid(); Add.IDPersonel = AuUser.ReturnIDUser(IDLogUser.ToString().StringToGuid()); Add.IDSupplier = IDSupplier.ToString().StringToGuid(); Add.IDCurrency = IDCurrency.ToString().StringToGuid(); Add.Title = TitlePeyvastPrice.ToString(); Add.OrigDate = OrigDate.ToString().StringToDateTime(); Add.FileSizeExcel = File.ContentLength; //byte Add.FileUrlExcel = @"File\AttachCrm\" + Add.IDPeyvastPriceFile + "@" + File.FileName; Add.ExcelJsonPeyvastPrice = ExcelJsonPeyvastPrice.ToString(); bool ret = BisPeyvastPrice.AddPeyvastPriceFile(Add); if (ret) { try { File.SaveAs(AppDomain.CurrentDomain.BaseDirectory + Add.FileUrlExcel); return(Ok(ret)); } catch (Exception) { ViewModel.tblPeyvastPriceFile delete = new ViewModel.tblPeyvastPriceFile(); delete.IDPeyvastPriceFile = Add.IDPeyvastPriceFile; bool ret2 = BisPeyvastPrice.DeletePeyvastPriceFile(delete); return(NotFound()); } } else { return(NotFound()); } } catch { return(NotFound()); } }
public void DocumentWithoutPermissionWillBeFilteredOutSilentlyWithQueryStreaming() { new CompanyIndex().Execute(store); var rhinosCompany = new Company { Name = "Hibernating Rhinos" }; var secretCompany = new Company { Name = "Secret Co." }; var authorizationUser = new AuthorizationUser { Id = UserId, Name = "Ayende Rahien", }; var operation = "Company/Bid"; using (var s = store.OpenSession()) { s.Store(authorizationUser); s.Store(rhinosCompany); s.Store(secretCompany); var documentAuthorization = new DocumentAuthorization(); documentAuthorization.Permissions.Add(new DocumentPermission() { Allow = true, Operation = operation, User = UserId }); s.SetAuthorizationFor(rhinosCompany, documentAuthorization); // allow Ayende Rahien s.SetAuthorizationFor(secretCompany, new DocumentAuthorization()); // deny everyone s.SaveChanges(); } WaitForIndexing(store); using (var s = store.OpenSession()) { s.SecureFor(UserId, operation); var expected = s.Advanced.LuceneQuery <Company, CompanyIndex>().ToList().Count(); var results = QueryExtensions.StreamAllFrom(s.Advanced.LuceneQuery <Company, CompanyIndex>(), s); Assert.Equal(expected, results.Count()); } }
public ActionResult LogInUser() { object respond; string pass = (string)Request.Params["password"]; string username = (string)Request.Params["username"]; if (string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(username)) { respond = new { tittle = "Login user", message = "Login user", option = "Login", errorMessage = "Please complete all fields." }; return(View("401", respond, "login")); } Model.Repository.UserRepository userRepository = new Model.Repository.UserRepository(); Model.Entities.User user = userRepository.Login(username, pass); if (!string.IsNullOrEmpty(user.username)) { string tokenGenerated = Session.GenerateToken(user.username, user.password, secretWord); authorizationUser = new AuthorizationUser(user.username, user.password, secretWord); respond = new { tittle = "Pick Url", token = tokenGenerated, idUser = user.id, option = "Sign Out", message = "Welcome to Pick Url.", userLogged = user.firstName }; return(View("200", respond, "index")); } else { respond = new { tittle = "Login user", message = "Login user", option = "Login", errorMessage = "Passwod or Username incorrect." }; return(View("401", respond, "login")); } }
public ExceptionLogHandler(Exception exception) : base(LogMode.ExceptionLog) { AuthorizationUser currentUser = null; var current = HttpContextHelper.Current; if (current != null) { currentUser = AuthenticationHelper.Current(); } if (currentUser == null) { currentUser = new AuthorizationUser() { RealName = "匿名用户" }; } LogInfo = new ExceptionLog { CreatorTime = DateTime.Now, Message = exception.Message, StackTrace = exception.StackTrace, ExceptionType = exception.GetType().FullName, CreateUserName = currentUser.RealName, CreateaAcountId = currentUser.AccountId, ServerHost = HttpHelper.GetServerIp(), ClientHost = HttpHelper.GetClientIp(), Runtime = "Web" }; //获取请求信息 var request = HttpContextHelper.Current.Request; LogInfo.RequestUrl = request.GetAbsoluteUri(); LogInfo.HttpMethod = request.Method; LogInfo.UserAgent = HttpHelper.UserAgent(); var inputStream = request.Body; var streamReader = new StreamReader(inputStream); var requestData = HttpUtility.UrlDecode(streamReader.ReadToEnd()); //读取完数据流后重置当前流的位置(很重要) //request.Body.Position = 0; LogInfo.RequestData = requestData; LogInfo.InnerException = NLogger.GetExceptionFullMessage(exception.InnerException); }
public async Task <JsonResult> SignOut() { AuthorizationUser user = AuthenticationHelper.Current(); if (user != null) { SysLoginLog log = _sysLoginLogService.FindEntity(user.LoginId); if (log != null) { log.SignOutTime = DateTime.Now; TimeSpan ts = log.SignOutTime.Value - log.LoginTime; log.StandingTime = ts.TotalMinutes; await _sysLoginLogService.UpdateAsync(log); } } await AuthenticationHelper.SignOut(); return(Json(new OperateResult("退出成功", ResultStatus.SignOut))); }
private void ExecuteSecuredOperation(string userId) { string operation = "operation"; using (var s = store.OpenSession()) { AuthorizationUser user = new AuthorizationUser { Id = userId, Name = "Name" }; user.Permissions = new List<OperationPermission> { new OperationPermission {Allow = true, Operation = operation} }; s.Store(user); s.SaveChanges(); } using (var s = store.OpenSession()) { var authorizationUser = s.Load<AuthorizationUser>(userId); Assert.True(AuthorizationClientExtensions.IsAllowed(s, authorizationUser, operation)); } }
public async Task <IActionResult> Registration(Models.Authorization.Validation.AuthorisationUserView userInfo) { if (_userManager != null) { if (userInfo != null && TryValidateModel(userInfo)) { var user = new AuthorizationUser { UserName = userInfo.UserName, Email = userInfo.Email }; var resultOfCreating = await _userManager.CreateAsync(user, userInfo.Password); if (resultOfCreating.Succeeded) { await _userManager.AddToRoleAsync(user, "user"); await _signInManager.SignInAsync(user, false); return(RedirectToAction("Index", "Home")); } else { foreach (var valError in resultOfCreating.Errors) { ModelState.AddModelError(string.Empty, valError.Description); } return(View(userInfo)); } } else { return(View(userInfo)); } } else { throw new NullReferenceException("Identity User Manager is not exist in current services"); } }
public static bool IsAllowed( this IDocumentSession session, AuthorizationUser user, string operation) { if (session == null) { throw new ArgumentNullException("session"); } if (user == null) { throw new ArgumentNullException("user"); } if (operation == null) { throw new ArgumentNullException("operation"); } IEnumerable <IPermission> permissions = from permission in user.Permissions ?? new List <OperationPermission>() // permissions for user / role directly on document where OperationMatches(permission.Operation, operation) select permission; session.Load <AuthorizationRole>(user.Roles.Where(roleId => session.Advanced.IsLoaded(roleId) == false)); permissions = permissions.Concat( from roleId in user.Roles let role = session.Load <AuthorizationRole>(roleId) where role != null from permission in role.Permissions ?? new List <OperationPermission>() where OperationMatches(permission.Operation, operation) select permission ); IEnumerable <IPermission> orderedPermissions = permissions.OrderByDescending(x => x.Priority).ThenBy(x => x.Allow); var decidingPermission = orderedPermissions.FirstOrDefault(); return(decidingPermission != null && decidingPermission.Allow); }
public IHttpActionResult AddAllQouationDetail(object obj) { try { AuthorizationUser AuUser = new AuthorizationUser(); Bis.QouationDetailMethod BisQouationDetail = new Bis.QouationDetailMethod(); ViewModel.tblQouationDetail getQouationDetail = new ViewModel.tblQouationDetail(); JObject JsonObject = JObject.Parse(obj.ToString()); getQouationDetail.AllDetailJson = JsonObject["AllDetailJson"].ToString(); getQouationDetail.IDQouationFile = JsonObject["IDQouationFile"].ToString().StringToGuid(); getQouationDetail.IDPersonel = AuUser.ReturnIDUser(JsonObject["IDLogUser"].ToString().StringToGuid()); getQouationDetail.RatioChfToEu = JsonObject["RatioChfToEu"].ToString().StringToDecimal(); bool JsonQouation = BisQouationDetail.AddAllQouationDetail(getQouationDetail); return(Ok(JsonQouation)); } catch { return(NotFound()); } }
private static bool DocumentPermissionMatchesUser(DocumentPermission permission, AuthorizationUser user, string userId) { if (permission.User != null) { return(string.Equals(permission.User, userId, StringComparison.InvariantCultureIgnoreCase)); } if (permission.Role == null) { return(false); } return(GetHierarchicalNames(user.Roles).Any(role => permission.Role.Equals(role, StringComparison.InvariantCultureIgnoreCase))); }
private static bool DocumentPermisionMatchesUser(DocumentPermission permission, AuthorizationUser user, string userId) { if (permission.User != null) { return(permission.User == userId); } if (permission.Role == null) { return(false); } return(GetHierarchicalNames(user.Roles).Any(role => permission.Role == role)); }
private static void ExplainWhyUserCantAccessTheDocument(Action <string> logger, string documentId, string userId, AuthorizationUser user, DocumentAuthorization documentAuthorization, string operation) { var sb = new StringBuilder("Could not find any permissions for operation: ") .Append(operation) .Append(" on ") .Append(documentId) .Append(" for user ") .Append(userId) .Append("."); if (user.Roles.Count > 0) { sb.Append(" or the user's roles: [") .Append(string.Join(", ", user.Roles)) .Append("]"); } sb.AppendLine(); if (documentAuthorization.Permissions.Count(x => x.Operation.Equals(operation, StringComparison.InvariantCultureIgnoreCase)) == 0) { sb.Append("No one may perform operation ") .Append(operation) .Append(" on ") .Append(documentId); } else { sb.Append("Only the following may perform operation ") .Append(operation) .Append(" on ") .Append(documentId) .AppendLine(":"); foreach (var documentPermission in documentAuthorization.Permissions) { sb.Append("\t") .Append(documentPermission.Explain) .AppendLine(); } } logger(sb.ToString()); }
public IHttpActionResult UpdateQouationFile(object obj) { try { AuthorizationUser AuUser = new AuthorizationUser(); Bis.QouationFileMethod BisQouation = new Bis.QouationFileMethod(); ViewModel.tblQouationFile update = new ViewModel.tblQouationFile(); JObject JsonObject = JObject.Parse(obj.ToString()); update.IDQouationFile = JsonObject["IDQouationFile"].ToString().StringToGuid(); update.IDPersonel = AuUser.ReturnIDUser(JsonObject["IDLogUser"].ToString().StringToGuid()); update.Title = JsonObject["Title"].ToString(); update.IDSupplier = JsonObject["IDSupplier"].ToString().StringToGuid(); update.IDCurrency = JsonObject["IDCurrency"].ToString().StringToGuid(); //update.OrigDate = DateTime.Parse(JsonObject["OrigDate"].ToString()); update.OrigDate = JsonObject["OrigDate"].ToString().StringToDateTime(); if (JsonObject["NewFileUrlEmail"] == null) //zamane update fili entekhab nashode ast { if (JsonObject["OldFileUrlEmail"] != null) //dar lahze aval fili sabt shode ast { update.FileUrlEmail = JsonObject["OldFileUrlEmail"].ToString(); update.FileSizeEmail = JsonObject["OldFileSizeEmail"].ToString().StringToInt(); } } else { File.Delete(AppDomain.CurrentDomain.BaseDirectory + JsonObject["OldFileUrlEmail"].ToString()); byte[] FileByte = Convert.FromBase64String(JsonObject["NewFileUrlEmail"].ToString().Split(',')[1]); MemoryStream ms = new MemoryStream(FileByte, 0, FileByte.Length); ms.Write(FileByte, 0, FileByte.Length); FileTypes ft = new FileTypes(); string FileType = ft.FindFileTypeInString(JsonObject["NewFileUrlEmail"].ToString().Split(',')[0]); if (FileByte.Length > 0) { string FileUrl = ""; string TitleQoutationEmailFile = JsonObject["TitleQoutationEmailFile"].ToString(); FileUrl = @"File\AttachCrm\" + Guid.NewGuid() + "@" + TitleQoutationEmailFile.Split('.')[0]; update.FileUrlEmail = FileUrl; update.FileSizeEmail = FileByte.Length; try { File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + FileUrl + FileType, FileByte); } catch (Exception) { throw; } } } bool ret = BisQouation.UpdateQouationFile(update); if (ret) { return(Ok(ret)); } else { return(NotFound()); } } catch { return(NotFound()); } }
public IHttpActionResult AddQouationFile() { AuthorizationUser AuUser = new AuthorizationUser(); Bis.QouationFileMethod BisQouation = new Bis.QouationFileMethod(); try { ViewModel.tblQouationFile Add = new ViewModel.tblQouationFile(); bool ExcelModeQouation = HttpContext.Current.Request["ExcelModeQouation"].ToString().StringToBool(); var PdfFile = HttpContext.Current.Request.Files["pdfFileUploadQouation"]; var IDQouationFile = HttpContext.Current.Request["IDQouationFile"]; var IDLogUser = HttpContext.Current.Request["IDLogUser"]; var TitleQouation = HttpContext.Current.Request["TitleQouation"]; var IDSupplier = HttpContext.Current.Request["IDSupplier"]; var IDCurrency = HttpContext.Current.Request["IDCurrency"]; var OrigDate = HttpContext.Current.Request["OrigDate"]; var EmailFile = HttpContext.Current.Request.Files["EmailFileUploadQouation"]; Add.IDQouationFile = IDQouationFile.ToString().StringToGuid(); Add.IDPersonel = AuUser.ReturnIDUser(IDLogUser.ToString().StringToGuid()); Add.IDSupplier = IDSupplier.ToString().StringToGuid(); Add.IDCurrency = IDCurrency.ToString().StringToGuid(); Add.Title = TitleQouation.ToString(); Add.OrigDate = OrigDate.ToString().StringToDateTime(); Add.FileSizePdf = PdfFile.ContentLength; //byte Add.FileUrlPdf = @"File\AttachCrm\" + Add.IDQouationFile + "@" + PdfFile.FileName; if (EmailFile != null) { Add.FileSizeEmail = EmailFile.ContentLength; //byte Add.FileUrlEmail = @"File\AttachCrm\" + Add.IDQouationFile + "@" + EmailFile.FileName; } bool ret = false; if (ExcelModeQouation) { var ExcelFile = HttpContext.Current.Request.Files["excelFileUploadQouation"]; var ExcelJsonQouation = HttpContext.Current.Request["ExcelJsonQouation"]; Add.FileSizeExcel = ExcelFile.ContentLength; //byte Add.FileUrlExcel = @"File\AttachCrm\" + Add.IDQouationFile + "@" + ExcelFile.FileName; Add.ExcelJsonQouation = ExcelJsonQouation.ToString(); Add.ExcelMode = true; ret = BisQouation.AddQouationFileWithExcel(Add); if (ret) { try { ExcelFile.SaveAs(AppDomain.CurrentDomain.BaseDirectory + Add.FileUrlExcel); PdfFile.SaveAs(AppDomain.CurrentDomain.BaseDirectory + Add.FileUrlPdf); if (EmailFile != null) { EmailFile.SaveAs(AppDomain.CurrentDomain.BaseDirectory + Add.FileUrlEmail); } return(Ok(ret)); } catch (Exception) { ViewModel.tblQouationFile delete = new ViewModel.tblQouationFile(); delete.IDQouationFile = Add.IDQouationFile; bool ret2 = BisQouation.DeleteQouationFile(delete); return(NotFound()); } } else { return(NotFound()); } } else { Add.ExcelMode = false; ret = BisQouation.AddQouationFileWithOutExcel(Add); if (ret) { try { PdfFile.SaveAs(AppDomain.CurrentDomain.BaseDirectory + Add.FileUrlPdf); if (EmailFile != null) { EmailFile.SaveAs(AppDomain.CurrentDomain.BaseDirectory + Add.FileUrlEmail); } return(Ok(ret)); } catch (Exception) { ViewModel.tblQouationFile delete = new ViewModel.tblQouationFile(); delete.IDQouationFile = Add.IDQouationFile; bool ret2 = BisQouation.DeleteQouationFile(delete); return(NotFound()); } } else { return(NotFound()); } } } catch { return(NotFound()); } }
public void CanNotGetMessagesForRecipientWhenNotInRole() { List <WallMessage <AuthorizationUser> > messages; RavenQueryStatistics stats; var requester = new AuthorizationUser { Name = "requester", Id = "AuthorizationUsers-2" }; var sender = new AuthorizationUser { Name = "sender", Id = "AuthorizationUsers-3" }; var recipient = new AuthorizationUser { Name = "recipient", Id = "AuthorizationUsers-1" }; var wallMessage = new WallMessage <AuthorizationUser> { Id = "WallMessageOfAuthorizationUsers-1", Creator = sender, Recipient = recipient, MessageBody = "blah" }; new MessagesForAccountByCreatorId().Execute(store); using (var session = store.OpenSession()) { session.Store(recipient); session.Store(requester); session.Store(sender); session.Store(wallMessage); session.SaveChanges(); //set view permissions only for recipient and sender session.SetAuthorizationFor(wallMessage, new DocumentAuthorization { Permissions = { new DocumentPermission { Role = "Authorization/Roles/FriendsOf/" + wallMessage.Recipient.Id, Allow = true, Operation = "WallMessage/View" }, new DocumentPermission { Allow = true, Operation = "WallMessage/View", User = wallMessage.Recipient.Id } } }); session.SaveChanges(); } using (var session = store.OpenSession()) { session.SecureFor(requester.Id, "WallMessage/View"); messages = session.Query <WallMessage <AuthorizationUser> >().TransformWith <MessagesForAccountByCreatorId, WallMessage <AuthorizationUser> >() .Statistics(out stats) .Customize(x => x.WaitForNonStaleResultsAsOfNow()) .Where(x => x.Recipient.Id == recipient.Id) .ToList(); } Assert.True(messages.Count == 0); }
public void CanNotGetMessagesForRecipientWhenNotInRole() { List<WallMessage<AuthorizationUser>> messages; RavenQueryStatistics stats; var requester = new AuthorizationUser { Name = "requester", Id = "AuthorizationUsers-2" }; var sender = new AuthorizationUser { Name = "sender", Id = "AuthorizationUsers-3" }; var recipient = new AuthorizationUser { Name = "recipient", Id = "AuthorizationUsers-1" }; var wallMessage = new WallMessage<AuthorizationUser> { Id = "WallMessageOfAuthorizationUsers-1", Creator = sender, Recipient = recipient, MessageBody = "blah" }; new MessagesForAccountByCreatorId().Execute(store); using (var session = store.OpenSession()) { session.Store(recipient); session.Store(requester); session.Store(sender); session.Store(wallMessage); session.SaveChanges(); //set view permissions only for recipient and sender session.SetAuthorizationFor(wallMessage, new DocumentAuthorization { Permissions = { new DocumentPermission { Role = "Authorization/Roles/FriendsOf/" + wallMessage.Recipient.Id, Allow = true, Operation = "WallMessage/View" }, new DocumentPermission { Allow = true, Operation = "WallMessage/View", User = wallMessage.Recipient.Id } } }); session.SaveChanges(); } using (var session = store.OpenSession()) { session.SecureFor(requester.Id, "WallMessage/View"); messages = session.Query<WallMessage<AuthorizationUser>>().TransformWith<MessagesForAccountByCreatorId, WallMessage<AuthorizationUser>>() .Statistics(out stats) .Customize(x => x.WaitForNonStaleResultsAsOfNow()) .Where(x => x.Recipient.Id == recipient.Id) .ToList(); } Assert.True(messages.Count == 0); }