Exemple #1
0
        public async Task <JsonResult> CreateNewUser(PegaUser user)
        {
            if (!ModelState.IsValid)
            {
                return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
            }
            if (!Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_\-\.]+$"))
            {
                return(Json(ResultsItem.Error("Username must contain only: Letters(A-Z), Numbers(0-9), _, -, or .")));
            }
            if (!Utilities.IsValidEmailAddress(user.Email))
            {
                return(Json("Please enter a valid email address."));
            }

            var createPair = await AuthorizationLogic.CreateNewUser(user);

            if (createPair.Result.IsSuccess)
            {
                SetSession(Constant.Session.SessionCurrentUser, createPair.Value);
                TempData["UserCreatedTransferMessage"] = createPair.Result.Message;
                return(Json(ResultsItem.Success("Success")));
            }

            return(Json(ResultsItem.Error(createPair.Result.Message)));
        }
Exemple #2
0
        public async Task <JsonResult> CurrentUserChangePassword(PegaUser user)
        {
            if (user.NewChangedPassword.Length < 8 || user.NewChangedPassword.Length > 30)
            {
                return(Json(ResultsItem.Error("Password changed failed: Password length must be from 8 - 30 characters.")));
            }
            if (user.NewChangedPassword != user.ConfirmNewChangedPassword)
            {
                return(Json(ResultsItem.Error("Passwords does not match.")));
            }
            if (CurrentUser.Username != user.Username)
            {
                return(Json(ResultsItem.Error("Username does not match.")));
            }

            // do-later: check if current pw is valid first. if (!AuthorizationLogic.AuthorizeUser(CurrentUser.Username, user.Password))

            // Change password
            var pwChangeResult = await AuthorizationLogic.ChangePassword(user.Username, user.NewChangedPassword);

            if (!pwChangeResult.IsSuccess)
            {
                return(Json(pwChangeResult));
            }

            HttpContext.Session.Clear();

            string successMessage = "Your password has been successfully reset. Please login again";

            TempData["message"] = successMessage;
            return(Json(ResultsItem.Success(successMessage)));
        }
Exemple #3
0
        public async Task <IActionResult> ConfirmEmail(string username, string authCode)
        {
            ResultsItem emailResult = await AuthorizationLogic.ConfirmEmail(username, authCode);

            TempData["message"] = emailResult.Message;
            return(RedirectToAction("Index", "Home"));
        }
        private void ButtonLoginWindow_Click(object sender, RoutedEventArgs e)
        {
            string LoginCheck    = textBoxLogin.Text;
            string PasswordCheck = passwordBox1.Password;

            using (_unitOfWork)
            {
                if (textBoxLogin.Text == "" ||
                    passwordBox1.Password == "")
                {
                    MessageBox.Show("Please, fill in all the information");
                }
                if (AuthorizationLogic.LoginCheking(LoginCheck, PasswordCheck, _unitOfWork))
                {
                    AuthorizationLogic.GetUser(LoginCheck, _unitOfWork);
                    MainWindow mainWindow = new MainWindow(AuthorizationLogic.GetUser(LoginCheck, _unitOfWork), _unitOfWork);
                    mainWindow.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Incorrect User login or password.");
                }
            }
        }
        public string[] GetAllRoles(string tenantName)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }

            return(AuthorizationLogic.GetAllRoles(tenantName));
        }
Exemple #6
0
        public void AuthorizationLogic_IsAuthorized_ClaimsPrincipalWithNoRoles_ReturnsFalse()
        {
            AuthorizationLogic authorizationLogic = new AuthorizationLogic(null, GetAuditLogicMock());
            ClaimsPrincipal    user = GetClaimsPrincipalWithNoRoles();

            bool isAuthorized = authorizationLogic.IsAuthorized(AuthorizationScopes.ManageRoles, user);

            Assert.IsFalse(isAuthorized);
        }
Exemple #7
0
        public void AuthorizationLogic_CanViewPrivateKey_CertificateWithNoAcl_ReturnsFalse()
        {
            AuthorizationLogic authorizationLogic = new AuthorizationLogic(null, GetAuditLogicMock());

            Certificate     certificate     = new Certificate();
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal();

            bool isAuthorized = authorizationLogic.CanViewPrivateKey(certificate, claimsPrincipal);

            Assert.IsFalse(isAuthorized);
        }
