예제 #1
0
        /// <summary>
        ///     Converts database information from one object format to another.
        /// </summary>
        /// <param name="databaseInfo">
        ///     An object representing the database information to convert.
        /// </param>
        /// <returns>
        ///     An object representing the database configuration settings.
        /// </returns>
        public static DatabaseSettings Convert(DatabaseInfo databaseInfo)
        {
            if (databaseInfo == null)
            {
                throw new ArgumentNullException("databaseInfo");
            }

            var element = new DatabaseSettings
            {
                Server         = databaseInfo.Server,
                Database       = databaseInfo.Database,
                Authentication = databaseInfo.Authentication
            };

            if (databaseInfo.Authentication == DatabaseAuthentication.Database)
            {
                element.Username = CredentialHelper.GetFullyQualifiedName(databaseInfo.Credentials);
                element.Password = databaseInfo.Credentials.Password;
            }
            element.ConnectionTimeout  = databaseInfo.ConnectionTimeout;
            element.CommandTimeout     = databaseInfo.CommandTimeout;
            element.TransactionTimeout = databaseInfo.TransactionTimeout;

            return(element);
        }
예제 #2
0
        /// <summary>
        /// Get user's credential for the Azure cluster.
        /// We can't validate such credential at on-premise client.
        /// This method doesn't save the credential.
        /// </summary>
        ///<param name="headnode">head node name</param>
        ///<param name="username">user name</param>
        ///<param name="internalPassword">user password</param>
        ///<param name="savePassword">save password or not</param>
        internal static bool RetrieveCredentialOnAzure(string headnode, ref string username, ref string internalPassword, ref bool savePassword)
        {
            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(internalPassword))
            {
                return(false);
            }

            // Try to get the default username if it is not specified.
            if (String.IsNullOrEmpty(username))
            {
                username = CredentialHelper.FetchDefaultUsername(headnode);
            }

            // If the username is specified, try to get password from Windows Vault.
            if (!String.IsNullOrEmpty(username))
            {
                byte[] cached = CredentialHelper.FetchPassword(headnode, username);
                if (cached != null)
                {
                    internalPassword = Encoding.Unicode.GetString(ProtectedData.Unprotect(cached, null, DataProtectionScope.CurrentUser));

                    return(false);
                }
            }

            // If username or password is not specified, popup credential dialog.
            SecureString password = null;

            Credentials.PromptForCredentials(headnode, ref username, ref password, ref savePassword, bConsole, hwnd);
            internalPassword = Credentials.UnsecureString(password);
            return(true);
        }
예제 #3
0
        public async Task <List <string> > Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            // Final Result
            List <string> fresult = new List <string>();

            string  GeneratedPassword = CredentialHelper.GenerateRandomPassowrd(CredentialHelper.SystemPasswordPolicy);
            HCMUser user = new HCMUser()
            {
                UserName        = request.UserName,
                Email           = request.Email,
                OrganizationID  = request.OrganizationID,
                EmployeeID      = request.EmployeeID,
                PasswordChanged = request.PasswordChanged
            };


            IdentityResult result = await _userManager.CreateAsync(user, GeneratedPassword);

            if (result.Succeeded)
            {
                fresult.Add(GeneratedPassword);
            }
            else
            {
                StringBuilder ErrorBuilder = new StringBuilder();
                foreach (IdentityError error in result.Errors)
                {
                    ErrorBuilder.Append(error.Description).Append("\n");
                }

                throw new BusinessRulesException(ErrorBuilder.ToString());
            }

            return(fresult);
        }
예제 #4
0
        public void GetFullyQualifiedName_ValidUsernamePassword_ReturnsCorrectName( )
        {
            var    credential = new NetworkCredential("username", "password");
            string name       = CredentialHelper.GetFullyQualifiedName(credential);

            Assert.AreEqual(name, "username");
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ImpersonationSqlFileStream" /> class.
        /// </summary>
        public ImpersonationSqlFileStream( )
        {
            NetworkCredential databaseCredential;

            /////
            // Determine if an impersonation context is required.
            /////
            using (var context = DatabaseContext.GetContext( ))
            {
                databaseCredential = context.DatabaseInfo.Credentials;
            }

            if (databaseCredential != null)
            {
                WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent( );

                bool impersonate = false;

                if (windowsIdentity != null)
                {
                    var principal = new WindowsPrincipal(windowsIdentity);

                    string account = (( WindowsIdentity )principal.Identity).Name;

                    if (String.Compare(CredentialHelper.GetFullyQualifiedName(databaseCredential), account, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        impersonate = true;
                    }
                }

                if (impersonate)
                {
                    _impersonationContext = ImpersonationContext.GetContext(databaseCredential);

                    if (string.IsNullOrEmpty(databaseCredential.Domain))
                    {
                        windowsIdentity = WindowsIdentity.GetCurrent( );

                        if (windowsIdentity != null)
                        {
                            var principal = new WindowsPrincipal(windowsIdentity);

                            string account = (( WindowsIdentity )principal.Identity).Name;

                            var parts = account.Split(new[]
                            {
                                '\\'
                            }, StringSplitOptions.RemoveEmptyEntries);

                            if (parts.Length == 2)
                            {
                                databaseCredential.Domain = parts[0];
                            }
                        }
                    }
                }
            }
        }
예제 #6
0
        public int Add(UserCredentialDTO dto)
        {
            User user = _Mapper.Map <UserCredentialDTO, User>(dto);

            user.SaltToken = Guid.NewGuid().ToString().Replace("-", "").ToLower();
            user.Password  = CredentialHelper.CreatePasswordHash(user.Password, user.SaltToken);

            return(Add(user));
        }
예제 #7
0
        public void TestCredentials()
        {
            //CredentialHelper.ResetCredentials();

            var credential = CredentialHelper.GetStoredCredential(true);

            Assert.IsNotNull(credential);

            Console.WriteLine($"{credential.UserName} - {credential.Password}");
        }
예제 #8
0
        protected async Task <YouTubeService> GetYouTubeService()
        {
            var credential = await CredentialHelper.RetrieveCredential();

            return(new YouTubeService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = _configuration.ApplicationName
            }));
        }
