Example #1
0
        /// <summary>
        /// Convert from model instance
        /// </summary>
        public override object FromModelInstance(Protocol modelInstance, DataContext context, IPrincipal princpal)
        {
            var existingHandler = context.FirstOrDefault <DbProtocolHandler>(o => o.TypeName == modelInstance.HandlerClassName);

            if (existingHandler == null)
            {
                existingHandler = new DbProtocolHandler()
                {
                    Key          = Guid.NewGuid(),
                    CreatedByKey = modelInstance.CreatedByKey ?? princpal.GetUserKey(context).Value,
                    CreationTime = DateTime.Now,
                    IsActive     = true,
                    Name         = modelInstance.HandlerClass.Name,
                    TypeName     = modelInstance.HandlerClassName
                };
                context.Insert(existingHandler);
            }

            // DbProtocol
            return(new DbProtocol()
            {
                Key = modelInstance.Key ?? Guid.NewGuid(),
                CreatedByKey = modelInstance.CreatedByKey ?? princpal.GetUserKey(context).Value,
                CreationTime = modelInstance.CreationTime,
                Name = modelInstance.Name,
                ObsoletedByKey = modelInstance.ObsoletedByKey,
                ObsoletionTime = modelInstance.ObsoletionTime,
                Oid = modelInstance.Oid,
                HandlerKey = existingHandler.Key
            });
        }
Example #2
0
        public void SetLockout(string userName, bool lockout, IPrincipal authContext)
        {
            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }

            this.m_traceSource.TraceInformation("Lockout identity {0} = {1}", userName, lockout);
            try
            {
                // submit the changes
                using (var dataContext = this.m_configuration.Provider.GetWriteConnection())
                {
                    dataContext.Open();
                    new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.UnrestrictedAdministration, authContext).Demand();

                    var user = dataContext.FirstOrDefault <DbSecurityUser>(o => o.UserName.ToLower() == userName.ToLower());
                    if (user == null)
                    {
                        throw new KeyNotFoundException("Specified user does not exist!");
                    }

                    // Obsolete
                    if (lockout)
                    {
                        user.Lockout = DateTime.MaxValue.AddDays(-10);
                    }
                    else
                    {
                        user.Lockout = null;
                    }

                    user.ObsoletionTime = null;
                    user.ObsoletedByKey = null;
                    user.UpdatedByKey   = authContext.GetUserKey(dataContext);
                    user.UpdatedTime    = DateTimeOffset.Now;
                    user.SecurityHash   = Guid.NewGuid().ToString();

                    var updatedUser = dataContext.Update(user);

                    var securityUser = new SecurityUserPersistenceService().ToModelInstance(updatedUser, dataContext, authContext);
                    ApplicationContext.Current.GetService <IDataCachingService>()?.Add(securityUser);
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw;
            }
        }
Example #3
0
        public void DeleteIdentity(string userName, IPrincipal authContext)
        {
            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }

            this.m_traceSource.TraceInformation("Delete identity {0}", userName);
            try
            {
                // submit the changes
                using (var dataContext = this.m_configuration.Provider.GetWriteConnection())
                {
                    dataContext.Open();

                    new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.UnrestrictedAdministration, authContext).Demand();

                    var user = dataContext.FirstOrDefault <DbSecurityUser>(o => o.UserName.ToLower() == userName.ToLower());
                    if (user == null)
                    {
                        throw new KeyNotFoundException("Specified user does not exist!");
                    }

                    // Obsolete
                    user.ObsoletionTime = DateTimeOffset.Now;
                    user.ObsoletedByKey = authContext.GetUserKey(dataContext);
                    user.SecurityHash   = Guid.NewGuid().ToString();

                    dataContext.Update(user);
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw;
            }
        }
