public HttpResponseMessage UsersCreate([FromBody] UserCreateData data) { HttpResponseMessage retVal; ParameterValidator validator = new ParameterValidator(ModelState); if (!validator.IsValid) { retVal = Request.CreateResponse(HttpStatusCode.BadRequest, validator.Result); } else { IUser user = SecurityManager.FindUser(data.Name); if (user == default(User)) { IResult <IUser> createResult = SecurityManager.CreateUser(data.Name, data.DisplayName, data.Email, data.Password, data.Role); if (createResult.ResultCode != ResultCode.Failure) { retVal = Request.CreateResponse(HttpStatusCode.Created, new UserData(createResult.ReturnValue), JsonFormatter()); } else { retVal = Request.CreateResponse(HttpStatusCode.InternalServerError, new HttpErrorResult($"Failed to create User '{data.Name}'.", createResult), JsonFormatter()); } } else { retVal = Request.CreateResponse(HttpStatusCode.Conflict, "The specified User already exists."); } } return(retVal); }
public async Task LoadUser() { var userStore = Get <IUserStore>(); var identityId = "auth0|349874545"; var data = new UserCreateData { Name = "fred", Email = "", ExternalId = identityId }; var id = await userStore.Create( TrustDefaults.KnownRootIdentifier, TrustDefaults.KnownHomeResourceId, data, Permission.FullControl, CallerCollectionRights.User ); var user = await userStore.Get(id); Assert.Contains(identityId, user.ExternalIds); user = await userStore.GetByExternalId(identityId); Assert.Equal(id, user.Id); Assert.NotEqual(id, user.ExternalIds.First()); await userStore.Delete(id); }
public void Create(UserCreateData userCreateData) { using (var transactionScope = new TransactionScope()) { ApplicationUser user = new ApplicationUser { Id = userCreateData.Username, UserName = userCreateData.Username, Email = userCreateData.Email, PhoneNumber = userCreateData.Phone }; //IdentityResult createUserAccountResult = this.userManager.Create(user, userCreateData.Password); //this.ProcessIdentityResult("Creating User Account", createUserAccountResult); CEMUser userData = this.baseRepository.Create(); userData = this.mapper.Map <UserCreateData, CEMUser>(userCreateData, userData); // userData.AccountDataId = user.Id; this.Save(userData); //IdentityResult addingRolesToUserResult = this.userManager.AddToRoles(user.Id, userCreateData.Roles.ToArray()); //this.ProcessIdentityResult("Adding Roles to the User", addingRolesToUserResult); transactionScope.Complete(); } }
private static IEnumerable <Claim> GetClaimsFor(UserCreateData data, ApplicationUser user) { var claims = new List <Claim>(); claims.AddRange(new Claim[] { new Claim(JwtClaimTypes.Name, $"{data.GivenName} {data.FamilyName}"), new Claim(JwtClaimTypes.GivenName, data.GivenName), new Claim(JwtClaimTypes.FamilyName, data.FamilyName), new Claim(JwtClaimTypes.Email, data.Email), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json), new Claim("location", "Rosenheim") }); switch (data.Type) { case UserTypes.Student: claims.Add(new Claim(AuthConstants.StudentType, user.Id, ClaimValueTypes.String, AuthConstants.Issuer)); break; case UserTypes.Professor: claims.Add(new Claim(AuthConstants.ProfessorType, user.Id, ClaimValueTypes.String, AuthConstants.Issuer)); break; case UserTypes.Principal: claims.Add(new Claim(AuthConstants.PrincipalType, user.Id, ClaimValueTypes.String, AuthConstants.Issuer)); break; } return(claims); }
private static void CreateUser(UserManager <ApplicationUser> userMgr, UserCreateData data) { var user = userMgr.FindByIdAsync(data.Id).Result; if (user != null) { // Für die Vorlesung erzeugen wir den User jedes mal neu var deleteResult = userMgr.DeleteAsync(user).Result; } user = new ApplicationUser { Id = data.Id, UserName = data.Email, Email = data.Email, EmailConfirmed = true }; var result = userMgr.CreateAsync(user, "Pass123$").Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } result = userMgr.AddClaimsAsync(user, GetClaimsFor(data, user)).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } }
public void NameTooLong() { UserCreateData test = new UserCreateData() { Name = new string('a', 129), }; Assert.False(test.DataAnnotationIsValid()); }
public void PasswordTooLong() { UserCreateData test = new UserCreateData() { Password = new string('a', 513), }; Assert.False(test.DataAnnotationIsValid()); }
public void DisplayNameNull() { UserCreateData test = new UserCreateData() { DisplayName = null, }; Assert.False(test.DataAnnotationIsValid()); }
public void PasswordTooShort() { UserCreateData test = new UserCreateData() { Password = string.Empty, }; Assert.False(test.DataAnnotationIsValid()); }
public void NameTooShort() { UserCreateData test = new UserCreateData() { Name = string.Empty, }; Assert.False(test.DataAnnotationIsValid()); }
public void PasswordNull() { UserCreateData test = new UserCreateData() { Password = null, }; Assert.False(test.DataAnnotationIsValid()); }
public void EmailNull() { UserCreateData test = new UserCreateData() { Email = null, }; Assert.False(test.DataAnnotationIsValid()); }
public void EmailInvalid() { UserCreateData test = new UserCreateData() { Email = "email", }; Assert.False(test.DataAnnotationIsValid()); }
public static IEnumerable <UserCreateData> Get() { yield return(UserCreateData.New("chuck", "Chuck", "Norris", "*****@*****.**", UserTypes.Principal)); yield return(UserCreateData.New("katie", "Katie", "Bouman", "*****@*****.**", UserTypes.Professor)); yield return(UserCreateData.New("jason", "Jason", "Bourne", "*****@*****.**", UserTypes.Student)); yield return(UserCreateData.New("arnold", "Arnold", "Schwarzenegger", "*****@*****.**", UserTypes.Student)); }
public void NameNull() { UserCreateData test = new UserCreateData() { DisplayName = "display name", Email = "*****@*****.**", Password = "******", Role = Role.Reader, }; Assert.False(test.DataAnnotationIsValid()); }
public void UsersCreateFailure() { SecurityManager.Setup(s => s.FindUser(It.IsAny <string>())).Returns(default(User)); SecurityManager.Setup(s => s.CreateUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Role>())).Returns(new Result <IUser>(ResultCode.Failure)); UserCreateData newUser = new UserCreateData() { Name = "user", DisplayName = "name", Email = "*****@*****.**", Password = "******", Role = Role.Reader }; HttpResponseMessage response = Controller.UsersCreate(newUser); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); SecurityManager.Verify(s => s.CreateUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Role>()), Times.Once); }
public void Constructor() { UserCreateData test = new UserCreateData() { Name = "name", DisplayName = "display name", Email = "*****@*****.**", Password = "******", Role = Role.Reader, }; Assert.IsType <UserCreateData>(test); Assert.Equal("name", test.Name); Assert.Equal("display name", test.DisplayName); Assert.Equal("*****@*****.**", test.Email); Assert.Equal("password", test.Password); Assert.Equal(Role.Reader, test.Role); Assert.True(test.DataAnnotationIsValid()); }
/// <summary> /// <para> /// This method should only be external called when using the a trusted user through trusted code /// because it overrides the injected user from the context. /// </para> /// <para> /// If the user already exists, it just return that <see cref="User.Id" />. /// </para> /// </summary> /// <remarks> /// KLUDGE: this is easier than trying to reset the constructor inject of <see cref="User" /> /// </remarks> /// <returns>Id of the new or existing user</returns> public async Task <string> Create( string ownerId, string resourceId, UserCreateData data, Permission callerRights, IDictionary <RightType, Permission> callerCollectionRights) { if (await GetByExternalId(data.ExternalId) is User existingUser) { return(existingUser.Id); } // KLUDGE: needs to be injected var now = DateTime.UtcNow; var newUser = new User { Id = _idGenerator.New(), ExternalIds = new List <string> { data.ExternalId }, Email = data.Email, Name = data.Name, CreatedBy = _creator.Id, CreatedAt = now, UpdatedAt = now }; Log.TraceFormat("New user {0} '{1}' created by user {2}", newUser.Id, newUser.Email, _creator.Id); await _context.SaveAsync(newUser); await _userRightStore.CreateRights( newUser.Id, resourceId, new Dictionary <RightType, Permission> { { RightType.RootTenantCollection, Permission.Get | Permission.Post }, { RightType.RootTagCollection, Permission.Get | Permission.Post }, }); // create rights for new user and also the owner (if the owner if different) await Task.WhenAll( new List <string> { newUser.Id, ownerId } .Where(x => !x.IsNullOrWhitespace()) .Distinct() .Select(id => _userRightStore.CreateRights( id, newUser.Id, RightType.User.MakeCreateRights(callerRights, callerCollectionRights), new InheritForm { Type = RightType.RootUserCollection, ResourceId = resourceId, InheritedTypes = new List <RightType> { RightType.RootTagCollection, RightType.User, RightType.UserTenantCollection, RightType.UserTodoCollection }, CopyInheritTypes = new List <RightType> { RightType.Todo, RightType.TodoTagCollection, RightType.TodoCommentCollection, // RightType.Tag, // RightType.Comment } }))); return(newUser.Id); }
/// <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"); } }
/// <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"); } }