예제 #9
0
        public void TestCredentialSetting()
        {
            //CredentialHelper.ResetCredentials();
            var credentialStoreServiceName = CredentialHelper.GetCredentialStoreServiceName();

            Console.WriteLine(credentialStoreServiceName);

            //Assert.IsNotNull(credential);

            //Console.WriteLine($"{credential.UserName} - {credential.Password}");
        }
        public override ReadOnlyCollection <IAuthorizationPolicy> Authenticate(ReadOnlyCollection <IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message)
        {
            var session = CredentialHelper.GetSessionData(message);

            CheckCredentials(session);
            var        identity = new CentralUserIdentity(session);
            IPrincipal user     = new CentralPrincipal(identity);

            message.Properties["Principal"] = user;
            return(authPolicy);
        }
        [HttpPut, Route("update-password")] //TODO: add the regex to validate the string
        public IActionResult UpdatePassword([FromRoute] int UserId, [FromBody] string Password)
        {
            User user = _UserRepo.Find(i => i.Email.Equals(User.Identity.Name));

            if (user is null || user.Id <= 0)
            {
                return(BadRequest("User is Invalid or not Found"));
            }

            Password = CredentialHelper.CreatePasswordHash(Password, user.SaltToken);

            return(this.NoContent(() => _UserRepo.Update(user, new { Password }).Equals((int)TransactionStatus.SUCCESS)));
        }
예제 #12
0
        /// <summary>
        /// Overrides the specified server.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="database">The database.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public static DatabaseOverride Override(string server, string database, string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                return(Override(server, database));
            }

            NetworkCredential credential = CredentialHelper.ConvertToNetworkCredential(username, password);

            DatabaseInfo databaseSettings = new SqlDatabaseInfo(server, database, DatabaseAuthentication.Integrated, credential);

            return(Override(databaseSettings));
        }
예제 #13
0
 /// <summary>
 /// Handles Authentication Asynchronously
 /// </summary>
 /// <returns></returns>
 protected override Task <AuthenticateResult> HandleAuthenticateAsync()
 {
     if (!Request.Headers.ContainsKey("Authorization"))
     {
         return(Task.FromResult(AuthenticateResult.Fail("Authorization Error. Header Not Found")));
     }
     else
     {
         return(AuthService.CanAuthenticate(CredentialHelper.GetRequestCredentials(Request))
             ? Task.FromResult(AuthenticateResult.Success(ticket: GetAuthenticationTicket(authSign: CredentialHelper.GetRequestCredentials(Request))))
             : Task.FromResult(AuthenticateResult.Fail("Authorization Error. Authentication Error")));
     }
 }
        public MonadConnectionInfo DiscoverConnectionInfo(out SupportedVersionList supportedVersionList, string slotVersion)
        {
            if (string.IsNullOrEmpty(this.credentialKey) && !this.logonWithDefaultCredential)
            {
                throw new NotSupportedException();
            }
            bool flag = false;
            MonadConnectionInfo monadConnectionInfo = this.DiscoverConnectionInfo(ref flag, out supportedVersionList, slotVersion);

            if (flag && monadConnectionInfo.Credentials != null)
            {
                CredentialHelper.SaveCredential(this.credentialKey, monadConnectionInfo.Credentials);
            }
            return(monadConnectionInfo);
        }