Example #4
0
        /// <summary>
        /// Insert the data
        /// </summary>
        public override TModel InsertInternal(DataContext context, TModel data, IPrincipal principal)
        {
            // Ensure exists
            data.CreatedBy?.EnsureExists(context, principal);
            data.CreatedByKey = data.CreatedBy?.Key ?? data.CreatedByKey;

            // first we map the TDataKey entity
            var nonVersionedPortion = m_mapper.MapModelInstance <TModel, TDomainKey>(data);

            // Domain object
            var domainObject = this.FromModelInstance(data, context, principal) as TDomain;

            // First we must assign non versioned portion data
            if (nonVersionedPortion.Key == Guid.Empty &&
                domainObject.Key != Guid.Empty)
            {
                nonVersionedPortion.Key = domainObject.Key;
            }

            if (nonVersionedPortion.Key == null ||
                nonVersionedPortion.Key == Guid.Empty)
            {
                data.Key         = Guid.NewGuid();
                domainObject.Key = nonVersionedPortion.Key = data.Key.Value;
            }
            if (domainObject.VersionKey == null ||
                domainObject.VersionKey == Guid.Empty)
            {
                data.VersionKey         = Guid.NewGuid();
                domainObject.VersionKey = data.VersionKey.Value;
            }

            // Now we want to insert the non versioned portion first
            nonVersionedPortion = context.Insert(nonVersionedPortion);

            // Ensure created by exists
            data.CreatedByKey = domainObject.CreatedByKey = domainObject.CreatedByKey == Guid.Empty ? principal.GetUserKey(context).Value : domainObject.CreatedByKey;

            if (data.CreationTime == DateTimeOffset.MinValue || data.CreationTime.Year < 100)
            {
                data.CreationTime = DateTimeOffset.Now;
            }
            domainObject.CreationTime      = data.CreationTime;
            domainObject.VersionSequenceId = null;
            domainObject         = context.Insert(domainObject);
            data.VersionSequence = domainObject.VersionSequenceId;
            data.VersionKey      = domainObject.VersionKey;
            data.Key             = domainObject.Key;
            data.CreationTime    = (DateTimeOffset)domainObject.CreationTime;
            return(data);
        }
Example #5
0
        /// <summary>
        /// Update the data with new version information
        /// </summary>
        public override TModel UpdateInternal(DataContext context, TModel data, IPrincipal principal)
        {
            if (data.Key == Guid.Empty)
            {
                throw new AdoFormalConstraintException(AdoFormalConstraintType.NonIdentityUpdate);
            }

            data.CreatedBy.EnsureExists(context, principal);
            data.CreatedByKey = data.CreatedBy?.Key ?? data.CreatedByKey;


            // This is technically an insert and not an update
            SqlStatement currentVersionQuery = context.CreateSqlStatement <TDomain>().SelectFrom()
                                               .Where(o => o.Key == data.Key && !o.ObsoletionTime.HasValue)
                                               .OrderBy <TDomain>(o => o.VersionSequenceId, Core.Model.Map.SortOrderType.OrderByDescending);

            var existingObject    = context.FirstOrDefault <TDomain>(currentVersionQuery); // Get the last version (current)
            var nonVersionedObect = context.FirstOrDefault <TDomainKey>(o => o.Key == data.Key);

            if (existingObject == null)
            {
                throw new KeyNotFoundException(data.Key.ToString());
            }
            else if ((existingObject as IDbReadonly)?.IsReadonly == true ||
                     (nonVersionedObect as IDbReadonly)?.IsReadonly == true)
            {
                throw new AdoFormalConstraintException(AdoFormalConstraintType.UpdatedReadonlyObject);
            }

            // Map existing
            var storageInstance = this.FromModelInstance(data, context, principal);

            // Create a new version
            var user             = principal.GetUserKey(context);
            var newEntityVersion = new TDomain();

            newEntityVersion.CopyObjectData(storageInstance);

            // Client did not change on update, so we need to update!!!
            if (!data.VersionKey.HasValue ||
                data.VersionKey.Value == existingObject.VersionKey ||
                context.Any <TDomain>(o => o.VersionKey == data.VersionKey))
            {
                data.VersionKey = newEntityVersion.VersionKey = Guid.NewGuid();
            }

            data.VersionSequence    = newEntityVersion.VersionSequenceId = null;
            newEntityVersion.Key    = data.Key.Value;
            data.PreviousVersionKey = newEntityVersion.ReplacesVersionKey = existingObject.VersionKey;
            data.CreatedByKey       = newEntityVersion.CreatedByKey = data.CreatedByKey ?? user.Value;
            // Obsolete the old version
            existingObject.ObsoletedByKey = data.CreatedByKey ?? user;
            existingObject.ObsoletionTime = DateTimeOffset.Now;
            newEntityVersion.CreationTime = DateTimeOffset.Now;

            context.Update(existingObject);

            newEntityVersion  = context.Insert <TDomain>(newEntityVersion);
            nonVersionedObect = context.Update <TDomainKey>(nonVersionedObect);

            // Pull database generated fields
            data.VersionSequence = newEntityVersion.VersionSequenceId;
            data.CreationTime    = newEntityVersion.CreationTime;

            return(data);
            //return base.Update(context, data, principal);
        }
