예제 #1
0
        public byte[] ConvertGridToExcel(InMemoryUser user, ApplicationSchemaDefinition schema, IEnumerable <AttributeHolder> rows)
        {
            IEnumerable <ApplicationFieldDefinition> applicationFields = schema.Fields;

            using (var resultStream = new MemoryStream())
                using (var ms = new MemoryStream())
                    using (var xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook)) {
                        //                var ms = new MemoryStream();

                        // attributes of elements
                        // the xml writer

                        OpenXmlWriter writer;
                        int           rowIdx;
                        var           worksheetpart = Setup(xl, out writer, out rowIdx, schema);

                        // create header row
                        CreateHeaderRow(applicationFields, writer, rowIdx, schema.Name, schema.SchemaId);
                        //count up row
                        rowIdx++;

                        // write data rows
                        DoWriteRows(user, schema, rows, rowIdx, writer, applicationFields);


                        Finish(writer, xl, worksheetpart);

                        return(ms.ToArray());
                    }
        }
예제 #2
0
        public HomeModel(string url, string title, HomeConfigs configs, InMemoryUser user, bool hasLogoPopup,
                         JObject i18NJsons, string clientName, string initialModule, string windowTitle = null, string message = null, string messageType = null)
        {
            Allowed        = true;
            Url            = url;
            InitTimeMillis = configs.InitTimeMillis;
            Title          = title;
            InitialModule  = initialModule;
            ConfigJSON     = JsonConvert.SerializeObject(configs, Newtonsoft.Json.Formatting.None,
                                                         new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            UserJSON = JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.None,
                                                   new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
            HasPopupLogo = hasLogoPopup;
            I18NJsons    = i18NJsons.ToString(Newtonsoft.Json.Formatting.Indented);
            WindowTitle  = windowTitle;
            Message      = message;
            MessageType  = messageType;
        }
예제 #3
0
 public MyProfileModel(InMemoryUser user, List <LocationCostCenterRestriction> locationCostCenterRestrictions, bool canViewRestrictions, bool canChangeLanguage)
 {
     _user                = user;
     _restrictions        = locationCostCenterRestrictions;
     _canViewRestrictions = canViewRestrictions;
     _canChangeLanguage   = canChangeLanguage;
 }
예제 #4
0
        private static InMemoryUser UserFound(User dbUser, string userTimezoneOffset)
        {
            int?userTimezoneOffsetInt = null;
            int tmp;

            if (Int32.TryParse(userTimezoneOffset, out tmp))
            {
                userTimezoneOffsetInt = tmp;
            }

            var profiles     = UserProfileManager.FindUserProfiles(dbUser);
            var inMemoryUser = new InMemoryUser(dbUser, profiles, userTimezoneOffsetInt);

            if (_users.ContainsKey(inMemoryUser.Login))
            {
                _users.Remove(inMemoryUser.Login);
            }
            try {
                _users.Add(inMemoryUser.Login, inMemoryUser);
            } catch {
                Log.Warn("Duplicate user should not happen here " + inMemoryUser.Login);
            }
            LogicalThreadContext.SetData("user", dbUser.UserName);
            _eventDispatcher.Dispatch(new UserLoginEvent(inMemoryUser));
            if (Log.IsDebugEnabled)
            {
                Log.Debug(String.Format("user:{0} logged in with roles {1}; profiles {2}; locations {3}",
                                        inMemoryUser.Login,
                                        string.Join(",", inMemoryUser.Roles),
                                        string.Join(",", inMemoryUser.Profiles),
                                        string.Join(",", inMemoryUser.PersonGroups)
                                        ));
            }
            return(inMemoryUser);
        }
예제 #5
0
        public static String ConvertAllValues(String input, InMemoryUser user)
        {
            string valueParsed = null;

            input = ReadFromUserGenericProperties(input, user);

            foreach (var pastFunction in StringUtil.GetSubStrings(input, PastFunctionPrefix, FunctionSuffix))
            {
                valueParsed = ParsePastAndFutureFunction(pastFunction, -1, DBDateTimeFormat);
                input       = input.Replace(pastFunction, "'" + valueParsed + "'");
            }

            foreach (var futureFunction in StringUtil.GetSubStrings(input, FutureFunctionPrefix, FunctionSuffix))
            {
                valueParsed = ParsePastAndFutureFunction(futureFunction, 1, DBDateTimeFormat);
                input       = input.Replace(futureFunction, "'" + valueParsed + "'");
            }

            foreach (var keyword in StringUtil.GetSubStrings(input, "@"))
            {
                valueParsed = GetDefaultValue(keyword, user);
                input       = input.Replace("'" + keyword + "'", "'" + valueParsed + "'").Replace(keyword, "'" + valueParsed + "'");
            }

            return(input);
        }
예제 #6
0
        private void BuildNotify(IOperationData operationData, DynamicObject proxy, InMemoryUser curUser)
        {
            Type          type            = proxy.ProxyType;
            MethodInfo    mi              = type.GetMethod(_MethodName);
            ParameterInfo pi              = mi.GetParameters().First();
            object        notifyInterface = r.InstanceFromType(pi.ParameterType);
            var           header          = r.InstantiateProperty(notifyInterface, "Header");

            r.InstantiateProperty(header, "SenderID", new { Value = SwConstants.ExternalSystemName });
            r.SetProperty(notifyInterface, "Header", header);
            var    rootIntegrationObject = r.InstantiateArrayReturningSingleElement(notifyInterface, "Content");
            object integrationObject     = r.InstantiateProperty(rootIntegrationObject, 0);

            r.SetProperty(integrationObject, "actionSpecified", true);
            r.InstantiateProperty(integrationObject, "CHANGEDATE", new { Value = DateTime.Now.FromServerToRightKind() });
            //TODO: get current user, in the mobile case below code may be wrong
            WsUtil.SetValue(integrationObject, "ORGID", curUser.OrgId);
            WsUtil.SetValue(integrationObject, "SITEID", curUser.SiteId);
            r.InstantiateProperty(integrationObject, "CHANGEBY", new { Value = curUser.Login });
            OperationType  operationType = operationData.OperationType;
            EntityMetadata metadata      = operationData.EntityMetadata;

            r.SetProperty(integrationObject, "action", operationType.ToString());
            Proxy               = proxy;
            IntegrationObject   = integrationObject;
            RootInterfaceObject = notifyInterface;
        }
예제 #7
0
        /// <summary>
        /// retrieve a clone of the completemetadata, applying evental security restrictions associated for a given user
        /// </summary>
        /// <param name="originalMetadata"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static CompleteApplicationMetadataDefinition CloneSecuring(this CompleteApplicationMetadataDefinition originalMetadata,
                                                                          InMemoryUser user)
        {
            var schemas        = originalMetadata.Schemas();
            var securedSchemas = new Dictionary <ApplicationMetadataSchemaKey, ApplicationSchemaDefinition>();

            foreach (var applicationSchema in schemas)
            {
                if (applicationSchema.Value.IsWebPlatform())
                {
                    continue;
                }
                var securedMetadata = originalMetadata.ApplyPolicies(applicationSchema.Key, user, ClientPlatform.Mobile);
                securedSchemas.Add(securedMetadata.Schema.GetSchemaKey(), securedMetadata.Schema);
            }

            return(new CompleteApplicationMetadataDefinition(
                       originalMetadata.Id,
                       originalMetadata.ApplicationName,
                       originalMetadata.Title,
                       originalMetadata.Entity,
                       originalMetadata.IdFieldName,
                       originalMetadata.Parameters, securedSchemas, originalMetadata.DisplayableComponents,
                       originalMetadata.Service));
        }