예제 #15
0
        static void Main(string[] args)
        {
            using (ClientContext ctx = CredentialHelper.GetContext("https://zalodev.sharepoint.com/sites/OD2", "*****@*****.**"))
            {
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                //ArtifactProvisioningHelper.ImportSearchConfig(ctx);
                // ArtifactProvisioningHelper.CreatePage(ctx);
                ArtifactProvisioningHelper.AddWebPartsToPage(ctx);

                Console.WriteLine(web.Title);
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }
예제 #16
0
        /// <summary>
        /// Save the user credential to the local windows vault.
        /// </summary>
        /// <param name="headnode">head node name</param>
        /// <param name="username">user name</param>
        /// <param name="password">user password</param>
        internal static void SaveCrendential(string headnode, string username, string password)
        {
            try
            {
                if (password != null)
                {
                    Debug.Assert(!string.IsNullOrEmpty(headnode), "The headnode can't be null or empty.");

                    CredentialHelper.PersistPassword(headnode, username, ProtectedData.Protect(Encoding.Unicode.GetBytes(password), null, DataProtectionScope.CurrentUser));

                    SessionBase.TraceSource.TraceInformation("Cached credential is saved to local Windows Vault.");
                }
            }
            catch (Win32Exception)
            {
                SessionBase.TraceSource.TraceInformation("Cached credential can't be saved to local Windows Vault.");
            }
        }
예제 #17
0
        public User Authenticate(string Username, string Password)
        {
            User user = null;

            if (!string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password))
            {
                user = Find(i => i.Username.Equals(Username));
                if (user is null)
                {
                    return(user);
                }

                if (!CredentialHelper.VerifyPasswordHash(Password, user.Password, user.SaltToken))
                {
                    return(null);
                }

                return(user);
            }

            return(user);
        }
        private MonadConnectionInfo RetryCredentialsFromLoadOrInput(Func <PSCredential, MonadConnectionInfo> tryConnectWithCredential)
        {
            PSCredential cred = this.proposedCredential;

            if (cred == null && !string.IsNullOrEmpty(this.credentialKey))
            {
                cred = CredentialHelper.ReadCredential(this.credentialKey);
            }
            MonadConnectionInfo monadConnectionInfo = null;

            while (monadConnectionInfo == null)
            {
                if (cred == null && this.uiInteractionHandler != null)
                {
                    if (WinformsHelper.IsWin7OrLater() && this.orgType == OrganizationType.Cloud)
                    {
                        CredentialHelper.ForceConnection(this.uri);
                    }
                    this.uiInteractionHandler.DoActionSynchronizely(delegate(IWin32Window window)
                    {
                        cred = CredentialHelper.PromptForCredentials((window == null) ? IntPtr.Zero : window.Handle, this.displayName, this.uri, this.GetErrorMessage(), ref this.rememberCredentialChecked);
                    });
                    if (cred != null && !string.IsNullOrEmpty(this.credentialKey))
                    {
                        CredentialHelper.RemoveCredential(this.credentialKey);
                    }
                }
                if (cred == null)
                {
                    throw new OperationCanceledException(Strings.UnableToConnectExchangeForest(this.displayName));
                }
                monadConnectionInfo = tryConnectWithCredential(cred);
                cred = null;
            }
            return(monadConnectionInfo);
        }
예제 #19
0
        /// <summary>
        ///     Adds the database user.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="role">The role.</param>
        /// <param name="server">The server.</param>
        /// <param name="catalog">The catalog.</param>
        /// <param name="dbUser">The database user.</param>
        /// <param name="dbPassword">The database password.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddDatabaseUser(string username, string role, string server, string catalog, string dbUser, string dbPassword)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(server) || string.IsNullOrEmpty(catalog))
            {
                throw new ArgumentNullException( );
            }

            bool impersonate = false;

            var credential = new NetworkCredential( );

            if (!string.IsNullOrEmpty(dbUser))
            {
                credential = CredentialHelper.ConvertToNetworkCredential(dbUser, dbPassword);

                /////
                // Check if the context identity matches the current windows identity
                /////
                WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent( );

                var principal = new WindowsPrincipal(windowsIdentity);

                string account = (( WindowsIdentity )principal.Identity).Name;

                if (String.Compare(CredentialHelper.GetFullyQualifiedName(credential), account, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    impersonate = true;
                }
            }

            ImpersonationContext impersonationContext = null;

            /////
            // Format up the connection string
            /////
            string connectionString = GetDatabaseConnectionString(server);

            try
            {
                if (impersonate)
                {
                    impersonationContext = ImpersonationContext.GetContext(credential);
                }

                using (var platformDbConnection = new SqlConnection(connectionString))
                {
                    platformDbConnection.Open( );

                    using (SqlCommand sqlCommand = platformDbConnection.CreateCommand( ))
                    {
                        /////
                        // If specific user exists then delete it
                        /////
                        sqlCommand.CommandText = string.Format(@"DECLARE @login NVARCHAR(MAX) = NULL; SELECT @login = name FROM sys.server_principals WHERE LOWER(name) = LOWER(N'{0}'); IF (@login IS NULL) CREATE LOGIN [{0}] FROM WINDOWS; GRANT VIEW SERVER STATE TO [{0}]", username);
                        sqlCommand.ExecuteNonQuery( );
                    }

                    platformDbConnection.Close( );
                }

                /////
                // Connect to the platform database and add in the new user to the database role.
                /////
                connectionString = $@"Server=tcp:{server};Integrated security=SSPI;database={catalog}";

                using (var platformDbConnection = new SqlConnection(connectionString))
                {
                    platformDbConnection.Open( );

                    using (SqlCommand sqlCommand = platformDbConnection.CreateCommand( ))
                    {
                        // If specific user exists then delete it
                        sqlCommand.CommandText = string.Format(@"DECLARE @user NVARCHAR(MAX) = NULL; SELECT @user = name FROM sys.database_principals WHERE LOWER(name) = LOWER(N'{0}'); IF (@user IS NOT NULL) EXEC ('ALTER USER [' + @user + '] WITH LOGIN = [{0}]') ELSE CREATE USER [{0}] FOR LOGIN [{0}]", username);
                        sqlCommand.ExecuteNonQuery( );

                        /////
                        // Assign the role for the user
                        /////
                        sqlCommand.CommandText = string.Format(@"exec sp_addrolemember N'{1}', N'{0}'", username, role);
                        sqlCommand.ExecuteNonQuery( );
                    }
                    platformDbConnection.Close( );
                }
            }
            finally
            {
                impersonationContext?.Dispose( );
            }
        }
 public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
 {
     CredentialHelper.SetSessionData(_user, _password, ref request);
     InvokePreRequestingService(new CentralSessionDataEventArgs <Message>(request));
     return(null);
 }