Exemple #8
0
        public PartialViewResult GetViewUser(string username)
        {
            var result = AuthorizationLogic.ViewUserProfile(username);

            if (!result.Result.IsSuccess)
            {
                return(GeneratePartialViewError(result.Result.Message));
            }

            return(PartialView("_ViewUser", result.Value));
        }
Exemple #9
0
        public void AuthorizationLogic_CanViewPrivateKey_CertificateWithDenyRole_DateExpiredAce_ReturnsFalse()
        {
            AuthorizationLogic authorizationLogic = new AuthorizationLogic(null, GetAuditLogicMock());

            Certificate     certificate     = GetCertificateWithDenyRoleClaimExpiredAce();
            ClaimsPrincipal claimsPrincipal = GetClaimsPrincipalWithRole();

            bool isAuthorized = authorizationLogic.CanViewPrivateKey(certificate, claimsPrincipal);

            Assert.IsFalse(isAuthorized);
        }
Exemple #10
0
        public void AuthorizationLogic_CanViewPrivateKey_CertificateWithAllowUserPrincipalAce_ReturnsTrue()
        {
            AuthorizationLogic authorizationLogic = new AuthorizationLogic(null, GetAuditLogicMock());

            Certificate     certificate     = GetCertificateWithAllowUserPrincipalClaimNoExpiry();
            ClaimsPrincipal claimsPrincipal = GetClaimsPrincipalWithRole();

            bool isAuthorized = authorizationLogic.CanViewPrivateKey(certificate, claimsPrincipal);

            Assert.IsTrue(isAuthorized);
        }
Exemple #11
0
        public async Task <ActionResult> Demo()
        {
            ResultsPair <PegaUser> pair = await AuthorizationLogic.AuthorizeUser("DemoUser", "49SPtrkuKDAtU27ifROw");

            if (pair.Result.IsSuccess)
            {
                SetSession(Constant.Session.SessionCurrentUser, pair.Value);
                return(RedirectToAction("Index", "Crypto"));
            }

            return(RedirectToAction("Index", "Home"));
        }
        public string[] GetRolesForUser(string tenantName, string username)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }

            return(AuthorizationLogic.GetRolesForUser(tenantName, username));
        }
        public void DeleteRole(string tenantName, string roleName)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }
            if (string.IsNullOrEmpty(roleName))
            {
                throw new ArgumentNullException("roleName");
            }

            AuthorizationLogic.DeleteRole(tenantName, roleName);
        }
        public bool RoleExists(string tenantName, string roleName)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }
            if (string.IsNullOrEmpty(roleName))
            {
                throw new ArgumentNullException("roleName");
            }

            return(AuthorizationLogic.RoleExists(tenantName, roleName));
        }
        public string[] GetUsersInRole(string tenantName, string roleName)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }
            if (string.IsNullOrEmpty(roleName))
            {
                throw new ArgumentNullException("roleName");
            }

            return(AuthorizationLogic.GetUsersInRole(tenantName, roleName));
        }
Exemple #16
0
        public void CreateUserTest()
        {
            ResultsItem deleteResult = AuthorizationLogic.DeletePegaUser("Test1234").Result;

            PegaUser user = new PegaUser
            {
                Username = "******",
                Password = "******",
                Email    = "*****@*****.**",
                IsSubscribeNewsLetter = true
            };
            ResultsPair <PegaUser> result = AuthorizationLogic.CreateNewUser(user).Result;

            Assert.IsTrue(result.Result.ResultType == Types.ResultsType.Successful);
        }
        public bool IsUserInRole(string tenantName, string username, string roleName)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }
            if (string.IsNullOrEmpty(roleName))
            {
                throw new ArgumentNullException("roleName");
            }

            return(AuthorizationLogic.IsUserInRole(tenantName, username, roleName));
        }
        public void RemoveUsersFromRoles(string tenantName, string[] usernames, string[] roleNames)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }
            if (usernames == null || usernames.Length == 0)
            {
                throw new ArgumentNullException("usernames");
            }
            if (roleNames == null || roleNames.Length == 0)
            {
                throw new ArgumentNullException("roleNames");
            }

            AuthorizationLogic.RemoveUsersFromRoles(tenantName, usernames, roleNames);
        }