예제 #8
0
        public static List <InMemoryUser> Users()
        {
            var u1 = new InMemoryUser
            {
                Username = "******",
                Password = "******",
                Subject  = "1",
                Claims   = new[]
                {
                    new Claim(Constants.ClaimTypes.GivenName, "Bob"),
                    new Claim(Constants.ClaimTypes.FamilyName, "Smith"),
                    new Claim(Constants.ClaimTypes.Email, "*****@*****.**"),
                    new Claim(Constants.ClaimTypes.Role, "BadAssAdmin")
                }
            };

            var u2 = new InMemoryUser
            {
                Username = "******",
                Password = "******",
                Subject  = "S-1-5-21-226636460-1763764126-764655366-1107",
                Claims   = new[]
                {
                    new Claim(Constants.ClaimTypes.GivenName, "Mike"),
                    new Claim(Constants.ClaimTypes.FamilyName, "Doerfler"),
                    new Claim(Constants.ClaimTypes.Email, "*****@*****.**"),
                    new Claim(Constants.ClaimTypes.Role, "KickAssDev")
                }
            };

            return(new List <InMemoryUser> {
                u1, u2
            });
        }
예제 #9
0
        private Boolean HandleNonCustomerApprovers(InMemoryUser user, IEnumerable <Dictionary <string, object> > wfassignment, string approvalGroup,
                                                   IDictionary <string, object> approval, IEnumerable <Dictionary <string, object> > wftransactions, Dictionary <string, object> rejectedTransaction)
        {
            //locate assignment
            var assignment = wfassignment.FirstOrDefault(f => f[c.RoleIdColumn].ToString().EqualsIc(approvalGroup));

            approval["#shouldshowaction"] = user.HasPersonGroup(approvalGroup);
            if (assignment == null)
            {
                //nothing has been done, so it needs approval still
                return(true);
            }
            var wfid    = assignment[c.WfIdColumn];
            var txs     = wftransactions.Where(tx => tx[c.WfIdColumn].ToString().Equals(wfid));
            var txToUse = txs.LastOrDefault();

            //locate the oldest tx of that assignment and use it´s data
            if (txToUse != null)
            {
                approval[c.ChangeByColumn]   = txToUse[c.PersonIdColumn];
                approval[c.ChangeDateColumn] = txToUse[c.TransDateColumn];
                approval[c.StatusColumn]     = GetStatusForPart1(rejectedTransaction, txToUse);
            }
            Log.DebugFormat("non customer approval handled " + string.Join(", ", approval.Select(m => m.Key + ":" + m.Value).ToArray()));
            //TODO: is this logic correct? if the status of the approvergroup is already rejected why should we give the user any chance to change it?
            return(!approval.ContainsKey(c.StatusColumn) || !approval[c.StatusColumn].EqualsAny(c.ApprovedStatus, c.RejectedStatus));
        }
예제 #10
0
        /// <summary>
        /// if user is external, then inactivate all %IFU% roles, and if internal, inactivate all %EFU% roles.
        ///
        /// This is double check to avoid wrong scenarios on maximo side
        ///
        ///
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public InMemoryUser HandleExternalUser(InMemoryUser user)
        {
            var isExternalUser =
                user.PersonGroups.Any(f => f.PersonGroup.Name.Equals(c.HExternalUser));
            var prefixToInactivate = isExternalUser ? c.InternalRolesPrefix : c.ExternalRolesPrefix;

            if (!isEndUserOrITC(user))
            {
                //not external, nor enduser(with roles), nor itc... user is ordinary enduser!
                prefixToInactivate = c.BaseHapagPrefixNoWildcard;
            }

            foreach (var role in user.Roles)
            {
                var module = _hapagModules.FirstOrDefault(m => m.Value.Name.Equals(role.Name));
                if (module.Key != null && module.Key.StartsWith(prefixToInactivate))
                {
                    Log.WarnFormat("marking role {0} as inactive to user {1}", role.Name, user.Login);
                    role.Active = false;
                }
            }

            if (user.IsInRole(FunctionalRole.Offering.ToString()) && !(user.IsInRole(FunctionalRole.Tom.ToString()) || user.IsInRole(FunctionalRole.Itom.ToString())))
            {
                //offering require either tom or itom, as due to thomas email comments
                user.Roles.First(r => r.Name.EqualsIc(FunctionalRole.Offering.ToString())).Active = false;
            }



            return(user);
        }
