public ActionResult Create([Bind(Include = "Id,LastName,FirstName,Phone,Email,SellerAccount,Login,Password")] Seller seller) { if (ModelState.IsValid) { // Creation du vendeur dans le SecurityContext du projet ASP.NET using (var secudb = new SecurityDbContext()) { IdentityRole userRole = RoleUtils.CreateOrGetRole("User"); UserManager <MyIdentityUser> userManager = new MyIdentityUserManager(new UserStore <MyIdentityUser>(secudb)); MyIdentityUser sellerUser = new MyIdentityUser() { UserName = seller.Login, Email = seller.Email, Login = seller.Login };; var result = userManager.Create(sellerUser, seller.Password); if (!result.Succeeded) { throw new System.Exception("database insert fail"); } RoleUtils.AssignRoleToUser(userRole, sellerUser); } // Creation du vendeur dans le ProductContext du projet librairie db.Sellers.Add(seller); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(seller)); }
public ActionResult Edit(int?organizationId) { OrganizationEntity organization; var user = Membership.GetUser().GetUserEntity(); if (!organizationId.HasValue) { // When adding new organization, default to "active". organization = RoleUtils.IsUserServiceAdmin() ? new OrganizationEntity { IsActive = true } } : user.Organization; else { organization = new OrganizationEntity(organizationId.Value); if (organization.IsNew) { throw new HttpException(404, Error.NotFound_Organization); } if (!Permissions.UserHasPermission("Edit", organization)) { throw new HttpException(401, Error.Unauthorized_Organization); } } return((Request.IsAjaxRequest() || ControllerContext.IsChildAction) ? (ActionResult)PartialView(organization) : View(organization)); }
private JsonResult JsonException() { if (RouteData.Values.ContainsKey("error")) { var error = (HandleErrorInfo)RouteData.Values["error"]; // send different amount of information based on who is logged in if (RoleUtils.IsUserServiceAdmin()) { return (Json( new { error.ActionName, error.ControllerName, Data = error.Exception.Data.ToString(), error.Exception.Message, InnerException = error.Exception.InnerException != null ? error.Exception.InnerException.ToString() : "", StackTrace = error.Exception.StackTrace.ToString(), TargetSite = error.Exception.TargetSite.ToString(), Source = error.Exception.Source.ToString(), error.Exception.HelpLink, }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { error.Exception.Message })); } } return(Json(Error.Error_Unspecified, JsonRequestBehavior.AllowGet)); }
public async Task AddRoleToRoleMention(string roleToChangeName, string roleToNotAllowToMention) { SocketRole roleNotToMention = RoleUtils.GetGuildRole(Context.Guild, roleToChangeName); SocketRole role = RoleUtils.GetGuildRole(Context.Guild, roleToNotAllowToMention); if (roleNotToMention == null || role == null) { await Context.Channel.SendMessageAsync( $"Either the **{roleToChangeName}** role doesn't exist or the **{roleToNotAllowToMention}** role doesn't exist!"); return; } if (!role.IsMentionable) { await Context.Channel.SendMessageAsync($"The **{role}** role is already not mentionable by anyone!"); return; } ServerListsManager.GetServer(Context.Guild).CreateRoleToRoleMention(roleNotToMention.Id, role.Id); ServerListsManager.SaveServerList(); await Context.Channel.SendMessageAsync( $"The **{roleNotToMention.Name}** role will not be allowed to mention the **{role.Name}** role."); }
private static EditUserModel GetEditModel(int?userId) { // If no user ID provided, return logged in user. if (!userId.HasValue) { return(new EditUserModel(Membership.GetUser().GetUserEntity())); } var user = new UserEntity(userId.Value); if (user.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_User); } // Service admin can edit all users. if (RoleUtils.IsUserServiceAdmin()) { return(new EditUserModel(user)); } // Org admin can edit all user in his/her organization. if (RoleUtils.IsUserOrgAdmin() && user.OrganizationId == Membership.GetUser().GetUserId().OrganizationId) { return(new EditUserModel(user)); } throw new HttpException(401, SharedRes.Error.Unauthorized_User); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new MyIdentityUser { UserName = model.UserName, Login = model.Login }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { IdentityRole defaultRole = RoleUtils.CreateOrGetRole(model.RoleId); RoleUtils.AssignRoleToUser(defaultRole, user); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771 // Envoyer un message électronique avec ce lien // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirmez votre compte", "Confirmez votre compte en cliquant <a href=\"" + callbackUrl + "\">ici</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire return(View(model)); }
public async Task GetOptRoles() { //Get all opt roles OptRole[] optRoles = ServerListsManager.GetServer(Context.Guild).RoleGives.ToArray(); //Setup string builder StringBuilder message = new StringBuilder(); message.Append("**Opt Roles**\n"); if (optRoles.Length == 0) { //There are no opt roles message.Append("There are no opt roles!"); } else { foreach (OptRole optRole in optRoles) { //There are opt roles, so add them to the String Builder IRole role = RoleUtils.GetGuildRole(Context.Guild, optRole.RoleToGiveId); message.Append(optRole.RoleRequiredId == 0 ? $"`{optRole.Name}` -> **{role.Name}**\n" : $"`{optRole.Name}` -> **{role.Name}** (Requires **{RoleUtils.GetGuildRole(Context.Guild, optRole.RoleRequiredId).Name}**)\n"); } } await Context.Channel.SendMessageAsync(message.ToString()); }
public ActionResult RoleList() { IdentityRoleListViewModel vm = new IdentityRoleListViewModel(); vm.Roles = RoleUtils.GetRoles(); return(PartialView("~/Views/Shared/Account/_RoleList.cshtml", vm)); }
public static async Task CheckForNewLeader(IReadOnlyCollection <IGuildUser> guildUsers, ulong channelID) { IGuildUser userWithMostPoints = null; long userPoints = 0; foreach (var user in guildUsers) { if (!user.IsBot) { UserInfo userInfo = ObjectUtils.GetUserInformation(user.Id); if (userInfo != null) { long currentUserPoints = userInfo.points; if (currentUserPoints > userPoints) { userWithMostPoints = user; userPoints = currentUserPoints; } } } } var currentTorchHolder = userWithMostPoints as SocketGuildUser; var role = currentTorchHolder.Roles.FirstOrDefault(x => Util.StringEquals(x.Name, "Point Torch")); if (!currentTorchHolder.Roles.Contains(role)) { await RoleUtils.RemoveRoleFromUser(guildUsers, "Point Torch"); await RoleUtils.GiveRoleToUser(userWithMostPoints as SocketGuildUser, "Point Torch", channelID); } }
public async Task DailyPoints() { string currentDate = DateTime.Now.ToString("yyyyMMdd"); DailyPoints dailyPoints = ObjectUtils.GetDailyPoints("_id", currentDate); var user = Context.Message.Author; List <string> users = dailyPoints.users.ToList(); if (users.Contains(user.ToString())) { TimeSpan untilReset = DateTime.Today.AddDays(1) - DateTime.Now; await ReplyAsync($"{user} has already reclaimed the daily points.\nClaim points in {untilReset.Hours}h {untilReset.Minutes}m"); } else { Util.UpdateArray("_id", currentDate, "users", user.ToString(), "dailyPoints"); Random rand = new Random(); var points = rand.Next(MIN_DAILY_POINTS, MAX_DAILY_POINTS + 1); var jackpot = rand.Next(MIN_DAILY_POINTS, MAX_DAILY_POINTS + 1); await RoleUtils.DailyPointsRoles(user as SocketGuildUser, Context.Message.Channel.Id, MIN_DAILY_POINTS, MAX_DAILY_POINTS, points, jackpot); if (points.Equals(jackpot)) { points *= JACKPOT_MULTIPLIER; await ReplyAsync($"{user} has hit the __***JACKPOT!***__"); } DatabaseUtils.IncrementDocument(user.Id, "points", points); await ReplyAsync($"{user} earned {points} points!"); } }
public async Task SetRuleRole([Remainder] string roleName = "") { if (string.IsNullOrWhiteSpace(roleName)) //Make sure the user actually provided a role { await Context.Channel.SendMessageAsync("You need to provide a role name!"); return; } SocketRole role = RoleUtils.GetGuildRole(Context.Guild, roleName); if (role == null) //Make sure the role exists { await Context.Channel.SendMessageAsync($"The role **{roleName}** doesn't exist!"); return; } //Modify the server settings to update for the new role ServerListsManager.GetServer(Context.Guild).RuleRoleId = role.Id; ServerListsManager.SaveServerList(); await Context.Channel.SendMessageAsync( $"The role that users shell receive after successfully reacting to the rules will be the **{role.Name}** role."); }
public async Task AddOptRole(string optRoleBaseName, string roleToAssignName, [Remainder] string requiredRoleName = "") { SocketRole roleToAssign = RoleUtils.GetGuildRole(Context.Guild, roleToAssignName); //Check to make sure the role exists first if (roleToAssign == null) { await Context.Channel.SendMessageAsync("You need to input a valid role to give!"); return; } //If a required role was specified, check to make sure it exists SocketRole requiredRole = null; if (!string.IsNullOrWhiteSpace(requiredRoleName)) { requiredRole = RoleUtils.GetGuildRole(Context.Guild, requiredRoleName); if (requiredRole == null) { await Context.Channel.SendMessageAsync($"Role {requiredRoleName} doesn't exist!"); return; } } ServerList server = ServerListsManager.GetServer(Context.Guild); //Check to make sure a role give doesn't already exist first if (server.GetOptRole(optRoleBaseName) != null) { await Context.Channel.SendMessageAsync( $"An opt role with the name '{optRoleBaseName}' already exists!"); return; } //Create and add our new opt role OptRole roleGive = new OptRole { Name = optRoleBaseName, RoleToGiveId = roleToAssign.Id, RoleRequiredId = 0 }; if (requiredRole != null) { roleGive.RoleRequiredId = requiredRole.Id; } server.RoleGives.Add(roleGive); ServerListsManager.SaveServerList(); await Context.Channel.SendMessageAsync($"An opt role with the name `{optRoleBaseName}` was created."); }
public override System.Collections.Generic.IEnumerable <ActionMenuAttribute> GetSubMenu() { if (!RoleUtils.IsUserServiceAdmin()) { return (base.GetSubMenu().Concat( MethodBase.GetCurrentMethod().GetCustomAttributes(typeof(ActionMenuAttribute), false).Cast <ActionMenuAttribute>())); } return(base.GetSubMenu()); }
public static IQueryable <OrganizationEntity> WithPermissions(this IQueryable <OrganizationEntity> organizations) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(organizations); } return(organizations.Where( x => x.Locations.Any( y => y.UserAssignedLocations.Any(u => u.UserId == user.UserId)))); }
private void Awake() { if (_instance != null && _instance != this) { Destroy(this.gameObject); } else { _instance = this; } GameObject gameController = GameObject.FindGameObjectWithTag("GameController"); gameState = gameController.GetComponent <GameState>(); }
/// <summary> /// Check the user to see if they have permissions to use the command /// </summary> /// <param name="context"></param> /// <param name="server"></param> /// <param name="argPos"></param> /// <returns></returns> private bool CheckUserPermission(SocketCommandContext context, ServerList server, int argPos) { //Get the command first SearchResult cmdSearchResult = _commands.Search(context, argPos); if (!cmdSearchResult.IsSuccess) return true; ServerList.CommandPermission perm = server.GetCommandInfo(cmdSearchResult.Commands[0].Command.Name); if (perm == null) return true; //If they are an administrator they override permissions return ((SocketGuildUser) context.User).GuildPermissions.Administrator || ((SocketGuildUser) context.User).Roles.Any(role => perm.Roles.Any(permRole => role == RoleUtils.GetGuildRole(context.Guild, permRole))); }
public async Task RolePoints() { StringBuilder sb = new StringBuilder(); ServerList server = ServerListsManager.GetServer(Context.Guild); sb.Append("__**Server Point Roles**__\n"); foreach (ServerRolePoints rolePoint in server.ServerRolePoints) { sb.Append( $"[{RoleUtils.GetGuildRole(Context.Guild, rolePoint.RoleId)}] **{rolePoint.PointsRequired}**\n"); } await Context.Channel.SendMessageAsync(sb.ToString()); }
public static IQueryable <LocationEntity> WithPermissions(this IQueryable <LocationEntity> locations, int?organizationId = null) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(organizationId.HasValue ? locations.Where(x => x.OrganizationId == organizationId.Value) : locations); } if (RoleUtils.IsUserOrgAdmin()) { return(locations.Where(x => x.OrganizationId == user.OrganizationId)); } return(locations.Where(x => x.UserAssignedLocations.Any(y => y.UserId == user.UserId))); }
public static IQueryable <PurchaseHistoryEntity> WithPermissions(this IQueryable <PurchaseHistoryEntity> purchases) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(purchases); } if (RoleUtils.IsUserOrgAdmin()) { return(purchases.Where(x => x.Location.OrganizationId == user.OrganizationId)); } return(purchases.Where(x => x.Location.UserAssignedLocations.Any(y => y.UserId == user.UserId))); }
public static IQueryable <TreatmentEntity> WithPermissions(this IQueryable <TreatmentEntity> treatments) { var user = Membership.GetUser().GetUserEntity(); if (RoleUtils.IsUserServiceAdmin()) { return(treatments); } if (RoleUtils.IsUserOrgAdmin()) { return(treatments.Where(x => x.Patient.Location.OrganizationId == user.OrganizationId)); } return(treatments.Where(x => x.Patient.Location.UserAssignedLocations.Any(y => y.UserId == user.UserId))); }
public async Task GiveOptRole([Remainder] string optRoleName = "") { SocketGuildUser user = (SocketGuildUser)Context.User; if (user == null) { return; } //Make sure the imputed optRoleName is not empty or null if (string.IsNullOrWhiteSpace(optRoleName)) { await Context.Channel.SendMessageAsync("You need to input an opt role name!"); return; } //Get the opt role OptRole optRole = ServerListsManager.GetServer(Context.Guild).GetOptRole(optRoleName); if (optRole == null) //And make sure it exists! { await Context.Channel.SendMessageAsync("That opt role doesn't exist!"); return; } //If the opt role has a required role, make sure the user has it if (optRole.RoleRequiredId != 0) { //The user doesn't have the required role if (!user.UserHaveRole(optRole.RoleRequiredId)) { await Context.Channel.SendMessageAsync("You do not meet the requirements to get this opt role!"); return; } } //Give the user the role await user.AddRoleAsync(RoleUtils.GetGuildRole(Context.Guild, optRole.RoleToGiveId)); //Say to the user that they now have the role await Context.Channel.SendMessageAsync( $"You now have the **{RoleUtils.GetGuildRole(Context.Guild, optRole.RoleToGiveId).Name}** role, {user.Mention}."); }
/// <summary> /// Edit and existing credit card and update CIM. /// </summary> /// <param name="creditcardid"></param> /// <returns></returns> public ActionResult EditCard(int creditcardid) { var card = new CreditCardEntity(creditcardid); if (card.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_CreditCard); } if (!Permissions.UserHasPermission("Edit", card)) { throw new HttpException(401, SharedRes.Error.Unauthorized_CreditCard); } // populate the model with the card data loaded from authorize.net try { CustomerGateway cg; var customer = RoleUtils.IsUserServiceAdmin() ? EnsureProfile(out cg, card.UserCreditCards.First().User) : EnsureProfile(out cg); var profile = customer.PaymentProfiles.First(x => x.ProfileID == card.AuthorizeId); var addressLines = profile.BillingAddress.Street.Split('\n'); var model = new EditCard { AddressLine1 = addressLines[0], AddressLine2 = addressLines.Length > 1 ? addressLines[1] : "", City = profile.BillingAddress.City, Country = profile.BillingAddress.Country, FirstName = profile.BillingAddress.First, LastName = profile.BillingAddress.Last, State = profile.BillingAddress.State, Zip = profile.BillingAddress.Zip, }; return(PartialView(model)); } catch (Exception ex) { ModelState.AddModelError("", Purchase.EditCard_Error); Log.Error(Purchase.EditCard_Error, ex); } return(PartialView()); }
public async Task AddRolePoints(uint pointsAmount, [Remainder] string roleName) { //First, lets make sure that the role actually exists SocketRole role = RoleUtils.GetGuildRole(Context.Guild, roleName); if (role == null) { await Context.Channel.SendMessageAsync("That role doesn't exists!"); return; } ServerList server = ServerListsManager.GetServer(Context.Guild); //Make sure a point role with that many points doesn't exist if (server.GetServerRolePoints(pointsAmount).PointsRequired != 0) { await Context.Channel.SendMessageAsync( $"A role is already given when a user gets `{pointsAmount}` points."); return; } //Can't have a point role lower then the amount of points given each time if (pointsAmount >= server.PointGiveAmount) { await Context.Channel.SendMessageAsync( $"You have to set required points higher then `{server.PointGiveAmount}`!"); return; } ServerRolePoints serverRolePoints = new ServerRolePoints { RoleId = role.Id, PointsRequired = pointsAmount }; //Add our point role to our list server.ServerRolePoints.Add(serverRolePoints); ServerListsManager.SaveServerList(); await Context.Channel.SendMessageAsync( $"Ok, when a user gets {pointsAmount} points they shell receive the **{role.Name}** role.\nPlease note any user who already have {pointsAmount} points won't get the role."); }
public async Task GetRolePings() { ServerList server = ServerListsManager.GetServer(Context.Guild); StringBuilder builder = new StringBuilder(); builder.Append("__**Role to Roles**__\n```"); foreach (ServerRoleToRoleMention roleToRole in server.RoleToRoleMentions) { builder.Append( $"{RoleUtils.GetGuildRole(Context.Guild, roleToRole.RoleNotToMentionId).Name} =====> {RoleUtils.GetGuildRole(Context.Guild, roleToRole.RoleId).Name}\n"); } builder.Append("```"); await Context.Channel.SendMessageAsync(builder.ToString()); }
private FileContentResult ImageException() { using (var image = new Bitmap(300, 200)) { var g = Graphics.FromImage(image); g.InterpolationMode = InterpolationMode.High; g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; g.FillRectangle(new SolidBrush(Color.Black), 0, 0, image.Width, image.Height); var fontSize = 15; Font f; var message = Error.Error_Unspecified; if (RouteData.Values.ContainsKey("error")) { var error = (HandleErrorInfo)RouteData.Values["error"]; message = error.Exception.Message; // only show stack trace if service administrator is logged in if (RoleUtils.IsUserServiceAdmin()) { message += Environment.NewLine + Environment.NewLine + "Controller: " + error.ControllerName + Environment.NewLine + Environment.NewLine + "Action: " + error.ActionName + Environment.NewLine + Environment.NewLine + "Stack Trace: " + error.Exception.StackTrace; } } float height; do { f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold); height = g.MeasureString(message, f, 300).Height; fontSize--; } while (height > image.Height && fontSize > 4); g.DrawString(message, f, new SolidBrush(Color.White), new RectangleF(0, 0, image.Width, image.Height)); using (var mem = new MemoryStream()) { image.Save(mem, ImageFormat.Png); return(File(mem.ToArray(), "image/png")); } } }
public void GetCustomerProfileByAuthenticationTest_Success() { bool IsNewCustomer = false; CustomerHPIDUtils custUtils = new CustomerHPIDUtils(); RoleUtils rlUtils = new RoleUtils(); TokenDetails sessionToken = new TokenDetails(); sessionToken.AccessToken = "sessionToken"; hpidUtilsMock.Setup(x => x.GetHPIDSessionToken(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <GetProfileResponse>(), It.IsAny <string>(), It.IsAny <int>())).Returns(sessionToken); hpidUtilsMock.Setup(x => x.GetIdsAndProfile(It.IsAny <CustomerIds>(), It.IsAny <string>(), It.IsAny <GetProfileResponse>())). Callback((CustomerIds i, string u, GetProfileResponse r) => { i = new CustomerIds() { HPIDid = "hpidid", HPPid = "hppid" }; r.CustomerProfileObject = new CustomerProfile(); }).Returns(true); User aProfile = new User() { EmailConsent = true }; List <RoleMapping> roleMappings = new List <RoleMapping>(); RoleMapping role = new RoleMapping(); role.RoleId = 1; role.RoleMappingId = 1; role.UserId = 1; role.CreatedDate = DateTime.UtcNow; roleMappings.Add(role); aProfile.RoleMappings = roleMappings; isacMock.Setup(x => x.FindOrInsertHPIDProfile(It.IsAny <ResponseBase>(), It.IsAny <RequestFindOrInsertHPIDProfile>(), out IsNewCustomer)).Returns(aProfile); GetProfileResponse response = custUtils.GetCustomerProfileByAuthentication(new UserAuthenticationInterchange(), It.IsAny <bool>(), "access", "url", It.IsAny <APIMethods>()); Assert.IsTrue(response.ErrorList.Count == 0); Assert.IsTrue(response.CustomerProfileObject.EmailConsent.Equals(EmailConsentType.Y.ToString())); }
/// <summary> /// Checks if a given user is allowed to @mention a certain role, and warns them if not /// </summary> /// <param name="message">The message to check</param> /// <param name="user">The author of the message</param> /// <returns>Whether the user is allowed to do that action</returns> public bool CheckRoleMentions(SocketUserMessage message, SocketGuildUser user) { UserAccountServerData serverAccount = UserAccountsManager.GetAccount(user).GetOrCreateServer(user.Guild.Id); if (serverAccount.IsAccountNotWarnable) { return(false); } //If it is the owner of the Discord server, ignore if (user.Id == user.Guild.OwnerId) { return(false); } ServerList server = ServerListsManager.GetServer(user.Guild); //Go over each role a user has foreach (SocketRole role in user.Roles) { foreach (ServerRoleToRoleMention notToMentionRoles in server.RoleToRoleMentions.Where(notToMentionRoles => role.Id == notToMentionRoles.RoleNotToMentionId)) { message.DeleteAsync(); if (serverAccount.RoleToRoleMentionWarnings >= server.AntiSpamSettings.RoleToRoleMentionWarnings) { message.Channel.SendMessageAsync( $"Hey {user.Mention}, you have been pinging the **{RoleUtils.GetGuildRole(user.Guild, notToMentionRoles.RoleId).Name}** role, which you are not allowed to ping!\nA warning has been added to your account, for info see your profile."); serverAccount.Warnings++; UserAccountsManager.SaveAccounts(); } serverAccount.RoleToRoleMentionWarnings++; return(true); } } return(false); }
public async Task RemoveRoleToRoleMention(string roleToChangeName, string roleAllowedToMentionName) { SocketRole roleNotToMention = RoleUtils.GetGuildRole(Context.Guild, roleToChangeName); SocketRole role = RoleUtils.GetGuildRole(Context.Guild, roleAllowedToMentionName); if (roleNotToMention == null || role == null) { await Context.Channel.SendMessageAsync( $"Either the **{roleToChangeName}** role doesn't exist or the **{roleAllowedToMentionName}** role doesn't exist!"); return; } ServerList server = ServerListsManager.GetServer(Context.Guild); List <ServerRoleToRoleMention> roleToRoleMentionsWithRole = server.GetRoleToRoleMention(role.Id); if (roleToRoleMentionsWithRole.Count == 0) { await Context.Channel.SendMessageAsync($"The **{role}** role doesn't have any preventions on it!"); return; } foreach (ServerRoleToRoleMention roleMention in roleToRoleMentionsWithRole) { //We found it if (roleMention.RoleNotToMentionId == roleNotToMention.Id) { server.RoleToRoleMentions.Remove(roleMention); await Context.Channel.SendMessageAsync( $"The **{roleNotToMention.Name}** role can now mention the **{role.Name}** role."); ServerListsManager.SaveServerList(); return; } await Context.Channel.SendMessageAsync( $"The **{roleNotToMention.Name}** role can already mention the **{role}** role."); } }
/// <summary> /// Perform the authorization check using the Iprincipal on the action context. /// </summary> /// <param name="ctx"></param> /// <param name="resources"></param> /// <returns></returns> public static BoolMessage CheckAuthorization(IActionContext ctx, ILocalizedResourceManager resources) { // Principal object supplied. if (ctx.AuthenticationData != null && ctx.AuthenticationData.Identity.IsAuthenticated) { ctx.UserName = ctx.AuthenticationData.Identity.Name; // No roles required to perform this action. if (string.IsNullOrEmpty(ctx.AuthenticationRoles)) { return(BoolMessage.True); } bool isAllowedToPerformAction = RoleUtils.IsInRoles(ctx.AuthenticationRoles, ctx.AuthenticationData); string error = isAllowedToPerformAction ? string.Empty : resources.GetString("Authorization_Failed", "Authorizaion failed, not allowed to perform action per role."); return(new BoolMessage(isAllowedToPerformAction, error)); } return(BoolMessage.False); }
public async Task HasRole(string roleName, SocketGuildUser user) { //Get the role IRole role = RoleUtils.GetGuildRole(Context.Guild, roleName); if (role == null) { await Context.Channel.SendMessageAsync("That role doesn't exist!"); return; } if (user.UserHaveRole(role.Id)) { await Context.Channel.SendMessageAsync($"**{user.Username}** has the role **{role.Name}**."); } else { await Context.Channel.SendMessageAsync($"**{user.Username}** doesn't have the role **{role}**."); } }