Exemple #19
0
        public void AuthorizationLogic_IsAuthorized_ClaimsPrincipalWithRoleEmptyScopes_ReturnsFalse()
        {
            SecurityRole role = new SecurityRole()
            {
                Name = "TestRole", Scopes = new List <Guid>()
            };

            Mock <IConfigurationRepository> configurationRepository = new Mock <IConfigurationRepository>();

            configurationRepository.Setup(x => x.Get <SecurityRole>(It.IsAny <Guid>())).Returns(role);

            AuthorizationLogic authorizationLogic = new AuthorizationLogic(configurationRepository.Object, GetAuditLogicMock());
            ClaimsPrincipal    user = GetClaimsPrincipalWithNoRoles();

            bool isAuthorized = authorizationLogic.IsAuthorized(AuthorizationScopes.ManageRoles, user);

            Assert.IsFalse(isAuthorized);
        }
Exemple #20
0
        [Route("ResetPassword")] // Confirm Reset Password - Should be reaching here from email.
        public async Task <IActionResult> ResetPassword(string username, string authCode)
        {
            ResultsItem pwResetAuthResult = await AuthorizationLogic.AuthorizeResetPassword(username, authCode);

            if (pwResetAuthResult.IsSuccess)
            {
                PasswordUpdateRequest request = new PasswordUpdateRequest
                {
                    Username           = username,
                    EmailAuthCode      = authCode,
                    AuthenticationHash = Utilities.GenerateHmacSHA256Hash($"{username}{authCode}_ptpwresetreq", "PTPWRESET")
                };
                TempData["ResetPasswordRequest"] = Utilities.Serialize(request);

                return(View("ExecutePasswordReset", request));
            }

            return(Content(pwResetAuthResult.Message));
        }
Exemple #21
0
        private void ButtonSubmit_Click(object sender, RoutedEventArgs e)
        {
            User user;

            using (unitOfWork)
            {
                if (textBoxLogin.Text == "" ||
                    textBoxLastName.Text == "" ||
                    textBoxFirstName.Text == "" ||
                    passwordBox.Password == "")
                {
                    MessageBox.Show("Please fill in all information.");
                    return;
                }
                if (passwordBox.Password != passwordBoxConfirm.Password)
                {
                    MessageBox.Show("Passwords do not match.");
                    return;
                }

                if (AuthorizationLogic.LoginExists(textBoxLogin.Text, unitOfWork))
                {
                    MessageBox.Show("User with such login already exists. Please enter another login.");
                    return;
                }

                unitOfWork.Users.Add(new User
                {
                    Name     = textBoxLastName.Text + " " + textBoxFirstName.Text,
                    Login    = textBoxLogin.Text,
                    Password = passwordBox.Password,
                    Answers  = "50;50;50;50;50;50;50;50;50;50"
                });
                unitOfWork.SaveChanges();
                user = AuthorizationLogic.GetUser(textBoxLogin.Text, unitOfWork);
            }
            MainWindow mainWindow = new MainWindow(user, unitOfWork);

            mainWindow.Show();
            this.Close();
        }
Exemple #22
0
        public async Task <JsonResult> Login(PegaUser user)
        {
            ModelState.Remove("Email");
            if (!ModelState.IsValid)
            {
                return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
            }
            if (!Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_\-\.@]+$"))
            {
                return(Json(ResultsItem.Error("Username must contain only: Letters(A-Z), Numbers(0-9), _, -, ., or an email address.")));
            }

            ResultsPair <PegaUser> pair = await AuthorizationLogic.AuthorizeUser(user.Username, user.Password);

            if (pair.Result.IsSuccess)
            {
                SetSession(Constant.Session.SessionCurrentUser, pair.Value);
                return(Json(ResultsItem.Success("Success")));
            }
            return(Json(ResultsItem.Error(pair.Result.Message)));
        }
