/// <summary> /// Modifies the user access role to a specified value. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="userId">ID of the user whose access role is modified.</param> /// <param name="accessRole">The updated access role.</param> private void ModifyUserAccess(GoogleAdsClient client, long customerId, long userId, AccessRole accessRole) { // Get the CustomerUserAccessService. CustomerUserAccessServiceClient userAccessService = client.GetService( Services.V6.CustomerUserAccessService); // Creates the modified user access. CustomerUserAccess userAccess = new CustomerUserAccess() { ResourceName = ResourceNames.CustomerUserAccess(customerId, userId), AccessRole = accessRole }; // Creates the operation. CustomerUserAccessOperation operation = new CustomerUserAccessOperation() { Update = userAccess, UpdateMask = FieldMasks.AllSetFieldsOf(userAccess) }; // Updates the user access. MutateCustomerUserAccessResponse response = userAccessService.MutateCustomerUserAccess( customerId.ToString(), operation); // Displays the result. Console.WriteLine($"Successfully modified customer user access with " + $"resource name '{response.Result.ResourceName}'."); }
public DownloadResult DownloadDocument(IPwdManService pwdManService, string authenticationToken, long id) { logger.LogDebug("Download content for item ID {id}...", id); var dbContext = pwdManService.GetDbContext(); var docItem = dbContext.DbDocItems .SingleOrDefault(item => item.Type == DbDocItemType.Item && item.Id == id); if (docItem == null || !docItem.ContentId.HasValue) { throw new AccessDeniedPermissionException(); } if (!AccessRole.IsEverbody(docItem.AccessRole)) { var user = pwdManService.GetUserFromToken(authenticationToken); if (AccessRole.IsOwner(docItem.AccessRole)) { if (user.Id != docItem.OwnerId) { throw new AccessDeniedPermissionException(); } } else if (!pwdManService.HasRole(user, docItem.AccessRole)) { throw new AccessDeniedPermissionException(); } } var docContent = dbContext.DbDocContents.Single(c => c.Id == docItem.ContentId); return(new DownloadResult { Stream = new MemoryStream(docContent.Data), FileName = docItem.Name, ContentType = "application/octet-stream" }); }
public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) { hash ^= ResourceName.GetHashCode(); } if (UserId != 0L) { hash ^= UserId.GetHashCode(); } if (HasEmailAddress) { hash ^= EmailAddress.GetHashCode(); } if (AccessRole != global::Google.Ads.GoogleAds.V6.Enums.AccessRoleEnum.Types.AccessRole.Unspecified) { hash ^= AccessRole.GetHashCode(); } if (HasAccessCreationDateTime) { hash ^= AccessCreationDateTime.GetHashCode(); } if (HasInviterUserEmailAddress) { hash ^= InviterUserEmailAddress.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) { hash ^= ResourceName.GetHashCode(); } if (InvitationId != 0L) { hash ^= InvitationId.GetHashCode(); } if (AccessRole != global::Google.Ads.GoogleAds.V8.Enums.AccessRoleEnum.Types.AccessRole.Unspecified) { hash ^= AccessRole.GetHashCode(); } if (EmailAddress.Length != 0) { hash ^= EmailAddress.GetHashCode(); } if (CreationDateTime.Length != 0) { hash ^= CreationDateTime.GetHashCode(); } if (InvitationStatus != global::Google.Ads.GoogleAds.V8.Enums.AccessInvitationStatusEnum.Types.AccessInvitationStatus.Unspecified) { hash ^= InvitationStatus.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public static int GetAllowableRole(AccessRole role) { if (!Enum.IsDefined(typeof(AccessRole), role)) { return((int)AccessRole.Visitors); } return((int)role); }
public virtual AccessMode GetAccessMode(string roleName) { roleName = roleName.ToLower(); if (AccessRole.Any(x => x.Key == roleName)) { return(AccessRole[roleName]); } return(AccessMode.Edit); }
public ActionResult AddRole(int index, string roleName) { AccessRole newObj = new AccessRole() { Name = roleName }; ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("Roles[{0}]", index); return(PartialView("~/Views/Resource/Role.cshtml", newObj)); }
public virtual void AddAccess(string roleName, AccessMode mode) { roleName = roleName.ToLower(); if (AccessRole.Any(x => x.Key == roleName)) { AccessRole.Remove(roleName); } AccessRole.Add(roleName, mode); }
internal void SetAccess(Entity faction, AccessRole accessRole) { if (FactionAccessRoles.ContainsKey(faction)) { FactionAccessRoles[faction] = (uint)accessRole; } else { FactionAccessRoles.Add(faction, (uint)accessRole); } }
public string Sorted() { switch (AccessRole.ToLower()) { case "owner": return((primary ? "0-" : "1-") + Name); case "writer": return("1-" + Name); case "reader": return("2-" + Name); case "freebusyreader": return("2-" + Name); default: return("1-" + Name); } }
private static List <Entity> FactionsWithAccess(Player authorizedPlayer, AccessRole accessRole) { var factions = new List <Entity>(); foreach (KeyValuePair <Entity, AccessRole> keyValuePair in authorizedPlayer.AccessRoles) { Entity faction = keyValuePair.Key; AccessRole access = keyValuePair.Value; if (access.HasFlag(accessRole)) { factions.Add(faction); } } return(factions); }
/// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { UpdateUserAccess codeExample = new UpdateUserAccess(); Console.WriteLine(codeExample.Description); // The Google Ads customer ID for which the call is made. long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // Email address of the user whose access role should be modifled. string emailAddress = "INSERT_EMAIL_ADDRESS_HERE"; // The updated user access role. AccessRole accessRole = (AccessRole)Enum.Parse(typeof(AccessRole), "INSERT_ACCESS_ROLE_HERE"); codeExample.Run(new GoogleAdsClient(), customerId, emailAddress, accessRole); }
private bool GrantAccessRole(Guid UserId, String RoleName) { bool created = false; var testRole = this.mainContext.AccessRoles.Where(r => r.UserId == UserId && r.Name == RoleName).FirstOrDefault(); if (testRole == null) { LogService.Write("Grant Role", String.Format("User:{0};Role:{1}", UserId, RoleName)); created = true; var role = new AccessRole(UserId, RoleName); role.CreatedBy = this.Actor.UserId; this.mainContext.AccessRoles.Add(role); this.mainContext.SaveChanges(); } return(created); }
public void SetPlayer(Player player, string password) { CurrentPlayer = player; CurrentAuthToken = new AuthenticationToken(player, password); ReadOnlyDictionary <Entity, AccessRole> playerAccessRoles = player.GetAccessRoles(CurrentAuthToken); foreach (KeyValuePair <Entity, AccessRole> kvp in playerAccessRoles) { Entity faction = kvp.Key; AccessRole role = kvp.Value; // For now, just select the first faction with the Owner role. if ((role & AccessRole.Owner) == AccessRole.Owner) { CurrentFaction = faction; break; } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="emailAddress">Email address of the user whose access role should be /// updated.</param> /// <param name="accessRole">The updated access role.</param> public void Run(GoogleAdsClient client, long customerId, string emailAddress, AccessRole accessRole) { try { long?userId = GetUserAccess(client, customerId, emailAddress); if (userId != null) { ModifyUserAccess(client, customerId, userId.Value, accessRole); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="emailAddress">Email address of the user to send the invitation to.</param> /// <param name="accessRole">The access role for which the user is invited.</param> public void Run(GoogleAdsClient client, long customerId, string emailAddress, AccessRole accessRole) { // Get the CustomerUserAccessInvitationService. CustomerUserAccessInvitationServiceClient service = client.GetService( Services.V10.CustomerUserAccessInvitationService); // [START invite_user_with_access_role] MutateCustomerUserAccessInvitationRequest invitationRequest = new MutateCustomerUserAccessInvitationRequest() { CustomerId = customerId.ToString(), Operation = new CustomerUserAccessInvitationOperation() { Create = new CustomerUserAccessInvitation() { EmailAddress = emailAddress, AccessRole = accessRole }, } }; try { var response = service.MutateCustomerUserAccessInvitation(invitationRequest); Console.WriteLine("Customer user access invitation was sent for customerId = " + "{0} to email address = {1} and access role = {2}. The invitation resource " + "name is {3}.", customerId, emailAddress, accessRole, response.Result.ResourceName); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } // [END invite_user_with_access_role] }
public static List <AccessRoleName> has_right(List <AccessRoleName> roles, Guid?userId) { ITenant tenant = HttpContext.Current.GetCurrentTenant(); if (!userId.HasValue || userId == Guid.Empty || tenant == null /*|| * !RaaiVanUtil.is_authenticated(HttpContext.Current)*/) { return(new List <AccessRoleName>()); } roles = AccessRole.remove_ref_tenant_specific_roles(tenant.Id, roles); if (PublicMethods.is_system_admin(tenant.Id, userId.Value)) { return(roles); } List <AccessRoleName> ret = UsersController.check_user_group_permissions(tenant.Id, userId.Value, roles); return(ret); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userService = _resolver.GetService(typeof(IUserAccountService)) as IUserAccountService; if (userService == null) { context.SetError("invalid_service", "Missing authentication service"); return; } var username = context.UserName; UserAccountAuthentication account; if (!await userService.Authenticate(username, context.Password, out account)) { var msg = account.Status.HasValue ? account.Status.GetDescription() : "An error occurred trying to authentication your account."; context.SetError("invalid_grant", msg); return; } var authenticationManager = context.Request.Context.Authentication; authenticationManager.SignOut(context.Options.AuthenticationType); var roles = new List <string>(); var claims = account.Claims ?? new List <Claim>(); var access = new AccessRole(); roles.AddRange(from claim in claims where claim.Type == ClaimTypes.Role select claim.Value); if (roles.Count == 0) { access.Name = UserRoleEnum.Reader; roles.Add(access.Name.ToString()); } else { access.Name = (UserRoleEnum)Enum.Parse(typeof(UserRoleEnum), roles[0]); } claims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); claims.Add(new Claim(ClaimTypes.AuthenticationInstant, DateTime.Now.ToString("s"))); claims.Add(new Claim(ClaimTypes.Name, account.Username)); claims.Add(new Claim(ClaimTypes.NameIdentifier, account.UserId.ToString(CultureInfo.InvariantCulture))); claims.Add(new Claim("Guid", account.ID.ToString())); var cookiesIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType); var oAuthIdentity = new ClaimsIdentity(claims, context.Options.AuthenticationType); var currentUtc = new SystemClock().UtcNow; var properties = CreateProperties(context.ClientId, username, access); properties.IssuedUtc = currentUtc; properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); authenticationManager.SignIn(cookiesIdentity); Thread.CurrentPrincipal = new GenericPrincipal(oAuthIdentity, new string[0]); CacheUserAccount(account); }
/// <summary> /// Returns a JSON representation of the current object /// </summary> /// <returns>The JSON representing the current object</returns> public String ToJSONString() { return(String.Format(@"{{ ""BuildingID"":{0}, ""BuildingName"":""{1}"", ""AccessRole"":""{2}"", ""Parent"":{3} }}", BuildingID, BuildingName, AccessRole.ToString(), Parent)); }
/// <summary> /// whats this for? what's it doing? document ffs. /// </summary> /// <param name="event"></param> /// <param name="player"></param> /// <returns></returns> private bool IsPlayerConcerned([NotNull] Event @event, [NotNull] Player player) { if (@event == null) { throw new ArgumentNullException(nameof(@event)); } if (player == null) { throw new ArgumentNullException(nameof(player)); } if (player == _game.SpaceMaster) { return(true); } //var ownedDB = @event.Entity?.GetDataBlob<OwnedDB>(); if (@event.Entity != null) { if (@event.Entity.FactionOwner != Guid.Empty) { foreach (KeyValuePair <Entity, AccessRole> keyValuePair in player.AccessRoles) { Entity arFaction = keyValuePair.Key; AccessRole arRole = keyValuePair.Value; if (@event.Entity.FactionOwner == arFaction.Guid) { if (@event.Entity.HasDataBlob <ShipInfoDB>() && (arRole & AccessRole.UnitVision) == AccessRole.UnitVision) { return(true); } if (@event.Entity.HasDataBlob <ColonyInfoDB>() && (arRole & AccessRole.ColonyVision) == AccessRole.ColonyVision) { return(true); } return(false); } } return(false); } } if (@event.SystemGuid != Guid.Empty) { foreach (KeyValuePair <Entity, AccessRole> keyValuePair in player.AccessRoles) { Entity arFaction = keyValuePair.Key; AccessRole arRole = keyValuePair.Value; var factionInfo = arFaction.GetDataBlob <FactionInfoDB>(); if ((arRole & AccessRole.SystemKnowledge) == 0) { continue; } foreach (Guid knownSystem in factionInfo.KnownSystems) { if (knownSystem != @event.SystemGuid) { continue; } List <Entity> ownedEntities = _game.Systems[knownSystem].GetEntitiesByFaction(arFaction.Guid); if (ownedEntities.Count > 0) { return(true); } } } return(false); } if (@event.Faction != null) { foreach (KeyValuePair <Entity, AccessRole> keyValuePair in player.AccessRoles) { Entity arFaction = keyValuePair.Key; AccessRole arRole = keyValuePair.Value; if (arFaction != @event.Faction) { continue; } return((arRole & AccessRole.FactionEvents) != 0); } } return(false); }
public AuthenticationAttribute(AccessRole role) : base(typeof(AuthenticationFilter)) { Role = role; }
Widget CreatePage(Window win, string pageName) { Box box = new Box(win); ((IAccessibleObject)box).Name = pageName; box.Show(); Button abutton = new Button(win) { Text = "Accessibility-normal", WeightX = 1, AlignmentX = -1 }; ((IAccessibleObject)abutton).TranslationDomain = "kr"; ((IAccessibleObject)abutton).Name = "Accessibility"; ((IAccessibleObject)abutton).Description = "Description for Accessibility"; Label abutton_label = new Label(win) { WeightX = 1, AlignmentX = -1 }; abutton_label.Text = "domain : " + ((IAccessibleObject)abutton).TranslationDomain + ", name : " + ((IAccessibleObject)abutton).Name + ", desc : " + ((IAccessibleObject)abutton).Description; Button bbutton = new Button(win) { Text = "Accessibility-provider", WeightX = 1, AlignmentX = -1 }; ((IAccessibleObject)bbutton).NameProvider = (obj) => "Name-provider"; ((IAccessibleObject)bbutton).DescriptionProvider = (obj) => "Description-provider"; Label bbutton_label = new Label(win) { WeightX = 1, AlignmentX = -1 }; bbutton_label.Text = "name : " + ((IAccessibleObject)bbutton).Name + ", desc : " + ((IAccessibleObject)bbutton).Description; Button cbutton = new Button(win) { Text = "Readingtype,CanHighlight", WeightX = 1, AlignmentX = -1 }; ((IAccessibleObject)cbutton).ReadingInfoType = ReadingInfoType.Name | ReadingInfoType.Role | ReadingInfoType.Description; ((IAccessibleObject)cbutton).Name = "FooFoo"; ((IAccessibleObject)cbutton).Role = AccessRole.Text; ((IAccessibleObject)cbutton).Description = "FooFooButton"; Label name_onoff_label = new Label(win) { Text = "ReadingInfoType.Name : " + ((((IAccessibleObject)cbutton).ReadingInfoType & ReadingInfoType.Name) != 0 ? "on" : "off"), WeightX = 1, AlignmentX = -1 }; Label role_onoff_label = new Label(win) { Text = "ReadingInfoType.Role : " + ((((IAccessibleObject)cbutton).ReadingInfoType & ReadingInfoType.Role) != 0 ? "on" : "off"), WeightX = 1, AlignmentX = -1 }; Label description_onoff_label = new Label(win) { Text = "ReadingInfoType.Description : " + ((((IAccessibleObject)cbutton).ReadingInfoType & ReadingInfoType.Description) != 0 ? "on" : "off"), WeightX = 1, AlignmentX = -1 }; Label state_onoff_label = new Label(win) { Text = "ReadingInfoType.State : " + ((((IAccessibleObject)cbutton).ReadingInfoType & ReadingInfoType.State) != 0 ? "on" : "off"), WeightX = 1, AlignmentX = -1 }; Button saybutton = new Button(win) { Text = "HHGG with false", WeightX = 1, AlignmentX = -1 }; Button saybutton2 = new Button(win) { Text = "HHGG with true", WeightX = 1, AlignmentX = -1 }; int labelIndex = 0; Button roleButton = new Button(win) { WeightX = 1, AlignmentX = -1 }; roleButton.Clicked += (s, e) => { if (labelIndex >= accessRoleValues.Length) { labelIndex = 0; } IAccessibleObject obj = roleButton as IAccessibleObject; AccessRole role = (AccessRole)accessRoleValues.GetValue(labelIndex); obj.Role = role; roleButton.Text = Enum.GetName(typeof(AccessRole), obj.Role); labelIndex++; }; Label label = new Label(win) { Text = string.Format("{0} Apple", sequence++), WeightX = 1, AlignmentX = -1 }; ((IAccessibleObject)label).Name = "Apple"; Button push = new Button(win) { Text = "Push", WeightX = 1, AlignmentX = -1 }; ((IAccessibleObject)push).Name = "PushButton"; Button pop = new Button(win) { Text = "pop", WeightX = 1, AlignmentX = -1, }; ((IAccessibleObject)pop).Name = "PopButton"; abutton.Show(); abutton_label.Show(); bbutton.Show(); bbutton_label.Show(); cbutton.Show(); name_onoff_label.Show(); role_onoff_label.Show(); description_onoff_label.Show(); state_onoff_label.Show(); saybutton.Show(); saybutton2.Show(); roleButton.Show(); label.Show(); push.Show(); pop.Show(); push.Clicked += (s, e) => { NaviItem item = navi.Push(CreatePage(win, string.Format("Apple {0}", sequence - 1)), string.Format("Page {0}", sequence - 1)); }; Label statusLog = new Label(win) { WeightX = 1, AlignmentX = -1 }; statusLog.Show(); saybutton.Clicked += (s, e) => { AccessibleUtil.Say("The Hitchhiker's Guide to the Galaxy", false) .ContinueWith(status => { statusLog.Text = StatusStr(status.Result); }); }; saybutton2.Clicked += (s, e) => { AccessibleUtil.Say("The Hitchhiker's Guide to the Galaxy", true) .ContinueWith(status => { statusLog.Text = StatusStr(status.Result); }); }; pop.Clicked += (s, e) => { var item = navi.NavigationStack.LastOrDefault(); navi.Pop(); }; box.PackEnd(abutton); box.PackEnd(abutton_label); box.PackEnd(bbutton); box.PackEnd(bbutton_label); box.PackEnd(cbutton); box.PackEnd(name_onoff_label); box.PackEnd(role_onoff_label); box.PackEnd(description_onoff_label); box.PackEnd(state_onoff_label); box.PackEnd(saybutton); box.PackEnd(saybutton2); box.PackEnd(roleButton); box.PackEnd(label); box.PackEnd(push); box.PackEnd(pop); box.PackEnd(statusLog); return(box); }
public static bool IsInRole(this ClaimsPrincipal principal, AccessRole role) { return(principal.IsInRole(role.ToString())); }
public bool IsInRole(AccessRole role) { return(Roles.Contains(role)); }
/* * public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) * { * * string clientId; * string clientSecret; * * if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) * { * context.TryGetFormCredentials(out clientId, out clientSecret); * } * * if (string.IsNullOrEmpty(context.ClientId)) * { * //Remove the comments from the below line context.SetError, and invalidate context * //if you want to force sending clientId/secrets once obtain access tokens. * context.Validated(); * context.SetError("invalid_clientId", "Client Id is required."); * return; * } * * var audienceService = _resolver.GetService(typeof(IAudienceService)) as IAudienceService; * if (audienceService == null) * { * throw new ArgumentNullException("context"); * } * * var client = await audienceService.GetAudience(Guid.Parse(context.ClientId)); * if (client == null) * { * context.SetError("invalid_clientId", "Client Id is invalid."); * return; * } * * if (client.ApplicationType == ApplicationTypes.NativeConfidential) * { * if (string.IsNullOrWhiteSpace(clientSecret)) * { * context.SetError("invalid_clientId", "Client Id is invalid."); * return; * } * var cryptoService = _resolver.GetService(typeof(ICrypto)) as ICrypto; * if (cryptoService == null) * { * throw new ArgumentNullException("context"); * } * if (client.Secret != cryptoService.Hash(clientSecret)) * { * context.SetError("invalid_clientId", "Client secret is invalid."); * return; * } * } * * if (!client.Active) * { * context.SetError("invalid_clientId", "Client is inactive."); * return; * } * * context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin); * context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString()); * * context.Validated(); * * } */ /// <summary> /// Creates the properties. /// </summary> /// <param name="clientId">The client identifier.</param> /// <param name="userName">Name of the user.</param> /// <param name="role">The role.</param> /// <returns></returns> public static AuthenticationProperties CreateProperties(string clientId, string userName, AccessRole role) //string[] roles { IDictionary <string, string> data = new Dictionary <string, string> { { "as:client_id", clientId ?? string.Empty }, { "username", userName }, { "role", role.Name.ToString().ToLower() }, { "bitMask", role.BitMask.ToString() }, { "success", true.ToString() } }; return(new AuthenticationProperties(data)); }
/// <summary> /// Returns a JSON representation of the current object /// </summary> /// <returns>The JSON representing the current object</returns> public String ToJSONString() { return(String.Format(@"{{""BuildingID"":{0},""BuildingName"":""{1}"",""AccessRole"":""{2}"",""Parent"":{3},""HasAlarm"":{4}}}", BuildingID, BuildingName, AccessRole.ToString(), Parent, HasAlarm.ToString().ToLower())); }