예제 #11
0
        public async Task <ActionResult> QQLogin(NewUserViewModel viewModel)
        {
            var owinContext = Request.GetOwinContext();
            var identity    = await owinContext.Environment.GetIdentityServerPartialLoginAsync();

            if (identity == null || identity.IsAuthenticated == false)
            {
                return(new HttpUnauthorizedResult());
            }

            var qqConnectProfile = new QQConnectProfile(identity.Claims);

            var newUser = new InMemoryUser
            {
                Username   = viewModel.UserName ?? "Default Name",
                Subject    = Guid.NewGuid().ToString(),
                Enabled    = true,
                Provider   = qqConnectProfile.Issuer,
                ProviderId = qqConnectProfile.OpenId,
                Claims     = new[]
                {
                    new Claim(Constants.ClaimTypes.NickName, qqConnectProfile.NickName),
                    new Claim(Constants.ClaimTypes.Picture, qqConnectProfile.Avatar),
                }
            };

            Users.All.Add(newUser);

            var resumeUrl = await owinContext.Environment.GetPartialLoginResumeUrlAsync();

            return(Redirect(resumeUrl));
        }
        public static IEnumerable <InMemoryUser> Get()
        {
            var users = new InMemoryUser[]
            {
                new InMemoryUser {
                    Subject = "818727", Username = "******", Password = "******",
                    Claims  = new Claim[]
                    {
                        new Claim(Constants.ClaimTypes.Name, "Alice Smith"),
                        new Claim(Constants.ClaimTypes.GivenName, "Alice"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Smith"),
                        new Claim(Constants.ClaimTypes.Email, "*****@*****.**"),
                        new Claim(Constants.ClaimTypes.Role, "Admin"),
                        new Claim(Constants.ClaimTypes.Role, "Geek"),
                        new Claim(Constants.ClaimTypes.WebSite, "http://alice.com")
                    }
                },
                new InMemoryUser {
                    Subject = "88421113", Username = "******", Password = "******",
                    Claims  = new Claim[]
                    {
                        new Claim(Constants.ClaimTypes.Name, "Bob Smith"),
                        new Claim(Constants.ClaimTypes.GivenName, "Bob"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Smith"),
                        new Claim(Constants.ClaimTypes.Email, "*****@*****.**"),
                        new Claim(Constants.ClaimTypes.Role, "Developer"),
                        new Claim(Constants.ClaimTypes.Role, "Geek"),
                        new Claim(Constants.ClaimTypes.WebSite, "http://bob.com")
                    }
                },
            };

            return(users);
        }
예제 #13
0
        public static List <InMemoryUser> Get()
        {
            List <InMemoryUser> result = null;

            using (DBEntities db = new DBEntities())
            {
                List <USERINFO> users = db.USERINFO.Take <USERINFO>(5000).ToList <USERINFO>();
                if (null != users && users.Count > 0)
                {
                    result = new List <InMemoryUser>();
                    foreach (USERINFO user in users)
                    {
                        InMemoryUser u = new InMemoryUser
                        {
                            Subject  = user.USERID.ToString(),
                            Username = user.USERNAME,
                            Password = user.PASSWORD,
                            Claims   = new[]
                            {
                                new Claim("userinfo", Newtonsoft.Json.JsonConvert.SerializeObject(user))
                            }
                        };
                        result.Add(u);
                    }
                }
            }
            return(result);
        }
예제 #14
0
        /// <summary>
        /// If the user is not an external user, i.e TUI or SSO, we need to add default roles to it, so that the "enduser" actions become visible;
        /// otherwise, the sso/tui roles will take control over it
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public InMemoryUser HandleSsotuiModulesMerge(InMemoryUser user)
        {
            var isExternalUser = user.PersonGroups.Any(f => f.PersonGroup.Name.Equals(c.HExternalUser));
            var isSSO          = isExternalUser && user.PersonGroups.Any(f => f.PersonGroup.Name.Equals(c.SSO));
            var isTui          = isExternalUser && user.PersonGroups.Any(f => f.PersonGroup.Name.Equals(c.Tui));


            var dbUser = user.DBUser;

            if (dbUser.CustomRoles == null)
            {
                dbUser.CustomRoles = new HashedSet <UserCustomRole>();
            }
            if (!isSSO && !isTui)
            {
                //if not a tui nor sso, we need to add the default items on the menu (enduser...)
                AddCustomRole(user, RoleType.Defaulthome);
                AddCustomRole(user, RoleType.Defaultnewsr);
                AddCustomRole(user, RoleType.Defaultsrgrid);
                AddCustomRole(user, RoleType.Defaultssrsearch);
            }
            else
            {
                //otherwise, these items cannot be seem, just the module ones
                RemoveCustomRole(user, RoleType.Defaulthome);
                RemoveCustomRole(user, RoleType.Defaultnewsr);
                RemoveCustomRole(user, RoleType.Defaultsrgrid);
                RemoveCustomRole(user, RoleType.Defaultssrsearch);

                //remove it due to legacy data on swdb
                RemoveCustomRole(user, RoleType.IncidentDetailsReport);
            }
            return(user);
        }
        protected override IAddressBookContactsService GetContactsService(
            InMemoryDataContext dataContext, ref IEnumerable <IAddressBookContact> contacts)
        {
            if (contacts != null)
            {
                dataContext.Contacts.AddRange(contacts);
            }
            contacts = dataContext.Contacts;

            dataContext.Users.Add(
                User = new InMemoryUser
            {
                Active       = true,
                Email        = SecurityTestData.User.Email,
                PasswordHash = HashService.Hash64(SecurityTestData.User.CorrectPassword)
            }
                );

            dataContext.Sessions.Add(
                Session = new InMemorySession
            {
                User      = User,
                ExpiresOn = DateTime.UtcNow.AddDays(1)
            });

            return(new AddressBookContactsService(
                       new InMemoryAddressBookContactsDataService(dataContext),
                       new SecurityService(
                           new InMemoryUserDataService(dataContext),
                           new InMemorySessionDataService(dataContext),
                           HashService,
                           new UserRegistrationValidator()
                           )
                       ));
        }
예제 #16
0
 private static string ReadFromUserGenericProperties(string text, InMemoryUser user)
 {
     try {
         var innerReference = Regex.Split(text, UserPrefix);
         foreach (var s in innerReference)
         {
             if (s.StartsWith("properties"))
             {
                 var start  = s.IndexOf('[') + 2;
                 var lenght = (s.IndexOf(']') - 1) - start;
                 var key    = s.Substring(start, lenght);
                 if (user.Genericproperties.ContainsKey(key))
                 {
                     object value;
                     if (user.Genericproperties.TryGetValue(key, out value))
                     {
                         var property = UserPrefix + "properties['" + key + "']";
                         text = text.Replace(property, value.ToString());
                     }
                 }
             }
         }
         return(text);
     } catch {
         return(text);
     }
 }
        public static IEnumerable <InMemoryUser> Get()
        {
            var users = new InMemoryUser[]
            {
                new InMemoryUser {
                    Subject = "818727", Username = "******", Password = "******",
                    Claims  = new Claim[]
                    {
                        new Claim(Constants.ClaimTypes.Name, "Alice Smith"),
                        new Claim(Constants.ClaimTypes.GivenName, "Alice"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Smith"),
                        new Claim(Constants.ClaimTypes.Email, "*****@*****.**"),
                    }
                },
                new InMemoryUser {
                    Subject = "88421113", Username = "******", Password = "******",
                    Claims  = new Claim[]
                    {
                        new Claim(Constants.ClaimTypes.Name, "Bob Smith"),
                        new Claim(Constants.ClaimTypes.GivenName, "Bob"),
                        new Claim(Constants.ClaimTypes.FamilyName, "Smith"),
                        new Claim(Constants.ClaimTypes.Email, "*****@*****.**"),
                    }
                },
            };

            return(users);
        }
예제 #18
0
        public IGenericResponseResult Expand(InMemoryUser user, IDictionary <string, ApplicationCompositionSchema> compositionSchemas, CompositionExpanderHelper.CompositionExpansionOptions options)
        {
            var resultDict = new Dictionary <string, IEnumerable <IDictionary <string, object> > >();
            var result     = CompositionExpanderHelper.ParseDictionary(options.CompositionsToExpand);
            var printMode  = _contextLookuper.LookupContext().PrintMode;

            foreach (var toExpand in result.DetailsToExpand)
            {
                var name = toExpand.Key;
                var compositionSchema = compositionSchemas[name];
                var schema            = compositionSchema.Schemas.Detail;
                if (printMode)
                {
                    schema = compositionSchema.Schemas.Print;
                }
                var applicationMetadata = MetadataProvider.Application(EntityUtil.GetApplicationName(name))
                                          .ApplyPolicies(schema.GetSchemaKey(), user, ClientPlatform.Web);
                var slicedEntityMetadata = MetadataProvider.SlicedEntityMetadata(applicationMetadata);
                var searchDTO            = new SearchRequestDto();
                searchDTO.AppendSearchParam(schema.IdFieldName);
                searchDTO.AppendSearchValue(toExpand.Value);
                var compositionExpanded = _entityRepository.GetAsRawDictionary(slicedEntityMetadata, searchDTO);
                resultDict.Add(name, compositionExpanded.ResultList);
            }

            return(new GenericResponseResult <Dictionary <string, IEnumerable <IDictionary <string, object> > > >(resultDict));
        }
예제 #19
0
        private static GenericResponseResult <IList <DashboardDefinition> > DoGetFromList(List <DashboardDefinition> dashboardDefinitionList)
        {
            InMemoryUser user          = SecurityFacade.CurrentUser();
            var          dataObjectSet = new BaseApplicationDataSet();

            DashboardModuleHandler(dashboardDefinitionList);

            foreach (var definition in dashboardDefinitionList)
            {
                var key = new ApplicationMetadataSchemaKey(definition.SchemaId, definition.Mode, ClientPlatform.Web);
                var searchRequestDto = new SearchRequestDto {
                    SearchParams = definition.SearchParams,
                    SearchValues = definition.SearchValues,
                    Context      = new ApplicationLookupContext {
                        MetadataId = definition.Id
                    }
                };
                var applicationMetadata = MetadataProvider.Application(definition.ApplicationName)
                                          .ApplyPolicies(key, user, ClientPlatform.Web);

                definition.TotalCount = dataObjectSet.GetCount(applicationMetadata, searchRequestDto);
            }
            return(new GenericResponseResult <IList <DashboardDefinition> >(dashboardDefinitionList, null)
            {
                Title = new I18NResolver().I18NValue("_headermenu.serviceit", "ServiceIT")
            });
        }
예제 #20
0
        public byte[] ConvertGridToCsv(InMemoryUser user, ApplicationSchemaDefinition schema, IEnumerable <AttributeHolder> rows, Func <AttributeHolder, ApplicationFieldDefinition, string, string> ColumnValueDelegate = null)
        {
            var csv = new StringBuilder();
            var enumerableFields = schema.Fields.Where(ShouldShowField());
            var fields           = enumerableFields as IList <ApplicationFieldDefinition> ?? enumerableFields.ToList();
            // HEADER: line of comma separated labels
            var header = string.Join(",", fields.Select(field => GetI18NLabel(field, schema.Name)));

            csv.AppendLine(header);
            // ROWS
            rows.ForEach(item => {
                var row    = new StringBuilder();
                var values = fields.Select(field => {
                    var data = GetValueAsString(item, field);
                    if (ColumnValueDelegate != null)
                    {
                        data = ColumnValueDelegate(item, field, data);
                    }
                    var displayableData = AsDisplayableData(data, field, user);
                    return(AsCsvCompliantData(displayableData));
                });
                row.Append(string.Join(",", values));
                csv.AppendLine(row.ToString());
            });
            // dump to byte array
            return(Encoding.UTF8.GetBytes(csv.ToString()));
            //            return csv.ToString().GetBytes();
        }
예제 #21
0
        public InMemoryUser RemoveOrphanEntities(InMemoryUser user)
        {
            Iesi.Collections.Generic.ISet <Role> rolesToRemove = new HashedSet <Role>();

            Iesi.Collections.Generic.ISet <UserCustomRole> customRolesToDelete = new HashedSet <UserCustomRole>();
            Iesi.Collections.Generic.ISet <UserProfile>    profilesToremove    = new HashedSet <UserProfile>();
            foreach (var role in _hapagModules.Keys)
            {
                if (user.Roles.Contains(_hapagModules[role]) &&
                    !user.PersonGroups.Any(r => r.PersonGroup.Name.Equals(role)))
                {
                    rolesToRemove.Add(_hapagModules[role]);
                }
            }

            foreach (var profile in _hapagProfiles.Keys)
            {
                if (user.Profiles.Contains(_hapagProfiles[profile]) &&
                    !user.PersonGroups.Any(r => r.PersonGroup.Name.Equals(profile)))
                {
                    profilesToremove.Add(_hapagProfiles[profile]);
                }
            }



            if (!rolesToRemove.Any() && !profilesToremove.Any())
            {
                return(user);
            }

            var dbUser = user.DBUser;

            if (profilesToremove.Any())
            {
                foreach (var userProfile in profilesToremove)
                {
                    dbUser.Profiles.Remove(userProfile);
                }
                _dao.Save(dbUser);
            }

            if (rolesToRemove.Any())
            {
                foreach (var role in rolesToRemove)
                {
                    var customRole = dbUser.CustomRoles.FirstOrDefault(cr => cr.Role.Equals(role));
                    if (customRole == null)
                    {
                        continue;
                    }
                    customRolesToDelete.Add(customRole);
                    dbUser.CustomRoles.Remove(customRole);
                }
                _dao.DeleteCollection(customRolesToDelete);
            }

            return(new InMemoryUser(dbUser, dbUser.Profiles, user.TimezoneOffset));
        }
예제 #22
0
 public static bool HasPersonGroup(this InMemoryUser value, string groupName)
 {
     if (value.PersonGroups == null)
     {
         return(false);
     }
     return(value.PersonGroups.Any(p => p.PersonGroup.Name == groupName));
 }
예제 #23
0
 private bool isEndUserOrITC(InMemoryUser user)
 {
     if (user.HasProfile(ProfileType.Itc))
     {
         return(true);
     }
     return(user.PersonGroups.Any(f => f.PersonGroup.Name.EqualsAny(c.HEu, c.HExternalUser, c.HITC)));
 }
예제 #24
0
 public async Task DeleteUserTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("Delete");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     UnitTestHelper.IsSuccess(await manager.DeleteAsync(user));
     Assert.Null(await manager.FindByIdAsync(user.Id));
 }
예제 #25
0
 private static DateTime UserMaximoConversion(DateTime date, InMemoryUser user, bool fromUserToMaximo, int?maximoOffset = null)
 {
     if (user == null || !user.TimezoneOffset.HasValue)
     {
         return(date);
     }
     return(MaximoConversion(date, user.TimezoneOffset.Value, fromUserToMaximo, maximoOffset));
 }
예제 #26
0
 public static bool ValidateRegionSelectionIsAllowed(ContextHolder ctx, InMemoryUser user, bool forceXITCContext = false)
 {
     if (forceXITCContext || ctx.IsInModule(FunctionalRole.XItc))
     {
         return(user.IsWWUser());
     }
     return(ctx.IsInAnyModule(FunctionalRole.Tom, FunctionalRole.Itom, FunctionalRole.Purchase,
                              FunctionalRole.AssetControl));
 }
예제 #27
0
        private bool HandleCustomerApprovers(InMemoryUser user, AttributeHolder result, string approvalGroup, IEnumerable <Dictionary <string, object> > worklogs, IDictionary <string, object> approval,
                                             IEnumerable <Dictionary <string, object> > wostatus)
        {
            //https://controltechnologysolutions.atlassian.net/browse/HAP-976
            //https://controltechnologysolutions.atlassian.net/browse/HAP-1113 --> changing the way it filters the status
            worklogs = FilterWorkLogsOlderThanLatestAuth(worklogs, wostatus);

            var wlEnumerable = worklogs as Dictionary <string, object>[] ?? worklogs.ToArray();

            var apprDescription = c.GetWorkLogDescriptions(approvalGroup, true);
            var rejDescription  = c.GetWorkLogDescriptions(approvalGroup, false);


            var apprWl = wlEnumerable.FirstOrDefault(w =>
                                                     apprDescription.EqualsIc(w["description"] as string) &&
                                                     c.WlApprLogType.EqualsIc(w["logtype"] as string) &&
                                                     w["recordkey"].Equals(result.GetAttribute("wonum"))
                                                     );

            var rejWl = wlEnumerable.FirstOrDefault(w =>
                                                    rejDescription.EqualsIc(w["description"] as string) &&
                                                    c.WlRejLogType.EqualsIc(w["logtype"] as string) &&
                                                    w["recordkey"].Equals(result.GetAttribute("wonum"))
                                                    );

            var anyrejWl = wlEnumerable.FirstOrDefault(w =>
                                                       (w["description"] != null && w["description"].ToString().StartsWith(c.RejectedWorklogDescription, StringComparison.CurrentCultureIgnoreCase)) &&
                                                       w["logtype"].ToString().Equals(c.WlRejLogType) &&
                                                       w["recordkey"].Equals(result.GetAttribute("wonum"))
                                                       );

            //approval["#shouldshowaction"] = LevelMatches(result, approval) && user.HasPersonGroup(approvalGroup); ;
            //removed due to thomas comments, on HAP-976
            approval["#shouldshowaction"] = user.HasPersonGroup(approvalGroup);
            ;

            if (apprWl != null || rejWl != null)
            {
                Log.DebugFormat("Specific approval or rejected worklog found");

                approval[c.ChangeByColumn]    = apprWl != null ? apprWl[c.CreateByColumn] : rejWl[c.CreateByColumn];
                approval[c.ChangeDateColumn]  = apprWl != null ? apprWl[c.CreateDate] : rejWl[c.CreateDate];
                approval[c.StatusColumn]      = apprWl != null ? c.ApprovedStatus : c.RejectedStatus;
                approval["#shouldshowaction"] = false;
            }
            else if (anyrejWl != null)
            {
                Log.DebugFormat("At least one rejected worklog found scenario");
                //if there´s a rejected worklog on the level, then all groups should be rejected, except the ones that might have approved it already...
                approval[c.StatusColumn] = c.RejectedStatus;
                //HAP-993 if any of the groups rejected it, we should no longer display the actions
                approval["#shouldshowaction"] = false;
            }
            Log.DebugFormat("customer approval handled " + string.Join(", ", approval.Select(m => m.Key + ":" + m.Value).ToArray()));
            //if this group has not yet been approved or rejectd, it will still require some action (maybe not by this user)
            return(!approval.ContainsKey(c.StatusColumn) || !approval[c.StatusColumn].EqualsAny(c.ApprovedStatus, c.RejectedStatus));
        }
        public void SiteId()
        {
            var user = InMemoryUser.TestInstance();

            user.Login  = "******";
            user.SiteId = "testsite";
            string result = qb.ConvertAllValues("status='WAPPR' and reportedby=@username and siteid='@usersite'", user);

            Assert.AreEqual("status='WAPPR' and reportedby='test' and siteid='testsite'", result);
        }
예제 #29
0
        public static DateTime FromUserToRightKind(this DateTime date, InMemoryUser user)
        {
            var kind = ApplicationConfiguration.IsISM() ? DateTimeKind.Utc : DateTimeKind.Local;

            if (kind.Equals(DateTimeKind.Utc))
            {
                return(date.FromUserToUtc(user));
            }
            return(date.ToServerTimezone(user));
        }
예제 #30
0
        private static void RemoveCustomRole(InMemoryUser user, RoleType type)
        {
            var dbUser = user.DBUser;

            dbUser.CustomRoles.Remove(new UserCustomRole {
                Role   = _cachedDefaultRoles[type],
                UserId = dbUser.Id
            });
            user.Roles.Remove(_cachedDefaultRoles[type]);
        }
        private static AuthenticateResult GetAuthenticateResult(InMemoryUser user)
        {
            var authenticateResult = new AuthenticateResult(user.Subject,
                                                            user.Username,
                                                            user.Claims,
                                                            Constants.BuiltInIdentityProvider,
                                                            Constants.AuthenticationMethods.Password);

            return(authenticateResult);
        }
        private async Task IssueCookie(
            InMemoryUser user, 
            string idp,
            string amr)
        {
            var name = user.Claims.Where(x => x.Type == JwtClaimTypes.Name).Select(x => x.Value).FirstOrDefault() ?? user.Username;

            var claims = new Claim[] {
                        new Claim(JwtClaimTypes.Subject, user.Subject),
                        new Claim(JwtClaimTypes.Name, name),
                        new Claim(JwtClaimTypes.IdentityProvider, idp),
                        new Claim(JwtClaimTypes.AuthenticationTime, DateTime.UtcNow.ToEpochTime().ToString()),
                    };
            var ci = new ClaimsIdentity(claims, amr, JwtClaimTypes.Name, JwtClaimTypes.Role);
            var cp = new ClaimsPrincipal(ci);

            await HttpContext.Authentication.SignInAsync(Constants.PrimaryAuthenticationType, cp);
        }
        public InMemoryUser AutoProvisionUser(string provider, string userId, List<Claim> claims)
        {
            var filtered = new List<Claim>();
            foreach(var claim in claims)
            {
                if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.ContainsKey(claim.Type))
                {
                    filtered.Add(new Claim(JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[claim.Type], claim.Value));
                }
                else
                {
                    filtered.Add(claim);
                }
            }

            if (!filtered.Any(x=>x.Type == JwtClaimTypes.Name))
            {
                var first = filtered.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value;
                var last = filtered.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
            }

            var sub = Guid.NewGuid().ToString();
            var user = new InMemoryUser()
            {
                Enabled = true,
                Subject = sub,
                Username = sub,
                Provider = provider,
                ProviderId = userId,
                Claims = filtered
            };
            _users.Add(user);
            return user;
        }
예제 #34
0
 public async Task AddDupeUserFailsTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("dupe");
     var user2 = new InMemoryUser("dupe");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     UnitTestHelper.IsFailure(await manager.CreateAsync(user2), "Name dupe is already taken.");
 }
