public async Task <IActionResult> CreateUser(CreateUserViewModel model)
        {
            var user = new AppUser {
                UserName = model.Email, Email = model.Email
            };
            var password = _passwordGenerator.Generate();
            var result   = await _userManager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                return(Ok());
            }

            return(BadRequest());
        }
Exemple #2
0
        /// <summary>
        /// Signs the provided resource with an Authenticode signature.
        /// </summary>
        /// <param name="input">Object to sign</param>
        /// <param name="cert">Certificate to use for signing</param>
        /// <param name="description">Description to sign the object with</param>
        /// <param name="url">URL to include in the signature</param>
        /// <returns>A signed copy of the file</returns>
        public async Task <byte[]> SignAsync(byte[] input, X509Certificate2 cert, string description, string url)
        {
            // Temporarily save the cert to disk with a random password, as osslsigncode needs to read it from disk.
            var password  = _passwordGenerator.Generate();
            var inputFile = Path.GetTempFileName();
            var certFile  = Path.GetTempFileName();

            try
            {
                var exportedCert = cert.Export(X509ContentType.Pfx, password);
                File.WriteAllBytes(certFile, exportedCert);
                File.WriteAllBytes(inputFile, input);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    return(await SignUsingSignToolAsync(inputFile, certFile, password, description, url));
                }
                else
                {
                    return(await SignUsingOpenSsl(inputFile, certFile, password, description, url));
                }
            }
            finally
            {
                File.Delete(certFile);
            }
        }
Exemple #3
0
        /// <summary>
        /// Imports the specified keys from the temporary storage, and encrypts them.
        /// Outputs details to the console.
        /// </summary>
        /// <param name="keys">Keys to import</param>
        /// <param name="tempHomedir">Temporary GPG homedir</param>
        private void ImportAndEncryptSecretGpgKeys(IEnumerable <Key> keys, string tempHomedir)
        {
            foreach (var key in keys)
            {
                foreach (var subkey in key.Subkeys)
                {
                    if (!subkey.CanSign)
                    {
                        continue;
                    }

                    var inputFilename  = subkey.Keygrip + ".key";
                    var outputFilename = subkey.Keygrip + ".gpg";
                    var keygripPath    = Path.Join(
                        tempHomedir,
                        "private-keys-v1.d",
                        inputFilename
                        );
                    var code = _passwordGenerator.Generate();
                    _secretStorage.SaveSecret(outputFilename, File.ReadAllBytes(keygripPath), code);
                    File.Delete(keygripPath);

                    Console.WriteLine($"- {subkey.KeyId}");
                    Console.WriteLine($"  Expires: {subkey.Expires}");
                    Console.WriteLine($"  Key name: {outputFilename}");
                    Console.WriteLine($"  Secret Code: {code}");
                    Console.WriteLine();
                }
            }
        }
        public override async Task ExecuteAsync(RegisterUserCommand command)
        {
            Logger.ExecuteUserRegistration(command.Email);

            if (!IsValidEmail(command.Email))
            {
                throw new ValidationException("Email address is not valid.");
            }

            string newPassword = _passwordGenerator.Generate();
            var    newUser     = new User
            {
                Email        = command.Email.ToLowerInvariant(),
                PasswordHash = _passwordStorage.Create(newPassword),
                DisplayName  = "Newby",
                Roles        = new List <string> {
                    Roles.User
                },
                Location = new Location
                {
                    City       = "Bern",
                    PostalCode = "3011",
                    Latitude   = 46.944699,
                    Longitude  = 7.443788
                }
            };

            newUser = await UnitOfWork.InsertAsync(newUser);

            Logger.ExecuteUserRegistrationSuccessful(newUser.Id, command.Email);

            await _eventPublisher.PublishAsync(new UserRegisteredEvent(newUser, newPassword));
        }