예제 #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="audience">我是谁,即jwt是颁发给谁的</param>
        /// <param name="authority">当局。我该去向谁核实,即是谁颁发了这个jwt</param>
        /// <returns></returns>
        /// <exception cref="WebApiException"></exception>
        public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration,
                                                                 Func <JwtBearerChallengeContext, Task> onChallenge,
                                                                 Func <TokenValidatedContext, Task> onTokenValidated,
                                                                 Func <AuthenticationFailedContext, Task> onAuthenticationFailed,
                                                                 Func <ForbiddenContext, Task> onForbidden,
                                                                 Func <MessageReceivedContext, Task> onMessageReceived)
        {
            JwtClientSettings jwtSettings = new JwtClientSettings();

            configuration.Bind(jwtSettings);

            X509Certificate2 encryptCert = CertificateUtil.GetCertificateFromSubjectOrFile(
                jwtSettings.JwtContentCertificateSubject,
                jwtSettings.JwtContentCertificateFileName,
                jwtSettings.JwtContentCertificateFilePassword);

            return
                (services
                 .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                 .AddJwtBearer(jwtOptions =>
            {
//#if DEBUG
//                    jwtOptions.RequireHttpsMetadata = false;
//#endif
                jwtOptions.Audience = jwtSettings.Audience;
                jwtOptions.Authority = jwtSettings.Authority;
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    RequireExpirationTime = true,
                    RequireSignedTokens = true,
                    RequireAudience = true,
                    TryAllIssuerSigningKeys = true,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    TokenDecryptionKey = CredentialHelper.GetSecurityKey(encryptCert)
                };
                jwtOptions.Events = new JwtBearerEvents
                {
                    OnChallenge = onChallenge,
                    OnAuthenticationFailed = onAuthenticationFailed,
                    OnMessageReceived = onMessageReceived,
                    OnTokenValidated = onTokenValidated,
                    OnForbidden = onForbidden
                };
//#if DEBUG
//                    //这是为了ubuntu这货,在开发阶段不认开发证书。这个http请求,是由jwt audience 发向 jwt authority的。authority配置了正式证书后,就没问题了
//                    jwtOptions.BackchannelHttpHandler = new HttpClientHandler
//                    {
//                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
//                        {
//                            if (cert!.Issuer.Equals("CN=localhost", GlobalSettings.Comparison))
//                                return true;
//                            return errors == System.Net.Security.SslPolicyErrors.None;
//                        }
//                    };
//#endif
            }));
        }
예제 #22
0
        /// <summary>
        ///     Creates and opens a database connection using the specified properties.
        /// </summary>
        /// <param name="databaseInfo">An object describing the database properties.</param>
        /// <exception cref="InvalidOperationException"></exception>
        /// <returns>
        ///     An open database connection.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">databaseInfo</exception>
        /// <exception cref="System.InvalidOperationException">The specified database provider is not supported.</exception>
        /// <exception cref="System.Exception">Cannot open the database connection.</exception>
        private static IDbConnection CreateConnection(DatabaseInfo databaseInfo)
        {
            if (databaseInfo == null)
            {
                throw new ArgumentNullException("databaseInfo");
            }

            IDbConnection connection = null;

            try
            {
                // Attempt to open a connection to the database

                connection = new SqlConnection(databaseInfo.ConnectionString);
                bool impersonate = false;

                if (databaseInfo.Authentication == DatabaseAuthentication.Integrated)
                {
                    if (databaseInfo.Credentials != null)
                    {
                        impersonate = true;

                        // Check if the context identity matches the current windows identity
                        WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

                        if (windowsIdentity != null)
                        {
                            var    principal = new WindowsPrincipal(windowsIdentity);
                            string account   = ((WindowsIdentity)principal.Identity).Name;
                            if (String.Compare(CredentialHelper.GetFullyQualifiedName(databaseInfo.Credentials), account, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                impersonate = false;
                            }
                        }
                    }
                }

                // Open the database connection (impersonate if required)
                if (impersonate)
                {
                    using (ImpersonationContext.GetContext(databaseInfo.Credentials))
                    {
                        connection.Open();
                    }
                }
                else
                {
                    connection.Open();
                }
            }
            catch (Exception)
            {
                if (connection != null)
                {
                    connection.Close();
                }
                throw;
            }

            return(connection);
        }
 /// <summary>
 /// Called after an inbound message has been received but before the message is dispatched to the intended operation.
 /// </summary>
 /// <returns>
 /// The object used to correlate state. This object is passed back in the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.BeforeSendReply(System.ServiceModel.Channels.Message@,System.Object)"/> method.
 /// </returns>
 /// <param name="request">The request message.</param><param name="channel">The incoming channel.</param><param name="instanceContext">The current service instance.</param>
 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     CentralSessionDataContext.Current.RequestSession = CredentialHelper.GetSessionData(request);
     return(true);
 }