Exemple #23
0
        public async Task <JsonResult> ChooseNewResetPassword(PasswordUpdateRequest passRequest)
        {
            if (passRequest.NewPassword.Length < 8 || passRequest.NewPassword.Length > 30)
            {
                return(Json(ResultsItem.Error("Password changed failed: Password length must be from 8 - 30 characters.")));
            }
            if (passRequest.NewPassword != passRequest.ConfirmNewPassword)
            {
                return(Json(ResultsItem.Error("Passwords does not match.")));
            }

            PasswordUpdateRequest savedRequest = TempData["ResetPasswordRequest"] == null ? null : Utilities.Deserialize <PasswordUpdateRequest>(TempData["ResetPasswordRequest"].ToString());

            if (savedRequest == null || string.IsNullOrEmpty(savedRequest.AuthenticationHash))
            {
                return(Json(ResultsItem.Error("Password reset form expired. Please request another password reset.")));
            }

            if (savedRequest.Username != passRequest.Username)
            {
                return(Json(ResultsItem.Error("Passwords does not match.")));
            }
            if (Utilities.GenerateHmacSHA256Hash($"{savedRequest.Username}{savedRequest.EmailAuthCode}_ptpwresetreq", "PTPWRESET") != passRequest.AuthenticationHash)
            {
                return(Json(ResultsItem.Error("Authentication failed.")));
            }

            // Change password
            var pwChangeResult = await AuthorizationLogic.ChangePassword(passRequest.Username, passRequest.NewPassword);

            if (!pwChangeResult.IsSuccess)
            {
                return(Json(pwChangeResult));
            }

            string successMessage = "Your password has been successfully reset. Please login again";

            TempData["message"] = successMessage;
            return(Json(ResultsItem.Success(successMessage)));
        }
Exemple #24
0
        public async Task <PartialViewResult> LoadPortfolioViewMode(PortfolioRequest request, string username, string portfolioName, bool coinsOnly = false)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(portfolioName))
            {
                return(null);
            }

            request.ViewUser = new ViewUser
            {
                Username      = username,
                PortfolioName = portfolioName,
            };
            request.ViewUser.PortfolioName = Utilities.FormatPortfolioName(request.ViewUser.PortfolioName);
            request.ViewOtherUser          = true;

            ResultsPair <ViewUser> viewUserResult = AuthorizationLogic.AuthorizeViewUser(request.ViewUser.Username, request.ViewUser.PortfolioName);

            if (!viewUserResult.Result.IsSuccess)
            {
                return(GeneratePartialViewError(viewUserResult.Result.Message));
            }

            request.ViewUser = viewUserResult.Value;

            if (coinsOnly)
            {
                request.PortfolioID = request.ViewUser.SelectedPortfolioID;
                CoinsVM coinsVM = await GenerateCoinsVM(request);

                return(PartialView("_FullCoins", coinsVM));
            }

            PortfolioVM vm = await GeneratePortfolioVM(request);

            return(PartialView("_Portfolio", vm));
        }