Exemple #5
0
        public async Task <IActionResult> Register([FromBody] UserRegistration user)
        {
            // Check if the incoming request is valid
            if (ModelState.IsValid)
            {
                // check i the user with the same email exist
                var existingUser = await userManager.FindByEmailAsync(user.Email);

                if (existingUser != null)
                {
                    logger.LogWarning("Registration. Same email.{Email}", user.Email);
                    return(BadRequest(new RegistrationResponse {
                        Errors = new List <string> {
                            "Email already exist"
                        }
                    }));
                }

                ApplicationUser newUser = new()
                {
                    Email    = user.Email,
                    UserName = user.Email
                };

                var generatedPwd = passwordGenerator.Generate(32, 4);
                var isCreated    = await userManager.CreateAsync(newUser, generatedPwd);

                await userManager.AddToRoleAsync(newUser, AppUserRoles.User);

                //send email to end user with pwd assigned
                await emailSender.SendPasswordToNewlyCreatedUserAsync(newUser.Email, generatedPwd);

                if (isCreated.Succeeded)
                {
                    logger.LogInformation("Registration. New {user}", user);
                    return(Ok(new RegistrationResponse {
                        Result = true
                    }));
                }

                return(new JsonResult(new RegistrationResponse()
                {
                    Result = false,
                    Errors = isCreated.Errors.Select(x => x.Description).ToList()
                })
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError
                });
            }
            logger.LogInformation("Registration. model is invalid");

            return(BadRequest(new RegistrationResponse {
                Errors = new List <string> {
                    "Invalid payload"
                }
            }));
        }
 private void GeneratePassword()
 {
     Password = _passwordGenerator.Generate(
         PasswordLength,
         UseLetters,
         UseDigits,
         UsePunctuation
         );
 }
Exemple #7
0
        private async Task <Application> GenerateSecretAsync(Application application)
        {
            var secret = _passwordGenerator.Generate(64);

            application.ClientSecret = _passwordHasher.Hash(secret);
            await _applicationRepository.SaveAsync();

            application.ClientSecret = secret;

            return(application);
        }
Exemple #8
0
 private async Task GenerateAuthorizationCodeAsync()
 {
     _code = new AuthorizationCode
     {
         Code           = _passwordGenerator.Generate(_settings.AuthorizationCodeLength),
         ExpirationDate = DateTime.UtcNow.AddMinutes(_settings.AuthorizationCodeLifetimeMinutes),
         ClientId       = _request.ClientId,
         UserId         = _user.UserId,
         RedirectUri    = _request.RedirectUri,
         Scope          = _request.Scope
     };
     _authorizationCodeRepository.Add(_code);
     await _authorizationCodeRepository.SaveAsync();
 }
        public async Task <Result> Handle(CreateNewUser request, CancellationToken cancellationToken)
        {
            try
            {
                var user = request.NewUserData;

                var username = BuildUsername(user);

                var password = _password.Generate(
                    useLowercase: true,
                    useUppercase: false,
                    useNumbers: true,
                    useSpecial: false,
                    passwordSize: 12);

                // TODO: think how to make sure that username is unique

                if (!await _repository.CreateNewUserAsync(
                        user.Name,
                        user.Surname,
                        user.Patronymic,
                        username,
                        password,
                        user.UserRole,
                        user.OrganizationId))
                {
                    var random = new Random();
                    username += random.Next(100).ToString();

                    if (!await _repository.CreateNewUserAsync(
                            user.Name,
                            user.Surname,
                            user.Patronymic,
                            username,
                            password,
                            user.UserRole,
                            user.OrganizationId))
                    {
                        return(Result
                               .Fail(message: $"APPLICATION Can't create user with username: {username}. Try again"));
                    }
                }

                return(Result.Success((username, password)));
            }
            catch (Exception e)
            {
                return(Result.Fail(e));
            }
        }
Exemple #10
0
        public RefreshToken GenerateRefreshToken(int applicationId, string redirectUri, Guid userId, string scope = null)
        {
            var refreshToken = new RefreshToken
            {
                RefreshTokenId = _passwordGenerator.Generate(_settings.RefreshTokenLength),
                ApplicationId  = applicationId,
                ExpirationDate = DateTime.UtcNow.AddDays(_settings.RefreshTokenLifetimeDays),
                RedirectUri    = redirectUri,
                UserId         = userId,
                Scope          = scope
            };

            _refreshTokenRepository.Add(refreshToken);

            return(refreshToken);
        }