예제 #35
0
 public async Task RemoveUserFromRoleWithMultipleRoles()
 {
     var userManager = CreateManager();
     var roleManager = CreateRoleManager();
     var user = new InMemoryUser("MultiRoleUser");
     UnitTestHelper.IsSuccess(await userManager.CreateAsync(user));
     InMemoryRole[] roles =
     {
         new InMemoryRole("r1"), new InMemoryRole("r2"), new InMemoryRole("r3"),
         new InMemoryRole("r4")
     };
     foreach (var r in roles)
     {
         UnitTestHelper.IsSuccess(await roleManager.CreateAsync(r));
         UnitTestHelper.IsSuccess(await userManager.AddToRoleAsync(user.Id, r.Name));
         Assert.True(await userManager.IsInRoleAsync(user.Id, r.Name));
     }
     UnitTestHelper.IsSuccess(await userManager.RemoveFromRoleAsync(user.Id, roles[2].Name));
     Assert.False(await userManager.IsInRoleAsync(user.Id, roles[2].Name));
 }
예제 #36
0
 public async Task UpdateSecurityStampTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("stampMe");
     Assert.Null(user.SecurityStamp);
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     var stamp = user.SecurityStamp;
     Assert.NotNull(stamp);
     UnitTestHelper.IsSuccess(await manager.UpdateSecurityStampAsync(user.Id));
     Assert.NotEqual(stamp, user.SecurityStamp);
 }
