public async Task<JsonNetResult> RegisterUser(RegisterUserViewModel model) { if (ModelState.IsValid == false) return JsonFailure(); // Generate a user Id and try to register the user account (map from view model first) Guid userId = Guid.NewGuid(); var createUser = new CreateUser { EmailAddress = model.EmailAddress, FirstName = model.FirstName, LastName = model.LastName, Password = model.Password, UserId = userId }; // TODO: Validation to try and minimize chance of duplicate users // if (await _userWriteModel.CreateUser(createUser) == false) // { // ModelState.AddModelError(string.Empty, "A user with that email address already exists."); // return JsonFailure(); //} await _userManagement.CreateUser(createUser); // Assume creation successful so sign the user in SignTheUserIn(userId); // Return success return JsonSuccess(new UserRegisteredViewModel {UserId = userId}); }
/// <summary> /// Creates a new user account. /// </summary> public async Task CreateUser(CreateUser user) { // Hash the user's password string hashedPassword = PasswordHash.CreateHash(user.Password); // TODO: Use LINQ to create users DateTimeOffset timestamp = DateTimeOffset.UtcNow; PreparedStatement preparedCredentials = await _statementCache.NoContext.GetOrAddAsync( "INSERT INTO user_credentials (email, password, userid) VALUES (?, ?, ?) IF NOT EXISTS"); // Insert the credentials info (this will return false if a user with that email address already exists) IStatement insertCredentialsStatement = preparedCredentials.Bind(user.EmailAddress, hashedPassword, user.UserId); RowSet credentialsResult = await _session.ExecuteAsync(insertCredentialsStatement).ConfigureAwait(false); // The first column in the row returned will be a boolean indicating whether the change was applied (TODO: Compensating action for user creation failure?) var applied = credentialsResult.Single().GetValue<bool>("[applied]"); if (applied == false) return; PreparedStatement preparedUser = await _statementCache.NoContext.GetOrAddAsync( "INSERT INTO users (userid, firstname, lastname, email, created_date) VALUES (?, ?, ?, ?, ?) USING TIMESTAMP ?"); // Insert the "profile" information using a parameterized CQL statement IStatement insertUserStatement = preparedUser.Bind(user.UserId, user.FirstName, user.LastName, user.EmailAddress, timestamp, timestamp.ToMicrosecondsSinceEpoch()); await _session.ExecuteAsync(insertUserStatement).ConfigureAwait(false); // Tell the world about the new user await _bus.Publish(new UserCreated { UserId = user.UserId, FirstName = user.FirstName, LastName = user.LastName, EmailAddress = user.EmailAddress, Timestamp = timestamp }).ConfigureAwait(false); }