Exemple #11
0
        public async Task RestoreAccess(RestoreAccessModel model)
        {
            var user = await usersService.GetByEmailAsync(model.Email);

            if (user == null)
            {
                throw new ApplicationException("Пользователь не найден.");
            }

            var password          = passwordGenerator.Generate(8);
            var encryptedPassword = passwordEncrypter.Encrypt(password);

            user.Password = encryptedPassword;
            user.IsLocked = false;
            user.CountOfInvalidAttempts = 0;

            await dataContext.SaveChangesAsync();

            await emailService.SendRestoreAccessMailAsync(UserMap.Map(user), password);
        }
        /// <summary>
        /// Signs the provided resource with an Authenticode signature.
        /// </summary>
        /// <param name="input">Object to sign</param>
        /// <param name="cert">Certificate to use for signing</param>
        /// <param name="description">Description to sign the object with</param>
        /// <param name="url">URL to include in the signature</param>
        /// <returns>A signed copy of the file</returns>
        public async Task <Stream> SignAsync(Stream input, X509Certificate2 cert, string description, string url, string fileExtention)
        {
            // Temporarily save the cert to disk with a random password, as osslsigncode needs to read it from disk.
            var password  = _passwordGenerator.Generate();
            var inputFile = Path.GetTempFileName() + fileExtention;
            var certFile  = Path.GetTempFileName();

            _filesToDelete.Add(inputFile);

            try
            {
                var exportedCert = cert.Export(X509ContentType.Pfx, password);
                File.WriteAllBytes(certFile, exportedCert);
                await input.CopyToFileAsync(inputFile);

                if (fileExtention == "nupkg")
                {
                    return(await SignUsingNugetAsync(inputFile, certFile, password));
                }

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (fileExtention.Contains("ps"))
                    {
                        return(await SignUsingPowerShellAsync(inputFile, certFile, password));
                    }
                    else
                    {
                        return(await SignUsingSignToolAsync(inputFile, certFile, password, description, url));
                    }
                }
                else
                {
                    return(await SignUsingOpenSsl(inputFile, certFile, password, description, url));
                }
            }
            finally
            {
                File.Delete(certFile);
            }
        }
        /// <summary>
        /// Adds a new key to the secret storage.
        /// </summary>
        /// <param name="inputPath"></param>
        public void AddKey(string inputPath)
        {
            // Ensure output file does not exist
            var fileName = Path.GetFileName(inputPath);

            _secretStorage.ThrowIfSecretExists(fileName);

            var password = ConsoleUtils.PasswordPrompt("Password");
            var cert     = new X509Certificate2(File.ReadAllBytes(inputPath), password, X509KeyStorageFlags.Exportable);

            var code = _passwordGenerator.Generate();

            _secretStorage.SaveSecret(fileName, cert, code);
            Console.WriteLine();
            Console.WriteLine($"Saved {fileName} ({cert.FriendlyName})");
            Console.WriteLine($"Subject: {cert.SubjectName.Format(false)}");
            Console.WriteLine($"Issuer: {cert.IssuerName.Format(false)}");
            Console.WriteLine($"Valid from {cert.NotBefore} until {cert.NotAfter}");
            Console.WriteLine();
            Console.WriteLine($"Secret Code: {code}");
        }
