private async Task CreateAuditEntries(CreateUserAccountCommand message, CreateUserAccountResult returnValue, string hashedAccountId, User user)
        {
            //Account
            await _mediator.SendAsync(new CreateAuditCommand
            {
                EasAuditMessage = new EasAuditMessage
                {
                    Category          = "CREATED",
                    Description       = $"Account {message.OrganisationName} created with id {returnValue.AccountId}",
                    ChangedProperties = new List <PropertyUpdate>
                    {
                        PropertyUpdate.FromLong("AccountId", returnValue.AccountId),
                        PropertyUpdate.FromString("HashedId", hashedAccountId),
                        PropertyUpdate.FromString("Name", message.OrganisationName),
                        PropertyUpdate.FromDateTime("CreatedDate", DateTime.UtcNow),
                    },
                    AffectedEntity = new Entity {
                        Type = "Account", Id = returnValue.AccountId.ToString()
                    },
                    RelatedEntities = new List <Entity>()
                }
            });

            //Membership Account
            await _mediator.SendAsync(new CreateAuditCommand
            {
                EasAuditMessage = new EasAuditMessage
                {
                    Category          = "CREATED",
                    Description       = $"User {message.ExternalUserId} added to account {returnValue.AccountId} as owner",
                    ChangedProperties = new List <PropertyUpdate>
                    {
                        PropertyUpdate.FromLong("AccountId", returnValue.AccountId),
                        PropertyUpdate.FromString("UserId", message.ExternalUserId),
                        PropertyUpdate.FromString("Role", Role.Owner.ToString()),
                        PropertyUpdate.FromDateTime("CreatedDate", DateTime.UtcNow)
                    },
                    RelatedEntities = new List <Entity>
                    {
                        new Entity {
                            Id = returnValue.AccountId.ToString(), Type = "Account"
                        },
                        new Entity {
                            Id = user.Id.ToString(), Type = "User"
                        }
                    },
                    AffectedEntity = new Entity {
                        Type = "Membership", Id = message.ExternalUserId
                    }
                }
            });
        }
Beispiel #2
0
        /// <summary>
        /// New user account
        /// </summary>
        public static async Task <CreateUserAccountResult> CreateUserAccount(IServiceProvider services, string email, string password = null, bool emailConfirmed = false)
        {
            var logger      = services.GetLoggerFor(typeof(UserAccount));
            var dbContext   = services.GetRequiredService <ApplicationDbContext>();
            var userManager = services.GetRequiredService <UserManager <User> >();

            var ret = new CreateUserAccountResult()
            {
            };

            if (string.IsNullOrWhiteSpace(email))
            {
                ret.IsEmailExists = true;
                logger.Information("Failed to create user account: invalid email");
                return(ret);
            }

            var tfaSecret = GenerateTfaSecret();

            try {
                var sumusWallet = new Common.Sumus.Signer();

                var newUser = new User()
                {
                    UserName       = email,
                    Email          = email,
                    TfaSecret      = tfaSecret,
                    JwtSaltCabinet = GenerateJwtSalt(),
                    EmailConfirmed = emailConfirmed,

                    UserOptions = new DAL.Models.UserOptions()
                    {
                    },
                    UserSumusWallet = new DAL.Models.UserSumusWallet {
                        PublicKey   = sumusWallet.PublicKey,
                        PrivateKey  = sumusWallet.PrivateKey,
                        TimeCreated = DateTime.UtcNow,
                        TimeChecked = DateTime.UtcNow,
                    },

                    TimeRegistered = DateTime.UtcNow,
                };

                var result = (IdentityResult)null;
                if (password != null)
                {
                    result = await userManager.CreateAsync(newUser, password);
                }
                else
                {
                    result = await userManager.CreateAsync(newUser);
                }

                if (result.Succeeded)
                {
                    ret.User = newUser;

                    logger.Information($"User account created {newUser.Id}");

                    try {
                        var name = string.Format("u{0:000000}", newUser.Id);

                        newUser.UserName           = name;
                        newUser.NormalizedUserName = name.ToUpperInvariant();
                        newUser.JwtSaltCabinet     = GenerateJwtSalt();

                        await dbContext.SaveChangesAsync();

                        logger.Information($"User account {newUser.Id} prepared and saved");
                    }
                    catch { }
                }
                else
                {
                    foreach (var v in result.Errors)
                    {
                        if (v.Code == "DuplicateUserName")
                        {
                            ret.IsUsernameExists = true;
                            logger.Information($"Failed to create user account: duplicate username");
                        }
                        else if (v.Code == "DuplicateEmail")
                        {
                            ret.IsEmailExists = true;
                            logger.Information($"Failed to create user account: duplicate email");
                        }
                        else
                        {
                            throw new Exception("Unexpected result error: " + v.Code);
                        }
                    }
                }
            } catch (Exception e) {
                logger?.Error(e, "Failed to create user account");
            }

            return(ret);
        }