예제 #37
0
 public void UpdateSecurityStampSyncTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("stampMe");
     Assert.Null(user.SecurityStamp);
     UnitTestHelper.IsSuccess(manager.Create(user));
     var stamp = user.SecurityStamp;
     Assert.NotNull(stamp);
     UnitTestHelper.IsSuccess(manager.UpdateSecurityStamp(user.Id));
     Assert.NotEqual(stamp, user.SecurityStamp);
 }
예제 #38
0
 public async Task RemoveUserNotInRoleFailsTest()
 {
     var userMgr = CreateManager();
     var roleMgr = CreateRoleManager();
     var role = new InMemoryRole("addUserDupeTest");
     var user = new InMemoryUser("user1");
     UnitTestHelper.IsSuccess(await userMgr.CreateAsync(user));
     UnitTestHelper.IsSuccess(await roleMgr.CreateAsync(role));
     var result = await userMgr.RemoveFromRoleAsync(user.Id, role.Name);
     UnitTestHelper.IsFailure(result, "User is not in role.");
 }
예제 #39
0
 public async Task UserLockedOutWithDateTimeLocalKindNowPlus30()
 {
     var mgr = CreateManager();
     mgr.UserLockoutEnabledByDefault = true;
     var user = new InMemoryUser("LockoutTest");
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.True(mgr.GetLockoutEnabled(user.Id));
     Assert.True(user.LockoutEnabled);
     var lockoutEnd = new DateTimeOffset(DateTime.Now.AddMinutes(30).ToLocalTime());
     UnitTestHelper.IsSuccess(await mgr.SetLockoutEndDateAsync(user.Id, lockoutEnd));
     Assert.True(await mgr.IsLockedOutAsync(user.Id));
     var end = await mgr.GetLockoutEndDateAsync(user.Id);
     Assert.Equal(lockoutEnd, end);
 }