Exemple #14
0
        public static User Create(Email email, IUserIdGenerator userIdGenerator, IUserUniqueChecker userUniqueChecker, IPasswordGenerator passwordGenerator, IPasswordHasher passwordHasher, CancellationToken cancellationToken)
        {
            if (!email.IsValid)
            {
                throw new EmailNotValidException(email);
            }
            bool unique = userUniqueChecker.CheckAsync(email, cancellationToken).GetAwaiter().GetResult();

            if (!unique)
            {
                throw new UserAlreadyExistException(email);
            }

            UserId       userId           = userIdGenerator.Generate();
            Password     password         = passwordGenerator.Generate();
            PasswordHash passwordHash     = passwordHasher.Hash(password);
            var          user             = new User(userId, email, passwordHash, DateTime.UtcNow);
            var          userCreatedEvent = new UserCreatedEvent(user, password);

            user.AddDomainEvent(userCreatedEvent);
            return(user);
        }
        public async Task <IServiceReponse <bool> > Register(UserDto registration, UserType userType = UserType.Employee)
        {
            return(await HandleApiOperationAsync(async() =>
            {
                if (await _userManager.UserExistsAsync(registration.Email))
                {
                    throw await _helper.GetExceptionAsync(ErrorConstants.UserAccountExists);
                }

                if (!await _userManager.RolesExistAsync(registration.Roles ?? new List <string>()))
                {
                    throw await _helper.GetExceptionAsync(ErrorConstants.RoleNotExist);
                }

                var user = registration.MapTo <User>();

                user.UserType = userType;
                user.IsActive = true;

                var password = _passwordGenerator.Generate();

                if (!await _userManager.CreateUserAsync(user, password, registration.Roles ?? new List <string>()))
                {
                    throw await _helper.GetExceptionAsync(ErrorConstants.UserAccountRegistrationFailed);
                }

                await _messagingFactory.GetEmailManager().SendAsync(
                    "Business Mobility",
                    user.Email,
                    "Welcome to Business!",
                    $"<div> username: {user.Email } </div> <div> password: {password} </div>",
                    true
                    );

                return new ServiceResponse <bool>(true);
            }));
        }
Exemple #16
0
 private void btnGenerate_Click(object sender, RoutedEventArgs e)
 {
     tbInput.Text = IPasswordGenerator.Generate(20);
     tbInput.SelectAll();
     tbInput.Focus();
 }
