private string CreateToken(PersonAsUser user, IEnumerable <Claim> claims = null)
        {
            var newClaims = new List <Claim>();

            if (claims == null)
            {
                newClaims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Uuid.ToString()),
                    new Claim(ClaimTypes.Name, user.PersonFkNavigation.PlatformUserName),
                    new Claim(ClaimTypes.Role, user.PlatformParticipantTypeFkNavigation.ParticipantTypeIndicator),
                };

                if (user.MobileBusinessFkNavigation?.MobileBusinessNavigation.BusinessOrganizationNavigation.Uuid != null)
                {
                    newClaims.Add(
                        new Claim("PartyId", user.MobileBusinessFkNavigation.MobileBusinessNavigation.BusinessOrganizationNavigation.Uuid)
                        );
                }
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims ?? newClaims),
                //set expiration date from appsettings
                Expires            = DateTime.UtcNow.AddMinutes(int.Parse(configuration.GetSection("AppSettings:TokenExpirationInMinutes").Value)),
                SigningCredentials = creds,
                Issuer             = configuration.GetSection("AppSettings:IssuerUrl").Value,
                Audience           = configuration.GetSection("AppSettings:AppServiceBaseUrl").Value,
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
        public async Task <ServiceResponse <string> > Register(UserRegisterDto user)
        {
            var response = new ServiceResponse <string>();

            try
            {
                if (await UserExists(user.Username))
                {
                    response.Success = false;
                    response.Message = "User already exists.";
                    return(response);
                }

                CreatePasswordHash(user.Password, out byte[] passwordHash, out byte[] passwordSalt);

                //create new party
                var party = new Party
                {
                    //create new guid
                    Uuid                = Guid.NewGuid().ToString().ToUpper(),
                    CreateDate          = DateTime.UtcNow,
                    LastUpdateTimestamp = DateTime.UtcNow
                };

                await context.Party.AddAsync(party);

                //save to get the party id
                await context.SaveChangesAsync();

                //create person
                var person = new Person
                {
                    PersonId            = party.PartyId,
                    FullName            = user.FullName,
                    PlatformUserName    = user.Username,
                    LastUpdateTimestamp = DateTime.UtcNow
                };

                await context.Person.AddAsync(person);

                //save to get the person id
                await context.SaveChangesAsync();

                //create person as user
                var actorType = ActorType.Owner;

                var participantType = await context.PlatformParticipantType
                                      .Where(x => x.ParticipantTypeIndicator == actorType.GetDescription()).FirstOrDefaultAsync();

                var personAsUser = new PersonAsUser
                {
                    PersonFk                  = person.PersonId,
                    Uuid                      = Guid.NewGuid().ToString().ToUpper(),
                    MobileBusinessFk          = null,
                    PasswordBin               = passwordHash,
                    PasswordSalt              = passwordSalt,
                    PlatformParticipantTypeFk = participantType.PlatformParticipantTypeId,
                    LastUpdateTimestamp       = DateTime.UtcNow
                };

                await context.PersonAsUser.AddAsync(personAsUser);

                //save to get the person as user id
                await context.SaveChangesAsync();

                //save the person id
                var personId = (int)person.PersonId;

                //create new contact mechanism uuid
                var cm = new ContactMechanism()
                {
                    Uuid = Guid.NewGuid().ToString(),
                    LastUpdateTimestamp = DateTime.UtcNow
                };

                await context.ContactMechanism.AddAsync(cm);

                //need to save here to get the contact mechanism id!!
                await context.SaveChangesAsync();

                //create Email Address
                var email = new EmailAddress()
                {
                    EmailAddressId      = cm.ContactMechanismId,
                    Email               = user.Username,
                    EmailTypeCode       = user.EmailTypeCode ?? "P",
                    LastUpdateTimestamp = DateTime.UtcNow
                };

                await context.EmailAddress.AddAsync(email);

                await context.SaveChangesAsync();

                response.Data = $"User {person.PlatformUserName} created.";
            }
            catch (Exception ex)
            {
                //create user friendly exception
                response.Success   = false;
                response.Message   = ex.Message;
                response.Exception = new PlatformScreenException(ex);
            }

            return(response);
        }