예제 #40
0
 public async Task ChangePasswordFallsIfPasswordTooShortTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("user");
     const string password = "******";
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user, password));
     var result = await manager.ChangePasswordAsync(user.Id, password, "n");
     UnitTestHelper.IsFailure(result, "Passwords must be at least 6 characters.");
 }
예제 #41
0
 public void AddRemoveUserClaimSyncTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("ClaimsAddRemove");
     UnitTestHelper.IsSuccess(manager.Create(user));
     Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")};
     foreach (Claim c in claims)
     {
         UnitTestHelper.IsSuccess(manager.AddClaim(user.Id, c));
     }
     var userClaims = manager.GetClaims(user.Id);
     Assert.Equal(3, userClaims.Count);
     UnitTestHelper.IsSuccess(manager.RemoveClaim(user.Id, claims[0]));
     userClaims = manager.GetClaims(user.Id);
     Assert.Equal(2, userClaims.Count);
     UnitTestHelper.IsSuccess(manager.RemoveClaim(user.Id, claims[1]));
     userClaims = manager.GetClaims(user.Id);
     Assert.Equal(1, userClaims.Count);
     UnitTestHelper.IsSuccess(manager.RemoveClaim(user.Id, claims[2]));
     userClaims = manager.GetClaims(user.Id);
     Assert.Equal(0, userClaims.Count);
 }