예제 #24
0
        public static async Task <bool> RetrieveCredentialOnPremise(SessionStartInfo info, CredType expectedCredType, Binding binding)
        {
            bool popupDialog = false;

            // Make sure that we have a password and credentials for the user.
            if (String.IsNullOrEmpty(info.Username) || String.IsNullOrEmpty(info.InternalPassword))
            {
                string username = null;

                // First try to get something from the cache.
                if (String.IsNullOrEmpty(info.Username))
                {
                    username = WindowsIdentity.GetCurrent().Name;
                }
                else
                {
                    username = info.Username;
                }

                // Use local machine name for session without service job
                string headnode = info.Headnode;
                if (String.IsNullOrEmpty(headnode))
                {
                    headnode = Environment.MachineName;
                }

                //TODO: SF: headnode is a gateway string now
                // For back compact, get the cached password if it exists.
                byte[] cached = CredentialHelper.FetchPassword(headnode, username);
                if (cached != null)
                {
                    info.Username         = username;
                    info.InternalPassword = Encoding.Unicode.GetString(ProtectedData.Unprotect(cached, null, DataProtectionScope.CurrentUser));
                }
                else
                {
                    if (expectedCredType != CredType.None)
                    {
                        if (expectedCredType == CredType.Either || expectedCredType == CredType.Either_CredUnreusable)
                        {
                            // Pops up dialog asking users to specify the type of the credetial (password or certificate).
                            // The behavior here aligns with the job submission.
                            expectedCredType = CredUtil.PromptForCredentialType(bConsole, hwnd, expectedCredType);
                        }

                        Debug.Assert(expectedCredType == CredType.Password ||
                                     expectedCredType == CredType.Password_CredUnreusable ||
                                     expectedCredType == CredType.Certificate);

                        if (expectedCredType == CredType.Password)
                        {
                            bool         fSave    = false;
                            SecureString password = null;
                            Credentials.PromptForCredentials(headnode, ref username, ref password, ref fSave, bConsole, hwnd);
                            popupDialog = true;

                            info.Username         = username;
                            info.SavePassword     = fSave;
                            info.InternalPassword = Credentials.UnsecureString(password);
                        }
                        else if (expectedCredType == CredType.Password_CredUnreusable)
                        {
                            SecureString password = null;
                            Credentials.PromptForCredentials(headnode, ref username, ref password, bConsole, hwnd);
                            popupDialog = true;

                            info.Username         = username;
                            info.SavePassword     = false;
                            info.InternalPassword = Credentials.UnsecureString(password);
                        }
                        else
                        {
                            // Get the value of cluster parameter HpcSoftCardTemplate.
                            SessionLauncherClient client = new SessionLauncherClient(await Utility.GetSessionLauncherAsync(info, binding).ConfigureAwait(false), binding, info.IsAadOrLocalUser);
                            string softCardTemplate      = String.Empty;
                            try
                            {
                                softCardTemplate = await client.GetSOAConfigurationAsync(Constant.HpcSoftCardTemplateParam).ConfigureAwait(false);
                            }
                            finally
                            {
                                Utility.SafeCloseCommunicateObject(client);
                            }

                            // Query certificate from local store, and pops up CertSelectionDialog.
                            SecureString pfxPwd;
                            info.Certificate = CredUtil.GetCertFromStore(null, softCardTemplate, bConsole, hwnd, out pfxPwd);
                            info.PfxPassword = Credentials.UnsecureString(pfxPwd);
                        }
                    }
                    else
                    {
                        // Expect to use the cached credential at scheuler side.
                        // Exception may happen later if no cached redential or it is invalid.
                        info.ClearCredential();
                        info.Username = username;
                    }
                }
            }

            return(popupDialog);
        }
예제 #25
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Up and Running!");
            ParameterChecker parameterChecker = new ParameterChecker(req.Query);

            if (!parameterChecker.IsValidConfig)
            {
                return(new BadRequestResult());
            }
            ModeHelper modeHelper = new ModeHelper(req.Query, req.Headers);
            IMode      mode       = modeHelper.Mode;

            log.LogInformation("Initialize Credential Helper");
            CredentialHelper credentialHelper = new CredentialHelper();
            var serviceClientCredentials      = await credentialHelper.GetAzureCredentials();

            string SubscriptionID = Environment.GetEnvironmentVariable("SubscriptionID", EnvironmentVariableTarget.Process);

            string    resourceGroupName = req.Query["ResourceGroupName"];
            DnsHelper dnsHelper         = null;

            try
            {
                dnsHelper = new DnsHelper(serviceClientCredentials, SubscriptionID, resourceGroupName, mode.Zone);
            }
            catch (Exception e)
            {
                log.LogError(e.Message, e.StackTrace);
            }

            bool recordExists = await dnsHelper.RecordExists(mode);

            RecordSet newRecordSet = null;

            if ((!recordExists) && mode.AutoCreateZone)
            {
                try
                {
                    newRecordSet = await dnsHelper.CreateZone(mode);
                }
                catch (Exception e)
                {
                    return((ActionResult) new BadRequestObjectResult(e.Message));
                }
            }

            string answer         = string.Empty;
            bool   zoneIsUpToDate = await dnsHelper.ZoneIsUpToDate(mode.Hostname, mode.Type, mode.Address);

            if (!zoneIsUpToDate)
            {
                try
                {
                    newRecordSet = await dnsHelper.UpdateZone(mode);
                }
                catch (Exception e)
                {
                    return((ActionResult) new BadRequestObjectResult(e.Message));
                }
            }

            if (newRecordSet != null)
            {
                answer = JsonConvert.SerializeObject(newRecordSet);
                return((ActionResult) new OkObjectResult($"{answer}"));
            }
            else
            {
                return((ActionResult) new OkResult());
            }
        }
