/* /// <summary> /// Initializes a new instance of the FacebookLayer class /// </summary> public FacebookLayer() { this.Auth = new Authorizer(); if (this.Auth.Authorize()) { this.FbClient = new FacebookClient(CurrentSession.AccessToken); this.User = new FacebookUser(); try { var me = (IDictionary<string, object>) this.FbClient.Get("me"); this.User.FacebookId = (string) me["id"]; this.User.FacebookName = (string) me["first_name"]; } catch { this.IsAccessTokenValid = false; return; } this.IsAccessTokenValid = true; IDictionary<string, object> friendsData = (IDictionary<string, object>) this.FbClient.Get("me/friends"); this.facebookData = new FacebookData(this.User, friendsData); this.SortedFriends = this.facebookData.SortedFriends; } } */ /// <summary> /// Initializes a new instance of the FacebookLayer class using authorization /// </summary> /// <param name="auth">authorization instance</param> public FacebookLayer(Authorizer auth) { this.Auth = auth; if (auth.Authorize()) { this.FbClient = new FacebookClient(CurrentSession.AccessToken); this.User = new FacebookUser(); try { var me = (IDictionary<string, object>) this.FbClient.Get("me"); this.User.FacebookId = (string) me["id"]; this.User.FacebookName = (string) me["first_name"]; } catch { this.IsAccessTokenValid = false; return; } this.IsAccessTokenValid = true; IDictionary<string, object> friendsData = (IDictionary<string, object>)FbClient.Get("me/friends"); facebookData = new FacebookData(User, (IList<object>)friendsData["data"]); } }
/// <summary> /// Loads page /// </summary> /// <param name="sender">sender information</param> /// <param name="e">event information</param> protected void Page_Load(object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("p3p", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""); Authorizer auth = new Authorizer { Perms = "publish_stream" }; if (auth.Authorize()) { FacebookLayer fb = new FacebookLayer(auth); if (Request.QueryString["action"] != null) { this.LocationActions(Request.QueryString, fb); } this.ShowFacebookContent(fb); } else { Response.Redirect("~/Login.aspx?returnUrl=" + HttpUtility.UrlEncode(Request.Url.PathAndQuery)); } }
public void GettingAuthorization_Initially_ReturnsUnknown() { var test = new Authorizer(Substitute.For<ITwitterApplicationCredentials>(), Substitute.For<IAccessTokenStore>(), x => A.User); test.AuthorizationStatus.Should().Equal(AuthorizationStatus.Unknown); }
public void InjectedAuthorizerIsResolved() { var config = new EngineConfiguration(); var expected = new Authorizer(); config.SetAuthorizerFactory((c) => expected); var actual = config.CreateAuthorizer(); Assert.AreSame(expected,actual); }
public void Super_class_matches() { var target = new Authorizer(); target.SetHandler<object>((c, p) => true); var cmd = new AppendNumberCommand(42); Assert.AreEqual(typeof(Object), target.GetTypeKey(cmd.GetType())); Assert.IsTrue(target.Allows(cmd, Thread.CurrentPrincipal)); }
/// <summary> /// loads LoginPage if user is aloready logged in redirect to default.aspx /// </summary> /// <param name="sender">sender information</param> /// <param name="e">event information</param> protected void Page_Load(object sender, EventArgs e) { var authorizer = new Authorizer {Perms = "publish_stream"}; if (authorizer.IsAuthorized()) { Response.Redirect(HttpUtility.UrlDecode(Request.QueryString["returnUrl"] ?? "/")); } }
private void StartApplication_Load(object sender, EventArgs e) { IAuthorizer authorizer = new Authorizer(); LoginProviderWinForm loginProvider = new LoginProviderWinForm(authorizer); AuthorizationResult = loginProvider.Login(); if (AuthorizationResult.Authorized) { PrepareApplication(); } else { Application.Exit(); } }
public void ThrowExceptionGivenUserIsNotAuthorized() { // Arrange var authorizationProvider = new Mock<IAuthorizationProvider>(); authorizationProvider.Setup(x => x.Authorize(It.IsAny<AuthorizationRequest>())).Returns(false); var authorizer = new Authorizer(authorizationProvider.Object); var user = new User("testuser", "Test", "User"); var application = new Application("FakeApplication"); var activity = new Activity("FakeActivity", application); // Act var result = authorizer.Will.ThrowAccessDeniedException().When.User(user).Can.Not.ExecuteAnyOfTheseActivities(new[] { activity }).In(application); // Assert Assert.IsTrue(result); }
public void ReturnFalseGivenUserIsAuthorizedWhenInverted() { // Arrange var authorizationProvider = new Mock<IAuthorizationProvider>(); authorizationProvider.Setup(x => x.Authorize(It.IsAny<AuthorizationRequest>())).Returns(true); var authorizer = new Authorizer(authorizationProvider.Object); var user = new User("testuser", "Test", "User"); var application = new Application("FakeApplication"); var activity = new Activity("FakeActivity", application); // Act var result = authorizer.Will.Assert.User(user).Can.Not.ExecuteAnyOfTheseActivities(new[] { activity }).In(application); // Assert Assert.IsFalse(result); }
private static void Main(string[] args) { /*Run().Wait(); //System.Console.WriteLine(client.accessToken.Secret); GetBalance().Wait();*/ /*var expires = Convert.ToDateTime("2013-08-25 11:12:55"); var difference = (expires - DateTime.Now); if (int.Parse(difference.TotalDays.ToString().Split('.')[0]) > 0) { System.Console.WriteLine("Remaining: " + difference.TotalDays.ToString().Split('.')[0] + " days"); } else if(int.Parse(difference.TotalHours.ToString().Split('.')[0]) > 0) { System.Console.WriteLine("Remaining: " + difference.TotalHours.ToString().Split('.')[0] + " hours"); } else if (int.Parse(difference.TotalMinutes.ToString().Split('.')[0]) > 0) { System.Console.WriteLine("Remaining: " + difference.TotalMinutes.ToString().Split('.')[0] + " minutes"); } else { string value = int.Parse(difference.TotalSeconds.ToString().Split('.')[0]) > 0 ? difference.TotalSeconds.ToString().Split('.')[0] : "expired"; System.Console.WriteLine("Remaining: " + value +" seconds"); }*/ /*var try1 = ((Convert.ToDateTime("2013-09-08 07:12:34") - DateTime.Now).TotalDays / (Convert.ToDateTime("2013-09-08 07:12:34").AddMonths(-1) - Convert.ToDateTime("2013-09-08 07:12:34")).Days) * 100d; var try2 = (((Convert.ToDateTime("2013-09-08 07:12:34") - Convert.ToDateTime("2013-09-08 07:12:34").AddMonths(-1)).Days - Math.Round((Convert.ToDateTime("2013-09-08 07:12:34") - DateTime.Now).TotalDays, 0)) / (Convert.ToDateTime("2013-09-08 07:12:34") - Convert.ToDateTime("2013-09-08 07:12:34").AddMonths(-1)).Days) * 100d; System.Console.WriteLine("total days: " + (Convert.ToDateTime("2013-09-08 07:12:34") - Convert.ToDateTime("2013-09-08 07:12:34").AddMonths(-1)).Days); System.Console.WriteLine("passed: " + ((Convert.ToDateTime("2013-09-08 07:12:34") - Convert.ToDateTime("2013-09-08 07:12:34").AddMonths(-1)).Days - Math.Round((Convert.ToDateTime("2013-09-08 07:12:34") - DateTime.Now).TotalDays, 0))); System.Console.WriteLine( try1); System.Console.WriteLine(); System.Console.WriteLine(try2);*/ /*int minutes = 3592/60; int seconds = 3592%60; System.Console.WriteLine("{0}m {1}s", minutes, seconds); System.Console.ReadKey();*/ Authorizer auth = new Authorizer(); }
/// <summary> /// 是否具有管理Topic的权限 /// </summary> /// <param name="authorizer"></param> /// <param name="groupId"></param> /// <returns></returns> public static bool Topic_Manage(this Authorizer authorizer, long groupId) { TopicEntity group = new TopicService().Get(groupId); return(Topic_Manage(authorizer, group)); }
/// <summary> /// 是否具有管理BarSection的权限 /// </summary> /// <param name="authorizer"></param> /// <param name="barSectionId"></param> /// <returns></returns> public static bool BarSection_Manage(this Authorizer authorizer, long barSectionId) { BarSection section = new BarSectionService().Get(barSectionId); return(BarSection_Manage(authorizer, section)); }
public void GuestCanWrite() { Assert.True(Authorizer.IsAuthorized("neo.global.write", guestPermissions)); }
public void GuestCantJoinChannelWithoutPassword() { Assert.False(Authorizer.IsAuthorized("neo.channel.join.ignorepassword", guestPermissions)); }
public void AcceptsNullPrincipal() { var target = new Authorizer(); Assert.DoesNotThrow(() => target.Allows(new object(), null)); }
public IResponse HandleRequest(IRequest request) { if (Authorizer != null && !IPAddress.IsLoopback(request.RemoteEndpoint.Address) && !Authorizer.Authorize( request.Headers, request.RemoteEndpoint, IP.GetMAC(request.RemoteEndpoint.Address) )) { throw new HttpStatusException(HttpCode.Denied); } var path = request.Path.Substring(Prefix.Length); Debug(path); if (path == "description.xml") { return(new StringResponse( HttpCode.Ok, "text/xml", GenerateDescriptor(request.LocalEndPoint.Address) )); } if (path == "contentDirectory.xml") { return(new ResourceResponse( HttpCode.Ok, "text/xml", "contentdirectory" )); } if (path == "connectionManager.xml") { return(new ResourceResponse( HttpCode.Ok, "text/xml", "connectionmanager" )); } if (path == "MSMediaReceiverRegistrar.xml") { return(new ResourceResponse( HttpCode.Ok, "text/xml", "MSMediaReceiverRegistrar" )); } if (path == "control") { return(ProcessSoapRequest(request)); } if (path.StartsWith("file/", StringComparison.Ordinal)) { var id = path.Split('/')[1]; var item = GetItem(id) as IMediaResource; InfoFormat("{0}", request.RemoteEndpoint.Address + " : " + item.Path); return(new ItemResponse(Prefix, request, item)); } if (path.StartsWith("cover/", StringComparison.Ordinal)) /* * var id = path.Split('/')[1]; * InfoFormat("Serving cover {0}", id); * var item = GetItem(id) as IMediaCover; * if (item == null) { * throw new HttpStatusException(HttpCode.NotFound); * } * return new ItemResponse(Prefix, request, item.Cover, "Interactive"); */ { throw new HttpStatusException(HttpCode.NotFound); } if (path.StartsWith("subtitle/", StringComparison.Ordinal)) { var id = path.Split('/')[1]; var item = GetItem(id) as IMetaVideoItem; InfoFormat("{0}", request.RemoteEndpoint.Address + " : " + item.Subtitle.Path); if (item == null) { throw new HttpStatusException(HttpCode.NotFound); } return(new ItemResponse(Prefix, request, item.Subtitle, "Background")); } if (string.IsNullOrEmpty(path) || path == "index.html") { return(new Redirect(request, Prefix + "index/0")); } if (path.StartsWith("index/", StringComparison.Ordinal)) { var id = path.Substring("index/".Length); var item = GetItem(id); return(ProcessHtmlRequest(item)); } if (request.Method == "SUBSCRIBE") { var res = new StringResponse(HttpCode.Ok, string.Empty); res.Headers.Add("SID", $"uuid:{Guid.NewGuid()}"); res.Headers.Add("TIMEOUT", request.Headers["timeout"]); return(res); } if (request.Method == "UNSUBSCRIBE") { return(new StringResponse(HttpCode.Ok, string.Empty)); } WarnFormat("Did not understand {0} {1}", request.Method, path); throw new HttpStatusException(HttpCode.NotFound); }
private void AuthorizeRequest(AuthorizeRequest clientRequest) { Authorizer.Authorize(clientRequest); }
public void Setup() { _authorizer = new Authorizer(); }
private int SetAuthorizer(Context ctx, Authorizer authorizer, object arg) { ctx.Mutex.Enter(); ctx.Authorizer = authorizer; ctx.AuthorizerArg = arg; //ctx.ExpirePreparedStatements(); ctx.Mutex.Leave(); return (int)RC.OK; }
public bool CanCall(CallOptions options, string procedure) { return(Authorizer.CanCall(options, procedure)); }
public IResponse HandleRequest(IRequest request) { if (Authorizer != null && !IPAddress.IsLoopback(request.RemoteEndpoint.Address) && !Authorizer.Authorize( request.Headers, request.RemoteEndpoint, IP.GetMAC(request.RemoteEndpoint.Address) )) { throw new HttpStatusException(HttpCode.Denied); } var path = request.Path.Substring(prefix.Length); Debug(path); if (path == "description.xml") { return(new StringResponse( HttpCode.Ok, "text/xml", GenerateDescriptor(request.LocalEndPoint.Address) )); } if (path == "contentDirectory.xml") { return(new ResourceResponse( HttpCode.Ok, "text/xml", "contentdirectory" )); } if (path == "connectionManager.xml") { return(new ResourceResponse( HttpCode.Ok, "text/xml", "connectionmanager" )); } if (path == "MSMediaReceiverRegistrar.xml") { return(new ResourceResponse( HttpCode.Ok, "text/xml", "MSMediaReceiverRegistrar" )); } if (path == "control") { return(ProcessSoapRequest(request)); } if (path.StartsWith("file/", StringComparison.Ordinal)) { var id = path.Split('/')[1]; InfoFormat("Serving file {0}", id); var item = GetItem(id) as IMediaResource; return(new ItemResponse(prefix, request, item)); } if (path.StartsWith("cover/", StringComparison.Ordinal)) { var id = path.Split('/')[1]; InfoFormat("Serving cover {0}", id); var item = GetItem(id) as IMediaCover; return(new ItemResponse(prefix, request, item.Cover, "Interactive")); } if (path.StartsWith("subtitle/", StringComparison.Ordinal)) { var id = path.Split('/')[1]; InfoFormat("Serving subtitle {0}", id); var item = GetItem(id) as IMetaVideoItem; return(new ItemResponse(prefix, request, item.Subtitle, "Background")); } if (string.IsNullOrEmpty(path) || path == "index.html") { return(new Redirect(request, prefix + "index/0")); } if (path.StartsWith("index/", StringComparison.Ordinal)) { var id = path.Substring("index/".Length); var item = GetItem(id); return(ProcessHtmlRequest(item)); } if (request.Method == "SUBSCRIBE") { var res = new StringResponse(HttpCode.Ok, string.Empty); string notifySid; if (!request.Headers.TryGetValue("SID", out notifySid)) { notifySid = Guid.NewGuid().ToString(); } else { notifySid = notifySid.Remove(0, 5); } //string callback; Tuple <string, DateTime> subres; int timeout = System.Int32.Parse(request.Headers["timeout"].Remove(0, 7)); DateTime dtimeout = System.DateTime.Now.AddSeconds(timeout); if (!subscribers.TryGetValue(notifySid, out subres)) { if (request.Headers.ContainsKey("CALLBACK")) { string callback = request.Headers["CALLBACK"].Replace("<", "").Replace(">", ""); subscribers.Add(notifySid, new Tuple <string, DateTime>(callback, dtimeout)); Debug("Subscribe: " + notifySid + ": " + callback); } else { Error("SUBSCRIBE WTF: " + request.Headers); } } else { //RENEW subscribers[notifySid] = new Tuple <string, DateTime>(subres.Item1, dtimeout); } res.Headers.Add("SID", string.Format("uuid:{0}", notifySid)); res.Headers.Add("TIMEOUT", request.Headers["timeout"]); return(res); } if (request.Method == "UNSUBSCRIBE") { //TODO: remove from subscribers return(new StringResponse(HttpCode.Ok, string.Empty)); } WarnFormat("Did not understand {0} {1}", request.Method, path); throw new HttpStatusException(HttpCode.NotFound); }
/// <summary> /// 创建问题 /// </summary> public static bool Answer_Create(this Authorizer authorizer, AskQuestion question) { string errorMessage = string.Empty; return(authorizer.Answer_Create(question, out errorMessage)); }
/// <summary> /// 是否可以看到该贴吧 /// </summary> /// <param name="authorizer"></param> /// <param name="barSectionId"></param> /// <returns></returns> public static bool BarSection_View(this Authorizer authorizer, long barSectionId) { return(authorizer.BarSection_View(new BarSectionService().Get(barSectionId))); }
public bool CanSubscribe(SubscribeOptions options, string topicUri) { return(Authorizer.CanSubscribe(options, topicUri)); }
/// <summary> /// 是否具有创建BarThread的权限 /// </summary> /// <param name="authorizer"></param> /// <param name="sectionId">所属帖吧Id</param> /// <param name="errorMessage">无权信息提示</param> /// <returns></returns> public static bool BarThread_Create(this Authorizer authorizer, long sectionId, out string errorMessage) { errorMessage = string.Empty; IUser currentUser = UserContext.CurrentUser; if (currentUser == null) { errorMessage = "您需要先登录,才能发帖"; return(false); } BarSectionService barSectionService = new BarSectionService(); var barSection = barSectionService.Get(sectionId); if (barSection == null) { errorMessage = "贴吧不存在"; return(false); } if (authorizer.BarSection_Manage(barSection)) { return(true); } if (!authorizer.AuthorizationService.Check(currentUser, PermissionItemKeys.Instance().Bar_CreateThread())) { if (currentUser.IsModerated) { errorMessage = Resources.Resource.Description_ModeratedUser_CreateBarThreadDenied; } return(false); } if (barSection.TenantTypeId == TenantTypeIds.Instance().Bar()) { IBarSettingsManager barSettingsManager = DIContainer.Resolve <IBarSettingsManager>(); BarSettings barSetting = barSettingsManager.Get(); if (barSetting.OnlyFollowerCreateThread) { SubscribeService subscribeService = new SubscribeService(TenantTypeIds.Instance().BarSection()); if (subscribeService.IsSubscribed(sectionId, currentUser.UserId)) { return(true); } else { errorMessage = "您需要先关注此帖吧,才能发帖"; return(false); } } else { return(true); } } else { if (authorizer.AuthorizationService.IsTenantMember(currentUser, barSection.TenantTypeId, barSection.SectionId)) { return(true); } else { TenantType tenantType = new TenantTypeService().Get(barSection.TenantTypeId); errorMessage = string.Format("只有加入{0}才能发帖", tenantType.Name); return(false); } } }
/// <summary> /// 撰写日志/转载日志 /// 空间主人撰写空间用户的日志 /// </summary> public static bool BlogThread_Create(this Authorizer authorizer, string spaceKey) { string errorMessage = string.Empty; return(authorizer.BlogThread_Create(spaceKey, out errorMessage)); }
/// <summary> /// 是否具有删除BarThread的权限 /// </summary> /// <param name="threadId"></param> /// <returns></returns> public static bool BarThread_Delete(this Authorizer authorizer, long threadId) { BarThread thread = new BarThreadService().Get(threadId); return(authorizer.BarThread_Delete(thread)); }
public Replication GetReplicator(IDictionary <string, object> properties) { // TODO: in the iOS equivalent of this code, there is: {@"doc_ids", _documentIDs}) - write unit test that detects this bug // TODO: ditto for "headers" Authorizer authorizer = null; Replication repl = null; Uri remote = null; IDictionary <string, object> remoteMap; IDictionary <string, object> sourceMap = ParseSourceOrTarget(properties, "source"); IDictionary <string, object> targetMap = ParseSourceOrTarget(properties, "target"); string source = (string)sourceMap.Get("url"); string target = (string)targetMap.Get("url"); bool createTargetBoolean = (bool)properties.Get("create_target"); bool createTarget = (createTargetBoolean != null && createTargetBoolean); bool continuousBoolean = (bool)properties.Get("continuous"); bool continuous = (continuousBoolean != null && continuousBoolean); bool cancelBoolean = (bool)properties.Get("cancel"); bool cancel = (cancelBoolean != null && cancelBoolean); // Map the 'source' and 'target' JSON params to a local database and remote URL: if (source == null || target == null) { throw new CouchbaseLiteException("source and target are both null", new Status(Status .BadRequest)); } bool push = false; Database db = null; string remoteStr = null; if (Couchbase.Lite.Manager.IsValidDatabaseName(source)) { db = GetExistingDatabase(source); remoteStr = target; push = true; remoteMap = targetMap; } else { remoteStr = source; if (createTarget && !cancel) { bool mustExist = false; db = GetDatabaseWithoutOpening(target, mustExist); if (!db.Open()) { throw new CouchbaseLiteException("cannot open database: " + db, new Status(Status .InternalServerError)); } } else { db = GetExistingDatabase(target); } if (db == null) { throw new CouchbaseLiteException("database is null", new Status(Status.NotFound)); } remoteMap = sourceMap; } IDictionary <string, object> authMap = (IDictionary <string, object>)remoteMap.Get( "auth"); if (authMap != null) { IDictionary <string, object> persona = (IDictionary <string, object>)authMap.Get("persona" ); if (persona != null) { string email = (string)persona.Get("email"); authorizer = new PersonaAuthorizer(email); } IDictionary <string, object> facebook = (IDictionary <string, object>)authMap.Get("facebook" ); if (facebook != null) { string email = (string)facebook.Get("email"); authorizer = new FacebookAuthorizer(email); } } try { remote = new Uri(remoteStr); } catch (UriFormatException) { throw new CouchbaseLiteException("malformed remote url: " + remoteStr, new Status (Status.BadRequest)); } if (remote == null) { throw new CouchbaseLiteException("remote URL is null: " + remoteStr, new Status(Status .BadRequest)); } if (!cancel) { repl = db.GetReplicator(remote, GetDefaultHttpClientFactory(), push, continuous, GetWorkExecutor()); if (repl == null) { throw new CouchbaseLiteException("unable to create replicator with remote: " + remote , new Status(Status.InternalServerError)); } if (authorizer != null) { repl.SetAuthenticator(authorizer); } IDictionary <string, object> headers = (IDictionary)properties.Get("headers"); if (headers != null && !headers.IsEmpty()) { repl.SetHeaders(headers); } string filterName = (string)properties.Get("filter"); if (filterName != null) { repl.SetFilter(filterName); IDictionary <string, object> filterParams = (IDictionary <string, object>)properties .Get("query_params"); if (filterParams != null) { repl.SetFilterParams(filterParams); } } if (push) { ((Pusher)repl).SetCreateTarget(createTarget); } } else { // Cancel replication: repl = db.GetActiveReplicator(remote, push); if (repl == null) { throw new CouchbaseLiteException("unable to lookup replicator with remote: " + remote , new Status(Status.NotFound)); } } return(repl); }
/// <summary> /// 是否具有删除BarThread的权限 /// </summary> /// <param name="threadId"></param> /// <returns></returns> public static bool BarThread_Delete(this Authorizer authorizer, BarThread thread) { return(authorizer.BarThread_Edit(thread)); }
public IHttpActionResult Get(string login, string password) { var orderslist = db.Orders.ToList(); var userslist = db.Clients.ToList(); List <Order> reslist = new List <Order>(); foreach (var item in orderslist) { if (item.Nickname.Trim() == login.Trim()) //reslist.Add(item); { var tmpuser = userslist.Find(x => x.Login == login); if (tmpuser != null) { if (tmpuser.Password.Trim() == Authorizer.GetHashFromStringValue(Authorizer.DecryptStringByBase64(password), Authorizer.ServerSHAKey).Trim()) { reslist.Add(item); } } } } return(Ok(reslist)); }
/// <summary> /// 是否具有创建BarThread的权限 /// </summary> /// <param name="authorizer"></param> /// <param name="sectionId">所属帖吧Id</param> /// <returns></returns> public static bool BarPost_Create(this Authorizer authorizer, long sectionId) { string errorMessage = string.Empty; return(authorizer.BarPost_Create(sectionId, out errorMessage)); }
public bool AuthorizedFor(Permission permission, IContent content) { return(Authorizer.Authorize(permission, content)); }
/// <summary> /// 是否具有创建BarPost的权限 /// </summary> /// <param name="sectionId">所属帖吧Id</param> /// <returns></returns> public static bool BarPost_Create(this Authorizer authorizer, long sectionId, out string errorMessage) { IUser currentUser = UserContext.CurrentUser; errorMessage = "没有权限回帖"; BarSectionService barSectionService = new BarSectionService(); var barSection = barSectionService.Get(sectionId); if (barSection == null) { return(false); } if (barSection.AuditStatus != AuditStatus.Success) { errorMessage = "由于贴吧未经过审核,所以不允许发帖"; return(false); } if (!authorizer.AuthorizationService.Check(currentUser, PermissionItemKeys.Instance().Bar_CreatePost())) { if (currentUser != null && currentUser.IsModerated) { errorMessage = Resources.Resource.Description_ModeratedUser_CreateBarPostDenied; } return(false); } if (barSection.TenantTypeId == TenantTypeIds.Instance().Bar()) { //检查是否需要是关注用户才能发帖 IBarSettingsManager barSettingsManager = DIContainer.Resolve <IBarSettingsManager>(); BarSettings barSetting = barSettingsManager.Get(); if (barSetting.OnlyFollowerCreatePost) { if (currentUser == null) { errorMessage = "您需要先登录并关注此帖吧,才能回帖"; return(false); } SubscribeService subscribeService = new SubscribeService(TenantTypeIds.Instance().BarSection()); bool isSubscribed = subscribeService.IsSubscribed(sectionId, currentUser.UserId); if (!isSubscribed) { errorMessage = "您需要先关注此帖吧,才能回帖"; } return(isSubscribed); } } else { if (authorizer.BarSection_Manage(barSection)) { return(true); } bool isTenantMember = authorizer.AuthorizationService.IsTenantMember(currentUser, barSection.TenantTypeId, barSection.SectionId); if (!isTenantMember) { errorMessage = "您需要先加入,才能回帖"; } return(isTenantMember); } //站点设置是否启用了匿名发帖 ISiteSettingsManager siteSettingsManager = DIContainer.Resolve <ISiteSettingsManager>(); SiteSettings siteSettings = siteSettingsManager.Get(); if (siteSettings.EnableAnonymousPosting) { return(true); } if (currentUser == null) { errorMessage = "您必须先登录,才能回帖"; return(false); } return(true); }
public void GuestCanJoinChannel() { Assert.True(Authorizer.IsAuthorized("neo.channel.join.$", guestPermissions)); }
/// <summary> /// 是否具有删除BarPost的权限 /// </summary> /// <param name="postId"></param> /// <returns></returns> public static bool BarPost_Delete(this Authorizer authorizer, BarPost post) { return(authorizer.BarPost_Edit(post)); }
public void GuestCantCreateChannel() { Assert.False(Authorizer.IsAuthorized("neo.channel.create", guestPermissions)); }
/// <summary> /// 是否具有评分的权利 /// </summary> /// <param name="authorizer">权限项</param> /// <param name="threadId">被评论的帖子ID</param> /// <returns>是否具有评分的权利</returns> public static bool BarRating(this Authorizer authorizer, long threadId) { string errorMessage; return(authorizer.BarRating(new BarThreadService().Get(threadId), out errorMessage)); }
public bool AuthorizedFor(Permission permission) { return(Authorizer.Authorize(permission)); }
/// <summary> /// 是否拥有平分的权限 /// </summary> /// <param name="authorizer"></param> /// <param name="thread">被评分的帖子</param> /// <returns>是否允许评分</returns> public static bool BarRating(this Authorizer authorizer, BarThread thread) { string errorMessage; return(authorizer.BarRating(thread, out errorMessage)); }
/// <summary> /// 是否具有创建Topic的权限 /// </summary> /// <param name="authorizer"></param> /// <returns></returns> public static bool Topic_Create(this Authorizer authorizer) { string errorMessage = string.Empty; return(authorizer.Topic_Create(out errorMessage)); }
/// <summary> /// 是否具有评分的权限 /// </summary> /// <returns></returns> public static bool BarRating(this Authorizer authorizer, BarThread thread, out string errorMessage) { BarSettings barSettings = DIContainer.Resolve <IBarSettingsManager>().Get(); errorMessage = "没有找到对应的帖子"; if (thread == null) { return(false); } errorMessage = "您还没有登录"; IUser currentUser = UserContext.CurrentUser; if (currentUser == null) { return(false); } if (thread.UserId == currentUser.UserId) { errorMessage = "您不可以给自己的帖子评分哦"; return(false); } BarRatingService barRatingService = new BarRatingService(); //是否已经评过分 errorMessage = "您已经评论过此贴"; if (barRatingService.IsRated(currentUser.UserId, thread.ThreadId)) { return(false); } errorMessage = "您的剩余积分不够了哦"; if (barRatingService.GetUserTodayRatingSum(UserContext.CurrentUser.UserId) + barSettings.ReputationPointsMinValue > barSettings.UserReputationPointsPerDay) { return(false); } IBarSettingsManager barSettingsManager = DIContainer.Resolve <IBarSettingsManager>(); BarSettings barSetting = barSettingsManager.Get(); BarSectionService barSectionService = new BarSectionService(); var barSection = barSectionService.Get(thread.SectionId); if (barSection == null) { return(false); } if (barSection.TenantTypeId == TenantTypeIds.Instance().Bar()) { errorMessage = "此帖吧仅允许关注的用户评分哦"; if (barSetting.OnlyFollowerCreatePost) { SubscribeService subscribeService = new SubscribeService(TenantTypeIds.Instance().BarSection()); return(subscribeService.IsSubscribed(thread.SectionId, currentUser.UserId)); } } else { if (authorizer.AuthorizationService.IsTenantMember(currentUser, barSection.TenantTypeId, barSection.SectionId)) { return(true); } } errorMessage = "站点没有开启帖子评分"; if (!barSetting.EnableRating) { return(false); } return(true); }
/// <summary> /// 是否拥有设置管理员权限 /// </summary> /// <param name="authorizer"></param> /// <param name="sectionId">帖吧id</param> /// <returns>是否拥有设置管理员的权限</returns> public static bool BarSection_SetManager(this Authorizer authorizer, long sectionId) { return(authorizer.BarSection_SetManager(new BarSectionService().Get(sectionId))); }
public void DeniedIsDefault() { var authorizer = new Authorizer(); Assert.False(authorizer.Allows(new object(), Thread.CurrentPrincipal)); }