예제 #42
0
 public async Task LockoutFailsIfNotEnabled()
 {
     var mgr = CreateManager();
     var user = new InMemoryUser("LockoutNotEnabledTest");
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.False(mgr.GetLockoutEnabled(user.Id));
     Assert.False(user.LockoutEnabled);
     UnitTestHelper.IsFailure(await mgr.SetLockoutEndDateAsync(user.Id, new DateTimeOffset()), "Lockout is not enabled for this user.");
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
 }
예제 #43
0
 public async Task UserNotLockedOutWithNullDateTimeAndIsSetToNullDate()
 {
     var mgr = CreateManager();
     mgr.UserLockoutEnabledByDefault = true;
     var user = new InMemoryUser("LockoutTest");
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.True(mgr.GetLockoutEnabled(user.Id));
     Assert.True(user.LockoutEnabled);
     UnitTestHelper.IsSuccess(await mgr.SetLockoutEndDateAsync(user.Id, new DateTimeOffset()));
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
     Assert.Equal(new DateTimeOffset(), await mgr.GetLockoutEndDateAsync(user.Id));
     Assert.Equal(new DateTimeOffset(), user.LockoutEnd);
 }
예제 #44
0
 public async Task LockoutEndToUtcNowWithManagerShouldNotBeLockedOut()
 {
     var mgr = CreateManager();
     mgr.UserLockoutEnabledByDefault = true;
     var user = new InMemoryUser("LockoutUtcNowTest");
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.True(mgr.GetLockoutEnabled(user.Id));
     Assert.True(user.LockoutEnabled);
     UnitTestHelper.IsSuccess(await mgr.SetLockoutEndDateAsync(user.Id, DateTimeOffset.UtcNow.AddSeconds(-.5)));
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
 }
예제 #45
0
 public async Task LockoutEndToUtcNowPlus5ShouldBeLockedOut()
 {
     var mgr = CreateManager();
     mgr.UserLockoutEnabledByDefault = true;
     var user = new InMemoryUser("LockoutUtcNowTest") { LockoutEnd = DateTimeOffset.UtcNow.AddMinutes(5) };
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.True(mgr.GetLockoutEnabled(user.Id));
     Assert.True(user.LockoutEnabled);
     Assert.True(await mgr.IsLockedOutAsync(user.Id));
 }
예제 #46
0
 public void UserLockedOutWithDateTimeNowPlus30Sync()
 {
     var mgr = CreateManager();
     mgr.UserLockoutEnabledByDefault = true;
     var user = new InMemoryUser("LockoutTest");
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.True(mgr.GetLockoutEnabled(user.Id));
     Assert.True(user.LockoutEnabled);
     var lockoutEnd = new DateTimeOffset(DateTime.Now.AddMinutes(30));
     UnitTestHelper.IsSuccess(mgr.SetLockoutEndDate(user.Id, lockoutEnd));
     Assert.True(mgr.IsLockedOut(user.Id));
     var end = mgr.GetLockoutEndDate(user.Id);
     Assert.Equal(lockoutEnd, end);
 }
예제 #47
0
 public void ChangePasswordFallsIfPasswordWrongSyncTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("user");
     UnitTestHelper.IsSuccess(manager.Create(user, "password"));
     var result = manager.ChangePassword(user.Id, "bogus", "newpassword");
     UnitTestHelper.IsFailure(result, "Incorrect password.");
 }
예제 #48
0
 public void RemovePasswordSyncTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("RemovePasswordTest");
     const string password = "******";
     UnitTestHelper.IsSuccess(manager.Create(user, password));
     var stamp = user.SecurityStamp;
     UnitTestHelper.IsSuccess(manager.RemovePassword(user.Id));
     var u = manager.FindByName(user.UserName);
     Assert.NotNull(u);
     Assert.Null(u.PasswordHash);
     Assert.NotEqual(stamp, user.SecurityStamp);
 }
예제 #49
0
 public async Task ChangePasswordFallsIfPasswordWrongTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("user");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user, "password"));
     var result = await manager.ChangePasswordAsync(user.Id, "bogus", "newpassword");
     UnitTestHelper.IsFailure(result, "Incorrect password.");
 }
예제 #50
0
 public void CreateUserLoginAndAddPasswordSyncTest()
 {
     var manager = CreateManager();
     var login = new UserLoginInfo("Provider", "key");
     var user = new InMemoryUser("CreateUserLoginAddPasswordTest");
     UnitTestHelper.IsSuccess(manager.Create(user));
     UnitTestHelper.IsSuccess(manager.AddLogin(user.Id, login));
     UnitTestHelper.IsSuccess(manager.AddPassword(user.Id, "password"));
     var logins = manager.GetLogins(user.Id);
     Assert.NotNull(logins);
     Assert.Equal(1, logins.Count());
     Assert.Equal(user, manager.Find(login));
     Assert.Equal(user, manager.Find(user.UserName, "password"));
 }
예제 #51
0
 public void EnableLockoutManuallySync()
 {
     var mgr = CreateManager();
     mgr.DefaultAccountLockoutTimeSpan = TimeSpan.FromHours(1);
     mgr.MaxFailedAccessAttemptsBeforeLockout = 2;
     var user = new InMemoryUser("manualLockout");
     UnitTestHelper.IsSuccess(mgr.Create(user));
     Assert.False(mgr.GetLockoutEnabled(user.Id));
     Assert.False(user.LockoutEnabled);
     UnitTestHelper.IsSuccess(mgr.SetLockoutEnabled(user.Id, true));
     Assert.True(mgr.GetLockoutEnabled(user.Id));
     Assert.True(user.LockoutEnabled);
     Assert.False(mgr.IsLockedOut(user.Id));
     UnitTestHelper.IsSuccess(mgr.AccessFailed(user.Id));
     Assert.False(mgr.IsLockedOut(user.Id));
     Assert.False(mgr.GetLockoutEndDate(user.Id) > DateTimeOffset.UtcNow.AddMinutes(55));
     Assert.Equal(1, mgr.GetAccessFailedCount(user.Id));
     UnitTestHelper.IsSuccess(mgr.AccessFailed(user.Id));
     Assert.True(mgr.IsLockedOut(user.Id));
     Assert.True(mgr.GetLockoutEndDate(user.Id) > DateTimeOffset.UtcNow.AddMinutes(55));
     Assert.Equal(0, mgr.GetAccessFailedCount(user.Id));
 }