예제 #26
0
        protected AbstractMongoManager(string _name)
        {
            DBCredentials credentials = CredentialHelper.GetCredentials(_name);

            Initialize(credentials);
        }
 public virtual Credential GetCredentialsForNode(Node node)
 {
     return(CredentialHelper.ParseCredentialsFromNode(node));
 }
예제 #28
0
        internal void DoInventory(BackgroundInventoryManager.InventoryTask task)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            Node      node      = NodeBLDAL.GetNode(task.NodeID);

            if (node == null || node.get_PolledStatus() != 1)
            {
                BackgroundInventoryManager.log.InfoFormat("Skipping inventorying of Node {0}, status is not UP.", (object)task.NodeID);
            }
            else
            {
                SnmpSettings snmpSettings = new SnmpSettings();
                snmpSettings.set_AgentPort((int)node.get_SNMPPort());
                snmpSettings.set_ProtocolVersion((SNMPVersion)node.get_SNMPVersion());
                snmpSettings.set_TargetIP(IPAddress.Parse(node.get_IpAddress()));
                SnmpSettings          nodeSettings        = snmpSettings;
                SnmpInventorySettings inventorySettings   = new SnmpInventorySettings(node.get_SysObjectID());
                SnmpCredentials       credentialsFromNode = CredentialHelper.ParseCredentialsFromNode(node) as SnmpCredentials;
                List <string>         detectedPollers     = new List <string>();
                if (BackgroundInventoryManager.log.get_IsInfoEnabled())
                {
                    BackgroundInventoryManager.log.InfoFormat("Starting inventorying of Node {0}, NeedsInventory = '{1}'", (object)task.NodeID, (object)task.Settings);
                }
                string[]      array          = ((IEnumerable <string>)task.Settings.Split(':')).Distinct <string>().ToArray <string>();
                List <string> failedTasks    = new List <string>();
                List <string> completedTasks = new List <string>();
                foreach (string key in array)
                {
                    if (!this.inventories.ContainsKey(key))
                    {
                        failedTasks.Add(key);
                        if (BackgroundInventoryManager.log.get_IsErrorEnabled())
                        {
                            BackgroundInventoryManager.log.ErrorFormat("Unable to inventory '{0}' on Node {1}", (object)key, (object)task.NodeID);
                        }
                    }
                    else
                    {
                        if (this.scheduler.IsTaskCanceled)
                        {
                            if (BackgroundInventoryManager.log.get_IsInfoEnabled())
                            {
                                BackgroundInventoryManager.log.InfoFormat("Inventorying of Node {0} was canceled. ElapsedTime = {1}", (object)task.NodeID, (object)stopwatch.ElapsedMilliseconds);
                            }
                            stopwatch.Stop();
                            return;
                        }
                        InventoryPollersResult inventoryPollersResult = this.inventories[key](nodeSettings, inventorySettings, credentialsFromNode);
                        if (inventoryPollersResult == null)
                        {
                            failedTasks.Add(key);
                            if (BackgroundInventoryManager.log.get_IsErrorEnabled())
                            {
                                BackgroundInventoryManager.log.ErrorFormat("Inventory '{0}' on Node {1} returned null result", (object)key, (object)task.NodeID);
                            }
                        }
                        else if (((InventoryResultBase)inventoryPollersResult).get_Outcome() == 1)
                        {
                            completedTasks.Add(key);
                            detectedPollers.AddRange((IEnumerable <string>)inventoryPollersResult.get_PollerTypes());
                        }
                        else
                        {
                            failedTasks.Add(key);
                            if (((InventoryResultBase)inventoryPollersResult).get_Error() != null)
                            {
                                if (BackgroundInventoryManager.log.get_IsWarnEnabled())
                                {
                                    BackgroundInventoryManager.log.WarnFormat("Inventory '{0}' on Node {1} failed with code {2}", (object)key, (object)task.NodeID, (object)((InventoryResultBase)inventoryPollersResult).get_Error().get_ErrorCode());
                                }
                                if (((InventoryResultBase)inventoryPollersResult).get_Error().get_ErrorCode() != 31002U)
                                {
                                    List <string> list = ((IEnumerable <string>)array).Where <string>((Func <string, bool>)(n => !completedTasks.Contains(n) && !failedTasks.Contains(n))).ToList <string>();
                                    if (list.Count > 0)
                                    {
                                        failedTasks.AddRange((IEnumerable <string>)list);
                                        if (BackgroundInventoryManager.log.get_IsWarnEnabled())
                                        {
                                            BackgroundInventoryManager.log.WarnFormat("Skipping inventory for '{0}' on Node {1}", (object)string.Join(":", list.ToArray()), (object)task.NodeID);
                                            break;
                                        }
                                        break;
                                    }
                                }
                            }
                            else if (BackgroundInventoryManager.log.get_IsWarnEnabled())
                            {
                                BackgroundInventoryManager.log.WarnFormat("Inventory '{0}' on Node {1} failed on unknown error", (object)key, (object)task.NodeID);
                            }
                        }
                    }
                }
                string lastNodeSettings = NodeSettingsDAL.GetLastNodeSettings(task.NodeID, (string)CoreConstants.NeedsInventoryFlag);
                if ((string.IsNullOrEmpty(lastNodeSettings) || !lastNodeSettings.Equals(task.Settings, StringComparison.OrdinalIgnoreCase)) && BackgroundInventoryManager.log.get_IsInfoEnabled())
                {
                    BackgroundInventoryManager.log.InfoFormat("Skipping inventory result processing for Node {0}, NeedsInventory flag changed. OldValue = '{1}', NewValue = '{2}'.", (object)task.NodeID, (object)task.Settings, (object)lastNodeSettings);
                }
                else
                {
                    this.InsertDetectedPollers(task, detectedPollers);
                    if (failedTasks.Count == 0)
                    {
                        NodeSettingsDAL.DeleteSpecificSettingForNode(task.NodeID, (string)CoreConstants.NeedsInventoryFlag);
                        if (BackgroundInventoryManager.log.get_IsInfoEnabled())
                        {
                            BackgroundInventoryManager.log.InfoFormat("Inventorying of Node {0} completed in {1}ms.", (object)task.NodeID, (object)stopwatch.ElapsedMilliseconds);
                        }
                    }
                    else if (failedTasks.Count < array.Length)
                    {
                        string str = string.Join(":", failedTasks.ToArray());
                        NodeSettingsDAL.SafeInsertNodeSetting(task.NodeID, (string)CoreConstants.NeedsInventoryFlag, (object)str);
                        if (BackgroundInventoryManager.log.get_IsInfoEnabled())
                        {
                            BackgroundInventoryManager.log.InfoFormat("Inventorying of Node {0} partially completed in {1}ms. NeedsInventory updated to '{2}'", (object)task.NodeID, (object)stopwatch.ElapsedMilliseconds, (object)str);
                        }
                    }
                    else if (BackgroundInventoryManager.log.get_IsInfoEnabled())
                    {
                        BackgroundInventoryManager.log.InfoFormat("Inventorying of Node {0} failed. Elapsed time {1}ms.", (object)task.NodeID, (object)stopwatch.ElapsedMilliseconds);
                    }
                    stopwatch.Stop();
                }
            }
        }