Exemple #17
0
        private void Promt_Loaded(object sender, RoutedEventArgs e)
        {
            btnOK.Visibility     = Visibility.Collapsed;
            btnYes.Visibility    = Visibility.Collapsed;
            btnNo.Visibility     = Visibility.Collapsed;
            btnCancel.Visibility = Visibility.Collapsed;

            tbInput.Visibility     = Visibility.Collapsed;
            btnGenerate.Visibility = Visibility.Collapsed;

            Title          = string.IsNullOrEmpty(title) ? "" : title;
            tbContent.Text = string.IsNullOrEmpty(prompt) ? "" : prompt;

            LocalizeButtons();

            switch (button)
            {
            case MessageBoxButton.OK:
                btnOK.Visibility = Visibility.Visible;
                break;

            case MessageBoxButton.OKCancel:
                btnOK.Visibility     = Visibility.Visible;
                btnCancel.Visibility = Visibility.Visible;
                break;

            case MessageBoxButton.YesNo:
                btnYes.Visibility = Visibility.Visible;
                btnNo.Visibility  = Visibility.Visible;
                break;

            case MessageBoxButton.YesNoCancel:
                btnYes.Visibility    = Visibility.Visible;
                btnNo.Visibility     = Visibility.Visible;
                btnCancel.Visibility = Visibility.Visible;
                break;
            }

            switch (icon)
            {
            case MessageBoxImage.Information:
                imgIcon.Source = new BitmapImage(new Uri("img/information.png", UriKind.Relative));
                break;

            case MessageBoxImage.Error:
                imgIcon.Source = new BitmapImage(new Uri("img/critical.png", UriKind.Relative));
                break;

            case MessageBoxImage.Exclamation:
                imgIcon.Source = new BitmapImage(new Uri("img/exclamation.png", UriKind.Relative));
                break;

            case MessageBoxImage.Question:
                imgIcon.Source = new BitmapImage(new Uri("img/question.png", UriKind.Relative));
                break;
            }

            switch (type)
            {
            case MessageBoxType.MessageBox:

                break;

            case MessageBoxType.InputBox:
                tbInput.Visibility = Visibility.Visible;
                tbInput.Text       = string.IsNullOrEmpty(defaultResponse) ? "" : defaultResponse;
                tbInput.SelectAll();
                tbInput.Focus();
                break;

            case MessageBoxType.PasswordBox:
                tbInput.Visibility     = Visibility.Visible;
                btnGenerate.Visibility = Visibility.Visible;
                tbInput.Text           = string.IsNullOrEmpty(defaultResponse) ? IPasswordGenerator.Generate(20) : defaultResponse;
                tbInput.SelectAll();
                tbInput.Focus();
                break;
            }
        }
        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var users = new List <User>();

            // This users are for the automated tests.
            if (await _unitOfWork.CountAsync <User>(u => u.Email == TestCredentials.User1) < 1)
            {
                users.Add(new User
                {
                    Id    = Guid.NewGuid(),
                    Email = TestCredentials.User1,
                    Roles = new List <string> {
                        Roles.User
                    },
                    PasswordHash = _passwordStorage.Create(TestCredentials.User1Password)
                });
            }

            if (await _unitOfWork.CountAsync <User>(u => u.Email == TestCredentials.User2) < 1)
            {
                users.Add(new User
                {
                    Id    = Guid.NewGuid(),
                    Email = TestCredentials.User2,
                    Roles = new List <string> {
                        Roles.User
                    },
                    PasswordHash = _passwordStorage.Create(TestCredentials.User2Password),
                    Location     = new Location
                    {
                        City       = "Bern",
                        PostalCode = "3011",
                        Latitude   = 46.944699,
                        Longitude  = 7.443788
                    }
                });
            }

            if (await _unitOfWork.CountAsync <User>(u => u.Email == TestCredentials.User3) < 1)
            {
                users.Add(new User
                {
                    Id    = Guid.NewGuid(),
                    Email = TestCredentials.User3,
                    Roles = new List <string> {
                        Roles.User
                    },
                    PasswordHash = _passwordStorage.Create(TestCredentials.User3Password),
                    Location     = new Location
                    {
                        City       = "Bern",
                        PostalCode = "3011",
                        Latitude   = 46.944699,
                        Longitude  = 7.443788
                    }
                });
            }

            if (await _unitOfWork.CountAsync <User>() <= SeedCount)
            {
                IList <string> zips = new[] { "3000", "3001", "3003", "3004", "3005", "3006", "3007", "3010", "3013", "3014", "3018", "3027", "3030" };

                Faker <Location> locationFaker = new Faker <Location>()
                                                 .RuleFor(u => u.PostalCode, f => f.PickRandom(zips))
                                                 .RuleFor(u => u.City, "Bern")
                                                 .RuleFor(u => u.Latitude, f => f.Location().AreaCircle(46.944699, 7.443788, 10_000).Latitude)
                                                 .RuleFor(u => u.Longitude, f => f.Location().AreaCircle(46.944699, 7.443788, 10_000).Longitude);

                // At least 10% should share the same location.
                // The picked locations are uniform distributed, hence just generate 10% of the seed.
                List <Location> locations = locationFaker.Generate(SeedCount / 100 * 10).ToList();

                Faker <User> faker = new Faker <User>()
                                     .RuleFor(u => u.Id, f => Guid.NewGuid())
                                     .RuleFor(u => u.Email, f => f.Internet.Email().ToLowerInvariant())
                                     .RuleFor(u => u.PasswordHash, _passwordStorage.Create(_passwordGenerator.Generate()))
                                     .RuleFor(u => u.DisplayName, f => f.Name.FirstName())
                                     .RuleFor(u => u.Roles, new List <string> {
                    Roles.User
                })
                                     .RuleFor(u => u.Location, f => f.PickRandom(locations));

                List <User> fakeUsers = faker.Generate(SeedCount);

                // Yes, this is expensive but we don't allow duplicated emails.
                DeduplicateEmails(fakeUsers);

                // Random generate friendships
                var random = new Random();
                foreach (User fakeUser in fakeUsers)
                {
                    for (var i = 0; i < SeedCount / 100 * 10; i++)
                    {
                        int index = random.Next(fakeUsers.Count);
                        fakeUser.Friends.Add(fakeUsers[index].Id);
                    }
                }

                users.AddRange(fakeUsers);
            }

            if (users.Any())
            {
                try
                {
                    await _unitOfWork.InsertManyAsync(users);
                }
                catch (DuplicateKeyException)
                {
                    // The tests are executed in parallel.
                    // Just ignore.
                }
            }
        }
