/// <summary> /// <para>Ensures there is a service user with root of trust.</para> /// /// <para> /// This user is identified via <see cref="TrustDefaults.KnownRootIdentifier"/> /// </para> /// /// <para> /// The user user has <see cref="Permission.ControlAccess"/> | <see cref="Permission.CreatorOwner"/> on: /// /// <list type="bullet"> /// <item><see cref="RightType.Root"/> which is resource <see cref="TrustDefaults.KnownHomeResourceId"/></item> /// <item><see cref="RightType.RootTenantCollection"/></item> /// <item><see cref="RightType.RootUserCollection"/></item> /// </list> /// </para> /// </summary> public static async Task SeedServiceUser(this IServiceProvider services, ILogger log) { log.Info("[Seed] service user start"); // guard to check everything is up and running await services.GetRequiredService <IAmazonDynamoDB>().WaitForAllTables(log); ////////////////////////// // Seed the root // ============= // // Register a service account using our own scheme "service|id" // /** * Hand make up these because we want to inject the user with the provisioning user */ var userRightStore = services.GetRequiredService <IUserRightStore>(); var userStore = new UserStore( new User { Id = TrustDefaults.ProvisioningId }, services.GetRequiredService <IDynamoDBContext>(), services.GetRequiredService <IIdGenerator>(), userRightStore, services.GetRequiredService <ILogger <UserStore> >()); // TODO: get from configuration var rootUserCreateData = new UserCreateData { Name = "Service Account", Email = "*****@*****.**", ExternalId = TrustDefaults.KnownRootIdentifier }; if ((await userStore.GetByExternalId(rootUserCreateData.ExternalId)).IsNull()) { // creat a user with explicit rights var rootId = await userStore.Create( null, // skyhook TrustDefaults.KnownHomeResourceId, rootUserCreateData, Permission.ControlAccess | Permission.Get | Permission.Owner, new Dictionary <RightType, Permission> { { RightType.Root, Permission.ControlAccess | Permission.Get }, { RightType.RootUserCollection, Permission.FullControl }, }); // now set template rights for when new users 'RootUserCollection' are created on the root resource var inheritRights = new Dictionary <RightType, Permission> { { RightType.Todo, Permission.CreatorOwner }, { RightType.TodoTagCollection, Permission.AllAccess }, { RightType.TodoCommentCollection, Permission.AllAccess }, // { RightType.Tag, Permission.Get }, // { RightType.Comment, Permission.FullControl }, }; await Task.WhenAll(inheritRights.Select(right => userRightStore.SetInherit( RightType.RootUserCollection, rootId, TrustDefaults.KnownHomeResourceId, right.Key, right.Value) )); log.InfoFormat("[Seed] service user '{0}'", rootUserCreateData.ExternalId); } else { log.Info("[Seed] service user already exists"); } }
public async System.Threading.Tasks.Task <OperationResult <UserPartial> > CreateUser(CreateStaffViewModel options) { return(await System.Threading.Tasks.Task.Factory.StartNew <OperationResult <UserPartial> >(() => { OperationResult <UserPartial> result = new OperationResult <UserPartial>(); try { if (options != null) { if (IsInCompany()) { IdentityUser user = new IdentityUser() { Email = options.Email, UserName = options.Email, CompanyId = CurrentUser.CompanyId, Salary = options.Salary }; UserStore.Create(user); user = UserStore.FindByName(options.Email); if (user != null) { user.Profile.FirstName = options.FirstName; user.Profile.LastName = options.LastName; user.Profile.MiddleName = options.MiddleName; UserStore.Update(user); if (options.CertificatesModify) { UserStore.AddToRole(user, RoleNames.CertificatesModify); } if (options.CompanyModify) { UserStore.AddToRole(user, RoleNames.CompanyModify); } if (options.EquipmentModify) { UserStore.AddToRole(user, RoleNames.EquipmentModify); } if (options.EventsModify) { UserStore.AddToRole(user, RoleNames.EventsModify); } if (options.GameTypesModify) { UserStore.AddToRole(user, RoleNames.GameTypesModify); } if (options.NewsModify) { UserStore.AddToRole(user, RoleNames.NewsModify); } if (options.OperationsModify) { UserStore.AddToRole(user, RoleNames.OperationsModify); } if (options.OperationsRead) { UserStore.AddToRole(user, RoleNames.OperationsRead); } if (options.PlaygroundsModify) { UserStore.AddToRole(user, RoleNames.PlaygroundsModify); } List <string> roles = new List <string>(UserStore.GetRoles(user)); UserPartial partial = new UserPartial { FirstName = user.Profile.FirstName, LastName = user.Profile.LastName, MiddleName = user.Profile.MiddleName, UserName = user.UserName, CompanyOwner = roles.Contains(RoleNames.CompanyOwner), CertificatesModify = roles.Contains(RoleNames.CertificatesModify), CompanyModify = roles.Contains(RoleNames.CompanyModify), EquipmentModify = roles.Contains(RoleNames.EquipmentModify), EventsModify = roles.Contains(RoleNames.EventsModify), GameTypesModify = roles.Contains(RoleNames.GameTypesModify), NewsModify = roles.Contains(RoleNames.NewsModify), OperationsModify = roles.Contains(RoleNames.OperationsModify), OperationsRead = roles.Contains(RoleNames.OperationsRead), PlaygroundsModify = roles.Contains(RoleNames.PlaygroundsModify) }; result.SingleResult = partial; result.Result = true; } } } } catch (Exception ex) { LoggingService.Log(ex); } return result; })); }
/// <summary> /// Creates a tenant, user on the tenant and some todos with tags /// </summary> public static async Task SeedData(this IServiceProvider services, ILogger log) { /** * Get registered services. */ var context = services.GetRequiredService <IDynamoDBContext>(); var idGenerator = services.GetRequiredService <IIdGenerator>(); var userRightsStore = services.GetRequiredService <IUserRightStore>(); var configuration = services.GetRequiredService <IConfiguration>(); /** * Setup the provisioning user */ var provisioningUser = new User { Id = TrustDefaults.ProvisioningId }; /** * Hand make up these because we want to inject the user with the provisioning user */ var tenantStore = new TenantStore( provisioningUser, context, idGenerator, userRightsStore, services.GetRequiredService <ILogger <TenantStore> >()); var userStore = new UserStore( provisioningUser, context, idGenerator, userRightsStore, services.GetRequiredService <ILogger <UserStore> >()); var tagStore = new TagStore( provisioningUser, context, idGenerator, userRightsStore, services.GetRequiredService <ILogger <TagStore> >()); var todoStore = new TodoStore( provisioningUser, context, idGenerator, userRightsStore, tagStore, tenantStore, services.GetRequiredService <ILogger <TodoStore> >()); // ensure the database is up and tables are created await services.GetRequiredService <IAmazonDynamoDB>() .WaitForAllTables(log); log.Info("[Seed] create sample data"); ////////////////////////// // Authentication // ============== // // A precreated user (in third-party system) [or decoded JWT through https://jwt.io // grab it from the Authorization header in a request] var knownAuth0Id = configuration.GetSection("TestSeedUser").Value; log.DebugFormat("[Seed] found seed user '{0}'", knownAuth0Id); var rootUser = (await userStore.GetByExternalId(TrustDefaults.KnownRootIdentifier)) .ThrowConfigurationErrorsExceptionIfNull(() => "Root user has not been configured"); ////////////////////////// // Seed a user // ============= // // Assume a known Auth0 (test) user, register a user and then link to tenant // var userData = new UserCreateData { Email = "*****@*****.**", Name = "test", ExternalId = knownAuth0Id }; // create seeed data if the user doesn't exist if ((await userStore.GetByExternalId(userData.ExternalId)).IsNull()) { log.Info($"[Seed] user {userData.Email}"); var userId = await userStore.Create( rootUser.Id, TrustDefaults.KnownHomeResourceId, userData, Permission.FullControl | Permission.Owner, CallerCollectionRights.User); ////////////////////////// // Seed a tenant // ============= // var tenantCreateData = new TenantCreateData { Code = "rewire.semanticlink.io", Name = "Rewire", Description = "A sample tenant (company/organisation)" }; log.Info($"[Seed] tenant '{tenantCreateData.Code}'"); var tenantId = await tenantStore.Create( rootUser.Id, TrustDefaults.KnownHomeResourceId, tenantCreateData, Permission.FullControl | Permission.Owner, CallerCollectionRights.Tenant); ////////////////////////// // Add user to tenant // ================== // if (!await tenantStore.IsRegisteredOnTenant(tenantId, userId)) { await tenantStore.IncludeUser( tenantId, userId, Permission.Get | Permission.Owner, CallerCollectionRights.Tenant); } log.Info($"[Seed] registered user '{userData.Email}' against tenant '{tenantCreateData.Code}'"); ////////////////////////// // Seed global tags // ============= // // create some global tags // var tagIds = (await Task.WhenAll( new[] { "Work", "Personal", "Grocery List" } .Select(tag => tagStore.Create( userId, TrustDefaults.KnownHomeResourceId, new TagCreateData { Name = tag }, Permission.Get, CallerCollectionRights.Tag) ))) .Where(result => result != null) .ToList(); log.InfoFormat("[Seed] tags: [{0}]", tagIds.ToCsvString(tagId => tagId)); ///////////////////////////////////// // Seed a named todo list // ====================== // var todoCreateData = new TodoCreateData { Parent = tenantId, Name = "Shopping Todo List", Type = TodoType.List }; var todoListId = await todoStore.Create( userId, tenantId, todoCreateData, Permission.FullControl | Permission.Owner, CallerCollectionRights.Todo); log.InfoFormat("[Seed] todo list [{0}]", todoListId); ////////////////////////// // Seed some todos // =============== // var createTodoDatas = new List <TodoCreateData> { new TodoCreateData { Name = "One Todo", Parent = todoListId, Type = TodoType.Item }, new TodoCreateData { Name = "Two Todo (tag)", Tags = new List <string> { tagIds.First() }, State = TodoState.Complete, Parent = todoListId, Type = TodoType.Item }, new TodoCreateData { Name = "Three Todo (tagged)", Tags = tagIds, Parent = todoListId, Type = TodoType.Item } }; var ids = await Task.WhenAll(createTodoDatas .Select(data => todoStore.Create( userId, userId, data, Permission.FullControl | Permission.Owner, CallerCollectionRights.Todo))); log.InfoFormat("[Seed] todos: [{0}]", ids.ToCsvString(id => id)); } else { log.Debug("[Seed] test data already setup"); } }