예제 #29
0
        /// <summary>
        ///     Installs the service(s) in the specified assembly.
        /// </summary>
        /// <param name="path">
        ///     A string containing the path to the service assembly.
        /// </param>
        /// <param name="startMode">
        ///     An enumeration that describes how and when this service is started.
        /// </param>
        /// <param name="account">
        ///     An enumeration that describes the type of account under which the service will run.
        /// </param>
        /// <param name="credentials">
        ///     The user credentials of the account under which the service will run.
        /// </param>
        /// <param name="parameters">
        ///     A dictionary of parameters passed to the service's installer.
        /// </param>
        public static void InstallService(string path, ServiceStartMode startMode, ServiceAccount account, NetworkCredential credentials, StringDictionary parameters)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("The specified path parameter is invalid.");
            }

            string filename = Path.GetFileNameWithoutExtension(path);

            try
            {
                // Initialize the service installer
                Assembly serviceAssembly  = Assembly.LoadFrom(path);
                var      serviceInstaller = new AssemblyInstaller(serviceAssembly, null);

                var commandLine = new ArrayList
                {
                    string.Format("StartMode={0}", startMode.ToString("g"))
                };

                // Set the service start mode

                // Set the service account
                switch (account)
                {
                case ServiceAccount.LocalService:
                case ServiceAccount.NetworkService:
                case ServiceAccount.LocalSystem:
                {
                    commandLine.Add(string.Format("Account={0}", account.ToString("g")));
                    break;
                }

                case ServiceAccount.User:
                {
                    commandLine.Add(string.Format("Account={0}", CredentialHelper.GetFullyQualifiedName(credentials)));
                    commandLine.Add(string.Format("Password={0}", credentials.Password));
                    break;
                }
                }

                // Set any parameters
                if (parameters != null)
                {
                    foreach (string key in parameters.Keys)
                    {
                        commandLine.Add(string.Format("{0}={1}", key, parameters[key]));
                    }
                }

                // Initialize the service installer
                serviceInstaller.CommandLine = ( string[] )commandLine.ToArray(typeof(string));

                // Initialize the base installer
                var transactedInstaller = new TransactedInstaller( );
                transactedInstaller.Installers.Add(serviceInstaller);
                transactedInstaller.Context = new InstallContext(string.Format("{0}.log", filename), ( string[] )commandLine.ToArray(typeof(string)));

                // Install the service
                var savedState = new Hashtable( );
                transactedInstaller.Install(savedState);
            }
            catch (Exception exception)
            {
                throw new Exception("Unable to install the specified service.", exception);
            }
        }