Exemple #19
0
        private int Run(string[] args)
        {
            var app = new CommandLineApplication();

            app.Name = "SecureSignTools";
            app.HelpOption("-?|-h|--help");
            app.OnExecute(() => app.ShowHelp());

            app.Command("addkey", command =>
            {
                command.Description = "Add a new key";
                var pathArg         = command.Argument("path", "Path to the key file to add");
                command.OnExecute(() =>
                {
                    var inputPath = pathArg.Value;
                    if (string.IsNullOrWhiteSpace(inputPath))
                    {
                        Console.WriteLine("Please include the file name to add");
                        return(1);
                    }

                    // Ensure input file exists
                    if (!File.Exists(inputPath))
                    {
                        throw new Exception("File does not exist: " + inputPath);
                    }

                    // Ensure output file does not exist
                    var fileName   = Path.GetFileName(inputPath);
                    var outputPath = _secretStorage.GetPathForSecret(fileName);
                    if (File.Exists(outputPath))
                    {
                        throw new Exception(outputPath + " already exists! I'm not going to overwrite it.");
                    }

                    var password = ConsoleUtils.PasswordPrompt("Password");
                    var cert     = new X509Certificate2(File.ReadAllBytes(inputPath), password, X509KeyStorageFlags.Exportable);

                    var code = _passwordGenerator.Generate();
                    _secretStorage.SaveSecret(fileName, cert, code);
                    Console.WriteLine();
                    Console.WriteLine($"Saved {fileName} ({cert.FriendlyName})");
                    Console.WriteLine($"Subject: {cert.SubjectName.Format(false)}");
                    Console.WriteLine($"Issuer: {cert.IssuerName.Format(false)}");
                    Console.WriteLine($"Valid from {cert.NotBefore} until {cert.NotAfter}");
                    Console.WriteLine();
                    Console.WriteLine($"Secret Code: {code}");
                    Console.WriteLine();
                    Console.WriteLine("This secret code is required whenever you create an access token that uses this key.");
                    Console.WriteLine("Store this secret code in a SECURE PLACE! The code is not stored anywhere, ");
                    Console.WriteLine("so if you lose it, you will need to re-install the key.");
                    return(0);
                });
            });

            app.Command("addtoken", command =>
            {
                command.Description = "Add a new access token";
                command.OnExecute(() =>
                {
                    var name = ConsoleUtils.Prompt("Key name");
                    var code = ConsoleUtils.Prompt("Secret code");

                    try
                    {
                        _secretStorage.LoadSecret(name, code);
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine($"Could not load key: {ex.Message}");
                        Console.Error.WriteLine("Please check that the name and secret code are valid.");
                        return(1);
                    }

                    // If we got here, the key is valid
                    var comment = ConsoleUtils.Prompt("Comment (optional)");

                    Console.WriteLine();
                    Console.WriteLine("Signing settings:");
                    var desc = ConsoleUtils.Prompt("Description");
                    var url  = ConsoleUtils.Prompt("Product/Application URL");

                    var accessToken = new AccessToken
                    {
                        Id       = Guid.NewGuid().ToShortGuid(),
                        Code     = code,
                        IssuedAt = DateTime.Now,
                        KeyName  = name,
                    };
                    var accessTokenConfig = new AccessTokenConfig
                    {
                        Comment  = comment,
                        IssuedAt = accessToken.IssuedAt,
                        Valid    = true,

                        SignDescription = desc,
                        SignUrl         = url,
                    };


                    // If this is the first time an access token is being added, we need to create the config file
                    if (!File.Exists(_pathConfig.AccessTokenConfig))
                    {
                        File.WriteAllText(_pathConfig.AccessTokenConfig, JsonConvert.SerializeObject(new
                        {
                            AccessTokens = new Dictionary <string, AccessToken>()
                        }));
                    }

                    // Save access token config to config file
                    dynamic configFile = JObject.Parse(File.ReadAllText(_pathConfig.AccessTokenConfig));
                    configFile.AccessTokens[accessToken.Id] = JToken.FromObject(accessTokenConfig);
                    File.WriteAllText(_pathConfig.AccessTokenConfig, JsonConvert.SerializeObject(configFile, Formatting.Indented));

                    var encodedAccessToken = _accessTokenSerializer.Serialize(accessToken);

                    Console.WriteLine();
                    Console.WriteLine("Created new access token:");
                    Console.WriteLine(encodedAccessToken);
                    return(0);
                });
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("ERROR: " + ex.Message);
#if DEBUG
                throw;
#else
                return(1);
#endif
            }
        }