private void IssueSystemPermissionClaims( IPrincipal claimsPrincipal, IEnumerable <SystemPermission> grantedPermissions, SystemAccount systemAccount) { var identity = ( IClaimsIdentity )claimsPrincipal.Identity; var exsitingPermissions = FindExistingSystemPermissionWellKnownNames(identity); var realm = _federationAuthenticationModule.Realm; foreach (var grantedPermission in grantedPermissions) { if (!exsitingPermissions.Any(x => x == grantedPermission.WellKnownName)) { var claim = new Claim( ClaimTypes.PermissionClaimType, grantedPermission.WellKnownName, realm); identity.Claims.Add(claim); Logger.Debug("Principal ({0}) is issued the following claim ({1}).", systemAccount.Identifier, claim.ToString()); } else { Logger.Debug("Claim for permission ({0}) has already existed.", grantedPermission.WellKnownName); } } }
public static string GetAvatarUrl(Node node, int?width = null, int?height = null) { if (node == null) { return(string.Empty); } // Reload in elevated mode because we do not know how the provided // node has been loaded and we need its avatar url. var fullNode = SystemAccount.Execute(() => Node.LoadNode(node.Id)); var group = fullNode as Group; var user = fullNode as User; if (group != null) { var url = GetDefaultGroupAvatarPath(); url = AddWidthHeightParam(url, width, height); return(url); } if (user != null) { var avatarUrl = user.AvatarUrl; var url = string.IsNullOrEmpty(avatarUrl) ? GetDefaultUserAvatarPath() : avatarUrl; url = AddWidthHeightParam(url, width, height); return(url); } return(string.Empty); }
public override object Execute(Content content, params object[] parameters) { var identityParamValue = parameters[0] == Type.Missing ? null : (string)parameters[0]; var canSeePermissions = content.Security.HasPermission(PermissionType.SeePermissions); // If the user doesn't have SeePermissions right, it can only query its own permissions if (!canSeePermissions && (string.IsNullOrEmpty(identityParamValue) || identityParamValue != User.Current.Path)) { throw new Exception("You are only authorized to query your own permissions for this content."); } // Elevation is required if the user doesn't have SeePermissions right, but // in this case, it will only see its own permissions anyway. IDisposable sysacc = null; try { if (!canSeePermissions) { sysacc = new SystemAccount(); } return(string.IsNullOrEmpty(identityParamValue) ? GetAcl(content) : GetAce(content, identityParamValue)); } finally { sysacc?.Dispose(); } }
public static IApplicationBuilder UseSenseNetUser(this IApplicationBuilder app) { app.Use(async(context, next) => { // At this point the user is already authenticated, which means // we can trust the information in the identity: we load the // user in elevated mode (using system account). var identity = context?.User?.Identity; if (!string.IsNullOrEmpty(identity?.Name)) { // Currently we look for users by their login name. In the future we may add // a more flexible user discovery algorithm here. var user = SystemAccount.Execute(() => User.Load(identity.Name)); if (user != null) { User.Current = user; } else { SnTrace.Security.Write("Unknown user: {0}", identity.Name); } } await next.Invoke(); }); return(app); }
public static List <string> GetRoles(SystemAccount anAccount) { List <string> roles = new List <string>(); using (SqlConnection conn = Utilities.GetConnection()) { SqlCommand comm = new SqlCommand(@"select Name from ApplicationRole, UserRole where UserRole.UserName = @accountName and UserRole.RoleId=ApplicationRole.Id", conn); comm.Parameters.Add("@accountName", SqlDbType.VarChar, 255); comm.Parameters["@accountName"].Value = anAccount.UserId; try { conn.Open(); SqlDataReader reader = comm.ExecuteReader(); while (reader.Read()) { roles.Add(reader["Name"].ToString()); } return(roles); } catch (SqlException sqlException) { throw new HCSMSException(sqlException.Message); } finally { if (conn != null) { conn.Close(); } } } }
/// <summary> /// Calculate the list of AgencyPermissions for a specific System Account. /// </summary> /// <param name="systemAccount">The System Account to Calculate the AgencyPermissions for.</param> /// <remarks> /// System Accounts are granted access to all Designers and Administration Modules, but no Data Entry Modules. /// </remarks> private List <AgencyPermissions> CalculateSystemAcountAgencyPermissions(SystemAccount systemAccount) { // Get a list of Ids of all Agencies in the system. var agencyIds = _administrationUnitOfWork.GetEntityQuery <Agency>() .Select(x => x.Id).ToList(); // Return the Calculated Agency Permissions return(agencyIds.Select(x => // In Each Agency a System Account is allowed access to all Designers and Administration Modules. // But NO Data Entry Moduels new AgencyPermissions { // The Id of the Agency AgencyId = x, // System Accounts are granted Administration Access to All Agencies. AdministrationGranted = true, // System Accounts are granted access to all designer modules. DesignerPermissions = ModuleTypeInfo.DesignerModules .Select(designerType => new DesignerPermissions { AccessGranted = true, DesignerType = designerType }) .ToList(), // System Accounts cannot access Data Entry Moduels DataEntryModulePermissions = new List <DataEntryModulePermissions>() }).ToList()); }
private bool HandleResponseForClientCache(HttpHeaderTools headerTools) { if (RequestedNodeHead == null) { return(false); } var cacheSetting = GetCacheHeaderSetting(headerTools); if (!cacheSetting.HasValue) { return(false); } // cache header (public or private) depends on whether the content is available for anyone var accessibleForVisitor = SystemAccount.Execute(() => Providers.Instance.SecurityHandler.HasPermission(User.Visitor, RequestedNodeHead.Id, PermissionType.Open)); // set MaxAge by type or extension or a global value as a fallback headerTools.SetCacheControlHeaders(cacheSetting.Value, accessibleForVisitor ? HttpCacheability.Public : HttpCacheability.Private); // in case of preview images do NOT return 304, because _undetectable_ permission changes // (on the image or on one of its parents) may change the preview image (e.g. display redaction or not). if (DocumentPreviewProvider.Current?.IsPreviewOrThumbnailImage(RequestedNodeHead) ?? false) { return(false); } // Handle If-Modified-Since and Last-Modified headers: end the response // if the content has not changed since the value posted by the client. var endResponse = headerTools.EndResponseForClientCache(RequestedNodeHead.ModificationDate); return(endResponse); }
public static object GetPermissions(Content content, string identity = null) { var canSeePermissions = content.Security.HasPermission(PermissionType.SeePermissions); // If the user doesn't have SeePermissions right, it can only query its own permissions if (!canSeePermissions && (string.IsNullOrEmpty(identity) || identity != User.Current.Path)) { throw new Exception("You are only authorized to query your own permissions for this content."); } // Elevation is required if the user doesn't have SeePermissions right, but // in this case, it will only see its own permissions anyway. IDisposable sysacc = null; try { if (!canSeePermissions) { sysacc = new SystemAccount(); } return(string.IsNullOrEmpty(identity) ? GetAcl(content) : GetAce(content, identity)); } finally { sysacc?.Dispose(); } }
public void IssueAccountStaffClaims(ClaimsPrincipal claimsPrincipal, SystemAccount systemAccount) { var identity = claimsPrincipal.Identity as ClaimsIdentity; if (identity != null) { identity.AddClaim(new Claim(AsamClaimTypes.AccountIdClaimType, systemAccount.Key.ToString())); if (systemAccount.IsSystemAdmin) { identity.AddClaim(new Claim(AsamClaimTypes.SystemAdminType, true.ToString())); } else { identity.AddClaim(new Claim(AsamClaimTypes.OrganizationIdClaimType, systemAccount.Organization.Key.ToString())); identity.AddClaim(new Claim(AsamClaimTypes.OrganizationNameClaimType, systemAccount.Organization.Name)); } var emailClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); if (emailClaim != null) { identity.RemoveClaim(emailClaim); } identity.AddClaim(new Claim(ClaimTypes.Email, systemAccount.Email.Address)); if (systemAccount.Staff != null) { identity.AddClaim(new Claim(AsamClaimTypes.StaffIdClaimType, systemAccount.Staff.Key.ToString())); identity.AddClaim(new Claim(AsamClaimTypes.StaffFullNameClaimType, systemAccount.Staff.Name.FirstName + " " + systemAccount.Staff.Name.LastName)); } } }
/// <summary> /// Ons the get async. /// </summary> /// <returns>The get async.</returns> public async Task <IActionResult> OnPostAsync() { _logger.LogDebug("SystemAccount/Create/OnPostAsync"); if (!ModelState.IsValid) { return(Page()); } var emptySystemAccount = new SystemAccount(); if (await TryUpdateModelAsync <SystemAccount>( emptySystemAccount, "systemaccount", // Preset for form value s => s.UserName, s => s.PassWord, s => s.LastUpdate ).ConfigureAwait(false)) { _context.SystemAccount.Add(emptySystemAccount); await _context.SaveChangesAsync().ConfigureAwait(false); return(RedirectToPage("./Index")); } return(null); }
/// <summary> /// Executes the boot sequence of the Repository by the passed <see cref="RepositoryStartSettings"/>. /// </summary> /// <example> /// Use the following code in your tool or other outer application: /// <code> /// var startSettings = new RepositoryStartSettings /// { /// PluginsPath = pluginsPath, // Local directory path of plugins if it is different from your tool's path. /// Console = Console.Out // Startup sequence will be traced to given writer. /// }; /// using (SenseNet.ContentRepository.Repository.Start(startSettings)) /// { /// // your code /// } /// </code> /// </example> /// <remarks> /// Repository will be stopped if the returned <see cref="RepositoryStartSettings"/> instance is disposed. /// </remarks> /// <returns>A new IDisposable <see cref="RepositoryInstance"/> instance.</returns> /// <returns></returns> public static RepositoryInstance Start(RepositoryStartSettings settings) { var instance = RepositoryInstance.Start(settings); SystemAccount.Execute(() => Root); return(instance); }
/// <summary> /// Called when [save]. /// </summary> /// <param name="entity">The entity to be saved.</param> /// <param name="id">The id of the entity.</param> /// <param name="state">The state information.</param> /// <param name="propertyNames">The property names.</param> /// <param name="types">The type information.</param> /// <returns><c>true</c> if it is an auditable entity.</returns> public override bool OnSave( object entity, object id, object[] state, string[] propertyNames, IType[] types) { bool entityModified = false; if (entity is IAuditable) { SystemAccount systemAccount = GetSystemAccount(); DateTimeOffset dateTime = DateTimeOffset.Now; SetStateValue(propertyNames, state, "CreatedTimestamp", dateTime); SetStateValue(propertyNames, state, "UpdatedTimestamp", dateTime); SetStateValue(propertyNames, state, "CreatedBySystemAccount", systemAccount); SetStateValue(propertyNames, state, "UpdatedBySystemAccount", systemAccount); entityModified = true; } return(entityModified); }
public static decimal GetLossToday(this SystemAccount sa) { var now = Math.Abs(sa.PublicSum); var pre = Math.Abs(sa.GetPreTotal()); return(now - pre); }
/// <summary> /// Create a new System Account in this RMSSystem. /// System accounts do not belong to any Agency, these are intended to be TriTech user accounts only. /// </summary> public SystemAccount CreateSystemAccount(Guid id, string username, string password) { CheckUsername(username); var systemAccount = new SystemAccount(id, this, username, password); IdentitiesCollection.Add(systemAccount); return(systemAccount); }
/// <summary> /// Issues the system permission claims. /// </summary> /// <param name="claimsPrincipal">The claims principal.</param> /// <param name="systemAccount">The system account.</param> public void IssueSystemPermissionClaims(IClaimsPrincipal claimsPrincipal, SystemAccount systemAccount) { Check.IsNotNull(claimsPrincipal, "ClaimsPrincipal is required."); Check.IsNotNull(systemAccount, "SystemAccount is required."); var grantedPermissions = systemAccount.FindGrantedPermissions(); IssueSystemPermissionClaims(claimsPrincipal, grantedPermissions, systemAccount); }
/// <summary> /// Exercises the emergency access. /// </summary> /// <param name="claimsPrincipal">The claims principal.</param> /// <param name="systemAccount">The system account.</param> public void ExerciseEmergencyAccess(IClaimsPrincipal claimsPrincipal, SystemAccount systemAccount) { Check.IsNotNull(claimsPrincipal, "ClaimsPrincipal is required."); Check.IsNotNull(systemAccount, "SystemAccount is required."); var emergencyPermissions = FindEmergencyAccessPermissions(); IssueSystemPermissionClaims(claimsPrincipal, emergencyPermissions, systemAccount); }
public void SystemAccountUpdate_Test() { SystemAccount sysAccount1 = linkWebDB.SystemAccounts.FirstOrDefault(); sysAccount1.UpdateSystemAccount("Gian Ismhael Lim", "gianismhael.lim", "B3 L1-2 Amparo Village, Tambaling", "Test account 1", PasswordHasher.HashPassword("gastovski"), EnumSystemAccountType.TellerAcount); linkWebDB.SaveChanges(); Assert.AreEqual(linkWebDB.SystemAccounts.FirstOrDefault().Name, "Gian Ismhael Lim"); }
private static ServiceQueryContext GetQueryContext(SnQuery query, IQueryContext context) { return(new ServiceQueryContext { UserId = context.UserId, FieldLevel = PermissionFilter.GetFieldLevel(query).ToString(), DynamicGroups = SystemAccount.Execute(() => Node.Load <User>(context.UserId)?.GetDynamicGroups(0)?.ToArray() ?? new int[0]) }); }
/// <summary> /// Issues the account staff claims. /// </summary> /// <param name="claimsPrincipal">The claims principal.</param> /// <param name="systemAccount">The system account.</param> /// <exception cref="System.InvalidOperationException"> /// Staff does not exist for key + systemAccount.StaffKey /// or /// Patient does not exist for key + systemAccount.PatientKey. /// </exception> public void IssueAccountClaims(ClaimsPrincipal claimsPrincipal, SystemAccount systemAccount) { var identity = claimsPrincipal.Identity as ClaimsIdentity; if (identity != null) { identity.AddClaim(new Claim(ProCenterClaimType.AccountKeyClaimType, systemAccount.Key.ToString())); if (systemAccount.OrganizationKey != Guid.Empty) { identity.AddClaim(new Claim(ProCenterClaimType.OrganizationKeyClaimType, systemAccount.OrganizationKey.ToString())); identity.AddClaim(new Claim(ProCenterClaimType.OrganizationNameClaimType, GetOrganizationName(systemAccount.OrganizationKey))); } var emailClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); if (emailClaim != null) { identity.RemoveClaim(emailClaim); } identity.AddClaim(new Claim(ClaimTypes.Email, systemAccount.Email.Address)); if (systemAccount.StaffKey != null) { var staff = _staffRepository.GetByKey(systemAccount.StaffKey.Value); if (staff == null) { throw new InvalidOperationException("Staff does not exist for key " + systemAccount.StaffKey); } identity.AddClaim(new Claim(ProCenterClaimType.StaffKeyClaimType, systemAccount.StaffKey.ToString())); identity.AddClaim(new Claim(ProCenterClaimType.UserFirstNameClaimType, staff.Name.FirstName)); identity.AddClaim(new Claim(ProCenterClaimType.UserLastNameClaimType, staff.Name.LastName)); systemAccount.Validate(); } else if (systemAccount.PatientKey != null) { var patient = _patientRepository.GetByKey(systemAccount.PatientKey.Value); if (patient == null) { throw new InvalidOperationException("Patient does not exist for key " + systemAccount.PatientKey); } identity.AddClaim(new Claim(ProCenterClaimType.PatientKeyClaimType, systemAccount.PatientKey.ToString())); identity.AddClaim(new Claim(ProCenterClaimType.UserFirstNameClaimType, patient.Name.FirstName)); identity.AddClaim(new Claim(ProCenterClaimType.UserLastNameClaimType, patient.Name.LastName)); } else { identity.AddClaim( new Claim(ProCenterClaimType.UserFirstNameClaimType, systemAccount.Identifier.Substring(0, systemAccount.Identifier.IndexOf('@')))); } if (systemAccount.Validated) { IssueSystemAccountValidationClaim(claimsPrincipal); } systemAccount.LogIn(); } }
public static void UpdateSystemAccount(this SystemAccount currentSystemAccount, string name, string logonName, string address, string notes, string hashedPassword, EnumSystemAccountType accountType) { currentSystemAccount.Name = name; currentSystemAccount.LogonName = logonName; currentSystemAccount.Address = address; currentSystemAccount.Notes = notes; currentSystemAccount.HashedPassword = hashedPassword; currentSystemAccount.AccountType = accountType.ToString(); }
/// <summary> /// Calculate the Permissions for a System Account. /// </summary> /// <param name="systemAccount">The System Account to calculate permissions for.</param> /// <returns></returns> private Permissions CalculateSystemAccountPermissions(SystemAccount systemAccount) { return(new Permissions { // System Accounts are granted System Administration SystemAdministrationGranted = true, // Calculate Agency Permissions for a System Account AgencyPermissions = CalculateSystemAcountAgencyPermissions(systemAccount) }); }
public void SystemAccount_Test() { SystemAccount sysAccount1 = SystemAccountsExtension.CreateSystemAccount("Sheen Ismhael Lim", "sheenismhael.lim", "B3 L1-2 Amparo Village, Tambaling", "Test account 1", PasswordHasher.HashPassword("gastovski"), EnumSystemAccountType.AdminAccount); linkWebDB.SystemAccounts.Add(sysAccount1); linkWebDB.SaveChanges(); Assert.AreEqual(linkWebDB.SystemAccounts.FirstOrDefault().GUID, sysAccount1.GUID); }
private static void AssignPatientToPortal(Role portalRole, Guid organizationKey, Patient patient) { if (patient.Email == null) { return; } var systemAccount = new SystemAccount(organizationKey, patient.Email.Address, patient.Email); systemAccount.AssignToPatient(patient.Key); systemAccount.AddRole(portalRole.Key); }
/// <summary> /// Create an IdentityContext for a SystemAcount's Identity /// </summary> private IdentityContext CreateSystemAccountIdentityContext(SystemAccount systemAccount) { var systemAccountContext = new IdentityContext { IdentityType = IdentityType.SystemAccount, GivenName = systemAccount.Username, IdentityId = systemAccount.Id, Permissions = CalculateSystemAccountPermissions(systemAccount), RoleIds = systemAccount.AssignedRoles.Select(x => x.RoleId).ToList() }; return(systemAccountContext); }
private Stream GetConvertedStream(out string contentType, out BinaryFileName fileName) { // We have to treat images differently: the image handler takes care // of putting redactions on the preview image if permissions require that. if (RequestedNode is Image img) { var parameters = new Dictionary <string, object>(); if (Width.HasValue) { parameters.Add("width", Width.Value); } if (Height.HasValue) { parameters.Add("height", Height.Value); } if (Watermark != null) { parameters.Add("watermark", Watermark); } // At this point we are certain that the user can have the binary. // If the user does not have Open permission, it is still possible for them // to access a preview image. In this case we have to reload the image // to clear the headonly flag and let the user access the binary. if (img.IsPreviewOnly) { // ReSharper disable once AccessToModifiedClosure img = SystemAccount.Execute(() => Node.Load <Image>(img.Id)); } return(img.GetImageStream(PropertyName, parameters, out contentType, out fileName)); } // Get the stream through our provider to let 3rd party developers serve custom data. var stream = DocumentBinaryProvider.Instance.GetStream(RequestedNode, PropertyName, _context, out contentType, out fileName); if (stream == null) { return(null); } // try to treat the binary value as an image and resize it if (Width.HasValue && Height.HasValue) { return(Image.CreateResizedImageFile(stream, string.Empty, Width.Value, Height.Value, 0, contentType)); } return(stream); }
public static SystemAccount CreateSystemAccount(string name, string logonName, string address, string notes, string hashedPassword, EnumSystemAccountType accountType) { SystemAccount newSystemAccount = new SystemAccount(); newSystemAccount.GUID = IDGenerator.GenerateSystemAccountID(accountType); newSystemAccount.Name = name; newSystemAccount.LogonName = logonName; newSystemAccount.Address = address; newSystemAccount.Notes = notes; newSystemAccount.HashedPassword = hashedPassword; newSystemAccount.AccountType = accountType.ToString(); return(newSystemAccount); }
public void IssueSystemPermissionClaims(ClaimsPrincipal claimsPrincipal, SystemAccount systemAccount) { var identity = claimsPrincipal.Identity as ClaimsIdentity; if (identity != null) { foreach (var role in systemAccount.Roles.Select(sar => sar.Role)) { foreach (var permission in role.Permissions) { identity.AddClaim(new Claim(AsamClaimTypes.PermissionClaimType, permission.SystemPermission.WellKnownName)); } } } }
public static Session NewSession(Account anAccount) { if (SystemAccountDao.IsExist(anAccount.Name)) { SystemAccount sysAccount = SystemAccountDao.Login(anAccount); Session session = new Session(sysAccount); sessionList.Add(session, DateTime.Now); return(session); } else { return(null); } }
public ValidationStatus ValidateInfo(SystemAccount systemAccount, string patientIdentifier, DateTime dateOfBirth) { if (string.Equals(patientIdentifier, UniqueIdentifier) && DateOfBirth.Value == dateOfBirth) { systemAccount.Validate(); UserContext.Current.RefreshValidationAttempts(); return(ValidationStatus.Valid); } if (UserContext.Current.ValidationAttempts >= 3) { systemAccount.Lock(); return(ValidationStatus.Locked); } UserContext.Current.FailedValidationAttempt(); return(ValidationStatus.AttemptFailed); }
public void IssueSystemPermissionClaims(ClaimsPrincipal claimsPrincipal, SystemAccount systemAccount) { var identity = claimsPrincipal.Identity as ClaimsIdentity; if (identity != null) { foreach (var roleKey in systemAccount.RoleKeys) { var role = _roleRepository.GetByKey(roleKey); foreach (var permission in role.Permissions) { identity.AddClaim(new Claim(ProCenterClaimType.PermissionClaimType, permission.Name)); } } } }