예제 #30
0
        /// <summary>
        /// Deploys the specified database.
        /// </summary>
        /// <param name="dacpacPath">The DacPac path.</param>
        /// <param name="serverName">Name of the server.</param>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="filePrefix">The file prefix.</param>
        /// <param name="dbUser">The database user.</param>
        /// <param name="dbPassword">The database password.</param>
        /// <param name="mdfDirectory">The MDF directory.</param>
        /// <param name="ldfDirectory">The LDF directory.</param>
        /// <param name="logger">The logger.</param>
        /// <exception cref="System.ArgumentNullException">dacpacPath</exception>
        /// <exception cref="System.IO.FileNotFoundException">Specified DacPac file does not exist</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
        /// <remarks>
        /// Both the mdfPath and ldfPath values have to be set to invoke the DatabaseCreationLocationModifier.
        /// </remarks>
        public static void DeployDatabase(string dacpacPath, string serverName = "localhost", string databaseName = "SoftwarePlatform", string filePrefix = "SoftwarePlatform", string dbUser = null, string dbPassword = null, string mdfDirectory = null, string ldfDirectory = null, Action <string> logger = null)
        {
            if (string.IsNullOrEmpty(dacpacPath))
            {
                throw new ArgumentNullException(nameof(dacpacPath));
            }

            if (!File.Exists(dacpacPath))
            {
                throw new FileNotFoundException("Specified DacPac file does not exist", dacpacPath);
            }

            if (string.IsNullOrEmpty(serverName))
            {
                serverName = "localhost";
            }

            if (string.IsNullOrEmpty(databaseName))
            {
                databaseName = "SoftwarePlatform";
            }

            if (string.IsNullOrEmpty(filePrefix))
            {
                filePrefix = "SoftwarePlatform";
            }

            bool databaseCreationLocationModifierActive = !string.IsNullOrEmpty(mdfDirectory) && !string.IsNullOrEmpty(ldfDirectory);

            var contributors = new List <string>( );

            if (databaseCreationLocationModifierActive)
            {
                /////
                //Contributor to set the MDF and LDF file locations.
                /////
                contributors.Add("ReadiNowDeploymentPlanContributors.DatabaseCreationLocationModifier");
            }

            var contributorArguments = new Dictionary <string, string>( );

            if (databaseCreationLocationModifierActive)
            {
                /////
                // Set the file paths.
                /////
                string mdfFileName = string.Format("{0}_Dat.mdf", filePrefix);
                string ldfFileName = string.Format("{0}_Log.ldf", filePrefix);

                string mdfFilePath = Path.Combine(mdfDirectory, mdfFileName);
                string ldfFilePath = Path.Combine(ldfDirectory, ldfFileName);

                contributorArguments.Add("DatabaseCreationLocationModifier.MdfFilePath", mdfFilePath);
                contributorArguments.Add("DatabaseCreationLocationModifier.LdfFilePath", ldfFilePath);
            }

            var options = new DacDeployOptions
            {
                BlockOnPossibleDataLoss = false
            };

            if (contributors.Count > 0)
            {
                /////
                // Add any contributors.
                /////
                options.AdditionalDeploymentContributors = string.Join(";", contributors);

                if (contributorArguments.Count > 0)
                {
                    /////
                    // Add any contributor arguments.
                    /////
                    options.AdditionalDeploymentContributorArguments = string.Join(";", contributorArguments.Select(arg => string.Format("{0}={1}", arg.Key, arg.Value)));
                }
            }

            bool impersonate = false;
            var  credential  = new NetworkCredential( );

            if (!string.IsNullOrEmpty(dbUser))
            {
                credential = CredentialHelper.ConvertToNetworkCredential(dbUser, dbPassword);

                /////
                // Check if the context identity matches the current windows identity
                /////
                WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent( );

                if (windowsIdentity != null)
                {
                    var principal = new WindowsPrincipal(windowsIdentity);

                    string account = (( WindowsIdentity )principal.Identity).Name;

                    if (String.Compare(CredentialHelper.GetFullyQualifiedName(credential), account, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        impersonate = true;
                    }
                }
            }

            ImpersonationContext impersonationContext = null;

            try
            {
                using (DacPackage dacpac = DacPackage.Load(dacpacPath, DacSchemaModelStorageType.Memory))
                {
                    if (impersonate)
                    {
                        impersonationContext = ImpersonationContext.GetContext(credential);
                    }

                    string connectionString = "Data Source=" + serverName + ";Integrated Security=True";

                    var dacServices = new DacServices(connectionString);

                    dacServices.Message += (sender, e) => LogDacpacMessage(e, logger);

                    dacServices.Deploy(dacpac, databaseName, true, options);
                }
            }
            catch (DacServicesException exc)
            {
                DacMessage directoryNotFoundMessage = exc.Messages.FirstOrDefault(message => message.MessageType == DacMessageType.Error && message.Number == 72014);

                if (directoryNotFoundMessage != null)
                {
                    var pathRegex = new Regex("Directory lookup for the file \"(.*)?\" failed");

                    Match match = pathRegex.Match(directoryNotFoundMessage.Message);

                    if (match.Success)
                    {
                        string directory = Path.GetDirectoryName(match.Groups[1].Value);

                        throw new DirectoryNotFoundException(string.Format("Directory '{0}' was not found. Please create it prior to deploying the database.", directory), exc);
                    }
                }

                throw;
            }
            finally
            {
                if (impersonationContext != null)
                {
                    impersonationContext.Dispose( );
                }
            }
        }