Exemplo n.º 1
0
        /// <summary>
        /// Remove users from roles
        /// </summary>
        public void RemoveUsersFromRoles(string[] users, string[] roles, IPrincipal authPrincipal)
        {
            this.VerifyPrincipal(authPrincipal, PermissionPolicyIdentifiers.AlterRoles);

            // Add users to role
            using (var dataContext = new Data.ModelDataContext(this.m_configuration.ReadWriteConnectionString))
            {
                foreach (var un in users)
                {
                    SecurityUser user = dataContext.SecurityUsers.SingleOrDefault(u => u.UserName == un);
                    if (user == null)
                    {
                        throw new KeyNotFoundException(String.Format("Could not locate user {0}", un));
                    }
                    foreach (var rol in roles)
                    {
                        SecurityRole role = dataContext.SecurityRoles.SingleOrDefault(r => r.Name == rol);
                        if (role == null)
                        {
                            throw new KeyNotFoundException(String.Format("Could not locate role {0}", rol));
                        }

                        var securityUserRole = user.SecurityUserRoles.SingleOrDefault(ur => ur.RoleId == role.RoleId && ur.UserId == user.UserId);

                        if (securityUserRole != null)
                        {
                            // Remove
                            dataContext.SecurityUserRoles.DeleteOnSubmit(securityUserRole);
                        }
                    }
                }

                dataContext.SubmitChanges();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Adds the specified users to the specified roles
        /// </summary>
        public void AddUsersToRoles(string[] users, string[] roles, IPrincipal authPrincipal)
        {
            this.VerifyPrincipal(authPrincipal, PermissionPolicyIdentifiers.AlterRoles);

            // Add users to role
            using (var dataContext = new Data.ModelDataContext(this.m_configuration.ReadWriteConnectionString))
            {
                foreach (var un in users)
                {
                    SecurityUser user = dataContext.SecurityUsers.SingleOrDefault(u => u.UserName == un);
                    if (user == null)
                    {
                        throw new KeyNotFoundException(String.Format("Could not locate user {0}", un));
                    }
                    foreach (var rol in roles)
                    {
                        SecurityRole role = dataContext.SecurityRoles.SingleOrDefault(r => r.Name == rol);
                        if (role == null)
                        {
                            throw new KeyNotFoundException(String.Format("Could not locate role {0}", rol));
                        }
                        if (!user.SecurityUserRoles.Any(o => o.RoleId == role.RoleId))
                        {
                            user.SecurityUserRoles.Add(new SecurityUserRole()
                            {
                                UserId = user.UserId, RoleId = role.RoleId
                            });
                        }
                    }
                }

                dataContext.SubmitChanges();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Insert the specified device entity
        /// </summary>
        public override Core.Model.Entities.DeviceEntity Insert(Data.ModelDataContext context, Core.Model.Entities.DeviceEntity data, IPrincipal principal)
        {
            data.SecurityDevice?.EnsureExists(context, principal);
            data.SecurityDeviceKey = data.SecurityDevice?.Key ?? data.SecurityDeviceKey;

            return(base.Insert(context, data, principal));
        }
        /// <summary>
        /// Insert the specified object
        /// </summary>
        public override Core.Model.Entities.EntityAddress Insert(Data.ModelDataContext context, Core.Model.Entities.EntityAddress data, IPrincipal principal)
        {
            // Ensure exists
            data.AddressUse?.EnsureExists(context, principal);
            data.AddressUseKey = data.AddressUse?.Key ?? data.AddressUseKey;

            var retVal = base.Insert(context, data, principal);

            // Data component
            if (data.Component != null)
            {
                base.UpdateAssociatedItems <Core.Model.Entities.EntityAddressComponent, Data.EntityAddressComponent>(
                    data.Component,
                    data,
                    context,
                    principal);
            }

            return(retVal);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Creates an identity from a hash
 /// </summary>
 internal static SqlClaimsIdentity Create(String userName)
 {
     try
     {
         using (var dataContext = new Data.ModelDataContext(s_configuration.ReadonlyConnectionString))
         {
             var user = dataContext.SecurityUsers.SingleOrDefault(u => !u.ObsoletionTime.HasValue && u.UserName == userName);
             if (user == null)
             {
                 return(null);
             }
             return(new SqlClaimsIdentity(user, false));
         }
     }
     catch (Exception e)
     {
         s_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
         throw new Exception("Creating unauthorized identity failed", e);
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Create a role
        /// </summary>
        public void CreateRole(string roleName, IPrincipal authPrincipal)
        {
            this.VerifyPrincipal(authPrincipal, PermissionPolicyIdentifiers.CreateRoles);

            // Add users to role
            using (var dataContext = new Data.ModelDataContext(this.m_configuration.ReadWriteConnectionString))
            {
                SecurityUser user = dataContext.SecurityUsers.SingleOrDefault(u => u.UserName == authPrincipal.Identity.Name);
                if (user == null)
                {
                    throw new SecurityException(String.Format("Could not verify identity of {0}", authPrincipal.Identity.Name));
                }

                // Insert
                dataContext.SecurityRoles.InsertOnSubmit(new SecurityRole()
                {
                    RoleId          = Guid.NewGuid(),
                    CreatedByEntity = user,
                    Name            = roleName
                });
                dataContext.SubmitChanges();
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// To model instance
        /// </summary>
        public virtual TEntityType ToModelInstance <TEntityType>(Data.EntityVersion dbInstance, Data.ModelDataContext context, IPrincipal principal) where TEntityType : Core.Model.Entities.Entity, new()
        {
            var retVal = m_mapper.MapDomainInstance <Data.EntityVersion, TEntityType>(dbInstance);

            retVal.ClassConceptKey      = dbInstance.Entity.ClassConceptId;
            retVal.DeterminerConceptKey = dbInstance.Entity.DeterminerConceptId;

            // Inversion relationships
            //if (retVal.Relationships != null)
            //{
            //    retVal.Relationships.RemoveAll(o => o.InversionIndicator);
            //    retVal.Relationships.AddRange(context.EntityAssociations.Where(o => o.TargetEntityId == retVal.Key.Value).Distinct().Select(o => new EntityRelationship(o.AssociationTypeConceptId, o.TargetEntityId)
            //    {
            //        SourceEntityKey = o.SourceEntityId,
            //        Key = o.EntityAssociationId,
            //        InversionIndicator = true
            //    }));
            //}

            return(retVal);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a principal based on username and password
        /// </summary>
        internal static SqlClaimsIdentity Create(String userName, String password)
        {
            try
            {
                if (userName == AuthenticationContext.AnonymousPrincipal.Identity.Name ||
                    userName == AuthenticationContext.SystemPrincipal.Identity.Name)
                {
                    throw new PolicyViolationException(PermissionPolicyIdentifiers.Login, PolicyDecisionOutcomeType.Deny);
                }

                Guid?userId = Guid.Empty;

                using (var dataContext = new Data.ModelDataContext(s_configuration.ReadWriteConnectionString))
                {
                    // Attempt to get a user
                    var hashingService = ApplicationContext.Current.GetService <IPasswordHashingService>();

                    var passwordHash = hashingService.EncodePassword(password);
                    dataContext.sp_Authenticate(userName, passwordHash, 3, ref userId);
                }

                using (var dataContext = new Data.ModelDataContext(s_configuration.ReadonlyConnectionString))
                {
                    var user         = dataContext.SecurityUsers.SingleOrDefault(u => u.UserId == userId);
                    var userIdentity = new SqlClaimsIdentity(user, true)
                    {
                        m_authenticationType = "Password"
                    };

                    // Is user allowed to login?
                    if (user.UserClass == UserClassKeys.HumanUser)
                    {
                        new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.Login, new GenericPrincipal(userIdentity, null)).Demand();
                    }
                    else if (user.UserClass == UserClassKeys.ApplicationUser)
                    {
                        new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.LoginAsService, new GenericPrincipal(userIdentity, null)).Demand();
                    }

                    return(userIdentity);
                }
            }
            catch (AuthenticationException)
            {
                // TODO: Audit this
                throw;
            }
            catch (SecurityException)
            {
                // TODO: Audit this
                throw;
            }
            catch (SqlException e)
            {
                switch (e.Number)
                {
                case 51900:
                    throw new AuthenticationException("Account is locked");

                case 51901:
                    throw new AuthenticationException("Invalid username/password");

                case 51902:
                    throw new AuthenticationException("User requires two-factor authentication");

                default:
                    throw e;
                }
            }
            catch (Exception e)
            {
                s_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw new Exception("Creating identity failed", e);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a principal based on username and password
        /// </summary>
        internal static SqlClaimsIdentity Create(byte[] refreshToken)
        {
            try
            {
                Guid?userId = Guid.Empty;

                using (var dataContext = new Data.ModelDataContext(s_configuration.ReadWriteConnectionString))
                {
                    // Attempt to get a user
                    var secretClaim = dataContext.SecurityUserClaims.FirstOrDefault(o => o.ClaimType == SqlServerConstants.RefreshSecretClaimType && o.ClaimValue == BitConverter.ToString(refreshToken).Replace("-", ""));

                    if (secretClaim == null)
                    {
                        throw new SecurityException("Invalid refresh token");
                    }

                    // Next we ensure that the claim isn't expired
                    var expiryClaim = dataContext.SecurityUserClaims.FirstOrDefault(o => o.ClaimType == SqlServerConstants.RefreshExpiryClaimType && o.UserId == secretClaim.UserId);
                    if (expiryClaim == null || DateTimeOffset.Parse(expiryClaim.ClaimValue) < DateTime.Now)
                    {
                        throw new SecurityException("Token expired");
                    }

                    dataContext.sp_Authenticate(secretClaim.SecurityUser.UserName, secretClaim.SecurityUser.UserPassword, 3, ref userId);
                }

                using (var dataContext = new Data.ModelDataContext(s_configuration.ReadonlyConnectionString))
                {
                    var user         = dataContext.SecurityUsers.SingleOrDefault(u => u.UserId == userId);
                    var userIdentity = new SqlClaimsIdentity(user, true)
                    {
                        m_authenticationType = "Refresh"
                    };

                    // Is user allowed to login?
                    if (user.UserClass == UserClassKeys.HumanUser)
                    {
                        new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.Login, new GenericPrincipal(userIdentity, null)).Demand();
                    }
                    else if (user.UserClass == UserClassKeys.ApplicationUser)
                    {
                        new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.LoginAsService, new GenericPrincipal(userIdentity, null)).Demand();
                    }

                    return(userIdentity);
                }
            }
            catch (AuthenticationException)
            {
                // TODO: Audit this
                throw;
            }
            catch (SecurityException)
            {
                // TODO: Audit this
                throw;
            }
            catch (SqlException e)
            {
                switch (e.Number)
                {
                case 51900:
                    throw new AuthenticationException("Account is locked");

                case 51901:
                    throw new AuthenticationException("Invalid username/password");

                case 51902:
                    throw new AuthenticationException("User requires two-factor authentication");

                default:
                    throw e;
                }
            }
            catch (Exception e)
            {
                s_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw new Exception("Creating identity failed", e);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Convert the database representation to a model instance
        /// </summary>
        public override Core.Model.Entities.DeviceEntity ToModelInstance(object dataInstance, Data.ModelDataContext context, IPrincipal principal)
        {
            var idp          = dataInstance as IDbVersionedData;
            var deviceEntity = dataInstance as Data.DeviceEntity ?? context.GetTable <Data.DeviceEntity>().Where(o => o.EntityVersionId == idp.VersionId).First();
            var dbe          = dataInstance as Data.EntityVersion ?? context.GetTable <Data.EntityVersion>().Where(o => o.EntityVersionId == deviceEntity.EntityVersionId).First();
            var retVal       = m_entityPersister.ToModelInstance <Core.Model.Entities.DeviceEntity>(dbe, context, principal);

            retVal.SecurityDeviceKey     = deviceEntity.DeviceId;
            retVal.ManufacturerModelName = deviceEntity.ManufacturedModelName;
            retVal.OperatingSystemName   = deviceEntity.OperatingSystemName;
            return(retVal);
        }