Example #6
0
        public IIdentity CreateIdentity(string userName, string password, IPrincipal authContext)
        {
            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }
            else if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password));
            }
            else if (authContext == null)
            {
                throw new ArgumentNullException(nameof(authContext));
            }

            this.m_traceSource.TraceInformation("Creating identity {0} ({1})", userName, authContext);

            try
            {
                using (var dataContext = this.m_configuration.Provider.GetWriteConnection())
                {
                    dataContext.Open();

                    using (var tx = dataContext.BeginTransaction())
                        try
                        {
                            var hashingService = ApplicationContext.Current.GetService <IPasswordHashingService>();
                            var pdpService     = ApplicationContext.Current.GetService <IPolicyDecisionService>();

                            // Demand create identity
                            new PolicyPermission(System.Security.Permissions.PermissionState.Unrestricted, PermissionPolicyIdentifiers.CreateIdentity, authContext).Demand();

                            // Does this principal have the ability to
                            DbSecurityUser newIdentityUser = new DbSecurityUser()
                            {
                                UserName     = userName,
                                PasswordHash = hashingService.EncodePassword(password),
                                SecurityHash = Guid.NewGuid().ToString(),
                                UserClass    = UserClassKeys.HumanUser
                            };
                            if (authContext != null)
                            {
                                newIdentityUser.CreatedByKey = authContext.GetUserKey(dataContext).Value;
                            }

                            dataContext.Insert(newIdentityUser);
                            var retVal = AdoClaimsIdentity.Create(newIdentityUser);
                            tx.Commit();
                            return(retVal);
                        }
                        catch
                        {
                            tx.Rollback();
                            throw;
                        }
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw;
            }
        }
Example #7
0
        /// <summary>
        /// Change the user's password
        /// </summary>
        public void ChangePassword(string userName, string newPassword, IPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }
            else if (!principal.Identity.IsAuthenticated)
            {
                throw new SecurityException("Authorization context must be authenticated");
            }

            this.m_traceSource.TraceInformation("Change userpassword for {0} to {1} ({2})", userName, newPassword, principal);

            // Password failed validation
            if (ApplicationContext.Current.GetService <IPasswordValidatorService>()?.Validate(newPassword) == false)
            {
                throw new SecurityException("Password failed validation");
            }

            try
            {
                // Create the hasher and load the user
                using (var dataContext = this.m_configuration.Provider.GetWriteConnection())
                {
                    dataContext.Open();

                    using (var tx = dataContext.BeginTransaction())
                        try
                        {
                            var user = dataContext.SingleOrDefault <DbSecurityUser>(u => u.UserName.ToLower() == userName.ToLower() && !u.ObsoletionTime.HasValue);
                            if (user == null)
                            {
                                throw new InvalidOperationException(String.Format("Cannot locate user {0}", userName));
                            }

                            // Security check
                            var policyDecisionService  = ApplicationContext.Current.GetService <IPolicyDecisionService>();
                            var passwordHashingService = ApplicationContext.Current.GetService <IPasswordHashingService>();

                            var pdpOutcome = policyDecisionService?.GetPolicyOutcome(principal, PermissionPolicyIdentifiers.ChangePassword);
                            if (userName != principal.Identity.Name &&
                                pdpOutcome.HasValue &&
                                pdpOutcome != PolicyDecisionOutcomeType.Grant)
                            {
                                throw new PolicyViolationException(PermissionPolicyIdentifiers.ChangePassword, pdpOutcome.Value);
                            }

                            user.PasswordHash = passwordHashingService.EncodePassword(newPassword);
                            user.SecurityHash = Guid.NewGuid().ToString();
                            user.UpdatedByKey = principal.GetUserKey(dataContext);

                            dataContext.Update(user);
                            tx.Commit();
                        }
                        catch
                        {
                            tx.Rollback();
                            throw;
                        }
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw;
            }
        }