Exemple #25
0
        private void InitializeApp(IServiceCollection services, AppSettings appSettings)
        {
            //singleton pattern here was a huge mistake, i'm going to fix this.

            LiteDbConfigurationRepository configurationRepository = new LiteDbConfigurationRepository(databaseLocator.GetConfigurationRepositoryConnectionString());

            appConfig = configurationRepository.GetAppConfig();

            ActiveDirectoryRepository activeDirectory = new ActiveDirectoryRepository();

            EncryptionProvider cipher = new EncryptionProvider(appConfig.EncryptionKey);

            services.AddSingleton <EncryptionProvider>(cipher);

            services.AddSingleton <IActiveDirectoryAuthenticator>(activeDirectory);
            services.AddSingleton <IActiveDirectoryRepository>(activeDirectory);

            IdentityAuthenticationLogic identityAuthenticationLogic = new IdentityAuthenticationLogic(configurationRepository, activeDirectory);

            services.AddSingleton <IdentityAuthenticationLogic>();

            ICertificateRepository certificateRepository = new LiteDbCertificateRepository(databaseLocator.GetCertificateRepositoryConnectionString());

            RuntimeCacheRepository runtimeCacheRepository = null;

            LiteDbAuditRepository auditRepository = new LiteDbAuditRepository(databaseLocator.GetAuditRepositoryConnectionString());

            IAuditLogic auditLogic = new AuditLogic(auditRepository, configurationRepository);

            services.AddSingleton <IAuditLogic>(auditLogic);

            IAuthorizationLogic authorizationLogic = new AuthorizationLogic(configurationRepository, auditLogic);

            IScriptManagementLogic scriptManagement = new ScriptManagementLogic(configurationRepository, authorizationLogic);

            services.AddSingleton <IScriptManagementLogic>(scriptManagement);

            IPowershellEngine powershellEngine = new PowershellEngine(auditLogic, scriptManagement);

            services.AddSingleton <IPowershellEngine>(powershellEngine);

            RoleManagementLogic roleManagementLogic = new RoleManagementLogic(configurationRepository, authorizationLogic);

            services.AddSingleton <RoleManagementLogic>(roleManagementLogic);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository, authorizationLogic);

            services.AddSingleton <UserManagementLogic>(userManagementLogic);

            SecurityPrincipalLogic securityPrincipalLogic = new SecurityPrincipalLogic(roleManagementLogic, userManagementLogic);

            services.AddSingleton <SecurityPrincipalLogic>();

            AdcsTemplateLogic adcsTemplateLogic = new AdcsTemplateLogic(configurationRepository, activeDirectory);

            services.AddSingleton <AdcsTemplateLogic>(adcsTemplateLogic);

            services.AddSingleton <IAuthorizationLogic>(authorizationLogic);

            services.AddSingleton <IConfigurationRepository>(configurationRepository);

            ICertificateProvider certificateProvider = new Win32CertificateProvider();

            services.AddSingleton <ICertificateProvider>(certificateProvider);

            services.AddSingleton <ICertificateRepository>(certificateRepository);

            ActiveDirectoryIdentityProviderLogic activeDirectoryIdentityProviderLogic = new ActiveDirectoryIdentityProviderLogic(configurationRepository);

            services.AddSingleton <ActiveDirectoryIdentityProviderLogic>(activeDirectoryIdentityProviderLogic);

            certificateManagementLogic = new CertificateManagementLogic(
                configurationRepository,
                certificateRepository,
                authorizationLogic,
                auditLogic,
                securityPrincipalLogic,
                cipher);

            services.AddSingleton <CertificateManagementLogic>(certificateManagementLogic);

            PrivateCertificateProcessing privateCertificateProcessing = new PrivateCertificateProcessing(certificateRepository, configurationRepository, certificateProvider, authorizationLogic, adcsTemplateLogic, auditLogic);

            services.AddSingleton <IPrivateCertificateProcessing>(privateCertificateProcessing);

            services.AddSingleton <NodeLogic>(new NodeLogic(configurationRepository, authorizationLogic, activeDirectoryIdentityProviderLogic, powershellEngine, auditLogic, certificateManagementLogic, privateCertificateProcessing));

            services.AddSingleton <IRuntimeConfigurationState>(
                new RuntimeConfigurationState(configurationRepository, runtimeCacheRepository)
            {
                InitialSetupComplete = initialSetupComplete
            });

            services.AddSingleton <IClientsideConfigurationProvider>(new ClientsideConfigurationProvider(configurationRepository));



            services.AddSingleton <AnalyticsLogic>(new AnalyticsLogic(configurationRepository, certificateRepository, auditRepository));

            services.AddSingleton <DataRenderingProvider>(new DataRenderingProvider());

            oidcLogic = new OpenIdConnectIdentityProviderLogic(configurationRepository, authorizationLogic);
            services.AddSingleton <IOpenIdConnectIdentityProviderLogic>(oidcLogic);
        }
Exemple #26
0
 public JsonResult PasswordResetForm(string email)
 {
     return(Json(AuthorizationLogic.RequestPasswordReset(email)));
 }
Exemple #27
0
        public string RenderScopeMap()
        {
            AuthorizationLogic authorizationLogic = new AuthorizationLogic(configurationRepository, null);

            return(string.Format("CmOptions.Scopes = {0}", JsonConvert.SerializeObject(authorizationLogic.GetAvailibleScopes())));
        }