예제 #52
0
        public async Task DeleteRoleNonEmptySucceedsTest()
        {
            // Need fail if not empty?
            var userMgr = CreateManager();
            var roleMgr = CreateRoleManager();
            var role = new InMemoryRole("deleteNonEmpty");
            Assert.False(await roleMgr.RoleExistsAsync(role.Name));
            UnitTestHelper.IsSuccess(await roleMgr.CreateAsync(role));
            var user = new InMemoryUser("t");
            UnitTestHelper.IsSuccess(await userMgr.CreateAsync(user));
            UnitTestHelper.IsSuccess(await userMgr.AddToRoleAsync(user.Id, role.Name));
            UnitTestHelper.IsSuccess(await roleMgr.DeleteAsync(role));
            Assert.Null(await roleMgr.FindByNameAsync(role.Name));
            Assert.False(await roleMgr.RoleExistsAsync(role.Name));
            // REVIEW: We should throw if deleteing a non empty role?
            var roles = await userMgr.GetRolesAsync(user.Id);

            // In memory this doesn't work since there's no concept of cascading deletes
            //Assert.Equal(0, roles.Count());
        }
예제 #53
0
 public void ChangePasswordSyncTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("ChangePasswordTest");
     const string password = "******";
     const string newPassword = "******";
     UnitTestHelper.IsSuccess(manager.Create(user, password));
     var stamp = user.SecurityStamp;
     Assert.NotNull(stamp);
     UnitTestHelper.IsSuccess(manager.ChangePassword(user.Id, password, newPassword));
     Assert.Null(manager.Find(user.UserName, password));
     Assert.Equal(user, manager.Find(user.UserName, newPassword));
     Assert.NotEqual(stamp, user.SecurityStamp);
 }
예제 #54
0
 public async Task ResetLockoutTest()
 {
     var mgr = CreateManager();
     mgr.DefaultAccountLockoutTimeSpan = TimeSpan.FromHours(1);
     mgr.UserLockoutEnabledByDefault = true;
     mgr.MaxFailedAccessAttemptsBeforeLockout = 2;
     var user = new InMemoryUser("resetLockout");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     Assert.True(await mgr.GetLockoutEnabledAsync(user.Id));
     Assert.True(user.LockoutEnabled);
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
     UnitTestHelper.IsSuccess(await mgr.AccessFailedAsync(user.Id));
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
     Assert.False(await mgr.GetLockoutEndDateAsync(user.Id) > DateTimeOffset.UtcNow.AddMinutes(55));
     Assert.Equal(1, await mgr.GetAccessFailedCountAsync(user.Id));
     UnitTestHelper.IsSuccess(await mgr.ResetAccessFailedCountAsync(user.Id));
     Assert.Equal(0, await mgr.GetAccessFailedCountAsync(user.Id));
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
     Assert.False(await mgr.GetLockoutEndDateAsync(user.Id) > DateTimeOffset.UtcNow.AddMinutes(55));
     UnitTestHelper.IsSuccess(await mgr.AccessFailedAsync(user.Id));
     Assert.False(await mgr.IsLockedOutAsync(user.Id));
     Assert.False(await mgr.GetLockoutEndDateAsync(user.Id) > DateTimeOffset.UtcNow.AddMinutes(55));
     Assert.Equal(1, await mgr.GetAccessFailedCountAsync(user.Id));
 }
예제 #55
0
 public async Task CreateUserAddRemoveLoginTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("CreateUserAddRemoveLoginTest");
     var login = new UserLoginInfo("Provider", "key");
     const string password = "******";
     var result = await manager.CreateAsync(user, password);
     Assert.NotNull(user);
     UnitTestHelper.IsSuccess(result);
     UnitTestHelper.IsSuccess(await manager.AddLoginAsync(user.Id, login));
     Assert.Equal(user, await manager.FindAsync(login));
     var logins = await manager.GetLoginsAsync(user.Id);
     Assert.NotNull(logins);
     Assert.Equal(1, logins.Count());
     Assert.Equal(login.LoginProvider, logins.Last().LoginProvider);
     Assert.Equal(login.ProviderKey, logins.Last().ProviderKey);
     var stamp = user.SecurityStamp;
     UnitTestHelper.IsSuccess(await manager.RemoveLoginAsync(user.Id, login));
     Assert.Null(await manager.FindAsync(login));
     logins = await manager.GetLoginsAsync(user.Id);
     Assert.NotNull(logins);
     Assert.Equal(0, logins.Count());
     Assert.NotEqual(stamp, user.SecurityStamp);
 }
예제 #56
0
 public async Task AddDupeLoginFailsTest()
 {
     var manager = CreateManager();
     var user = new InMemoryUser("DupeLogin");
     var login = new UserLoginInfo("provder", "key");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     UnitTestHelper.IsSuccess(await manager.AddLoginAsync(user.Id, login));
     var result = await manager.AddLoginAsync(user.Id, login);
     UnitTestHelper.IsFailure(result, "A user with that external login already exists.");
 }
예제 #57
0
 public async Task CreateUserLoginAndAddPasswordTest()
 {
     var manager = CreateManager();
     var login = new UserLoginInfo("Provider", "key");
     var user = new InMemoryUser("CreateUserLoginAddPasswordTest");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     UnitTestHelper.IsSuccess(await manager.AddLoginAsync(user.Id, login));
     UnitTestHelper.IsSuccess(await manager.AddPasswordAsync(user.Id, "password"));
     var logins = await manager.GetLoginsAsync(user.Id);
     Assert.NotNull(logins);
     Assert.Equal(1, logins.Count());
     Assert.Equal(user, await manager.FindAsync(login));
     Assert.Equal(user, await manager.FindAsync(user.UserName, "password"));
 }
예제 #58
0
 public async Task AddUserToRoleFailsIfAlreadyInRoleTest()
 {
     var userMgr = CreateManager();
     var roleMgr = CreateRoleManager();
     var role = new InMemoryRole("addUserDupeTest");
     var user = new InMemoryUser("user1");
     UnitTestHelper.IsSuccess(await userMgr.CreateAsync(user));
     UnitTestHelper.IsSuccess(await roleMgr.CreateAsync(role));
     UnitTestHelper.IsSuccess(await userMgr.AddToRoleAsync(user.Id, role.Name));
     Assert.True(await userMgr.IsInRoleAsync(user.Id, role.Name));
     UnitTestHelper.IsFailure(await userMgr.AddToRoleAsync(user.Id, role.Name), "User already in role.");
 }