Ejemplo n.º 1
0
        //
        // Authenticates against the given Jira server
        //
        private static Result Authenticate(string server, string username, string password, Logging.Logging logger)
        {
            // Check we have the properties we need
            bool validServer   = string.IsNullOrWhiteSpace(server) == false;
            bool validUser     = string.IsNullOrWhiteSpace(username) == false;
            bool validPassword = string.IsNullOrWhiteSpace(password) == false;

            // If it's not valid, throw and we're done
            if (validServer == false || validUser == false || validPassword == false)
            {
                logger.Log("Invalid server, username or password requested");
                throw new ArgumentException("Invalid server, username or password requested");
            }

            // Create our rest client
            Atlassian.Jira.Jira jiraInstance = null;
            try
            {
                jiraInstance = Atlassian.Jira.Jira.CreateRestClient(server, username, password);
            }
            catch (Exception e)
            {
                string message = string.Format("Unable to generate Jira instance for user '{0}'\n\n{1}", username, e.InnerException.Message);

                logger.Log(message);
                throw new InvalidOperationException(message);
            }

            // Check we can access this user
            try
            {
                // Pull out the user
                Task <Atlassian.Jira.JiraUser> thisUser = jiraInstance.Users.GetUserAsync(username);
                thisUser.Wait();

                // If we get here, the user exists and is fine
            }
            catch (Exception)
            {
                string message = string.Format("Unable to access Jira user '{0}'\n\nIf your username and password is correct, it is likely you have been locked out of your account.\n\nPlease visit {1} to unlock your account and then try again", username, server);

                logger.Log(message);
                throw new InvalidOperationException(message);
            }

            // Return the result
            return(new Result(true, "Successfully authenticated against the Jira server"));
        }
        //
        // Clears an existing credentials object
        //
        public static Credentials Clear(string server, Logging.Logging logger)
        {
            logger.Log("Clearing credentials for {0}", server);
            string filePath = GetServerFilePath(server);

            if (File.Exists(filePath) == true)
            {
                logger.Log(" * Deleted credentials file {0}", filePath);
                File.Delete(filePath);
            }

            // Load the credentials in
            Credentials loadedCredentials = Create(server, logger);

            return(loadedCredentials);
        }
        //
        // Creates a credentials object from an existing server file
        //
        public static Credentials Create(string server, Logging.Logging logger)
        {
            logger.Log("Creating credentials object for {0}", server);

            // Get the path to these credentials
            string filePath = GetServerFilePath(server);

            if (File.Exists(filePath) == false)
            {
                logger.Log(" * Unable to find the credentials file {0}", filePath);
                return(null);
            }

            Credentials credentials = null;

            try
            {
                // Load in the data
                string[] credentialData = File.ReadAllLines(filePath);

                // Convert the data from the credentials file into it's own array
                string[] fileData = new string[credentialData.Length - 2];
                for (int i = 0; i < fileData.Length; ++i)
                {
                    fileData[i] = credentialData[i + 2];
                }

                // Create our object
                Type thisType = Type.GetType("RB_Tools.Shared.Authentication.Credentials." + credentialData[0]);
                credentials = (Credentials)Activator.CreateInstance(thisType, fileData);

                logger.Log("Creating credentials object {0}", thisType.Name);

                // Set our server
                credentials.Server = credentialData[1];
            }
            catch (Exception e)
            {
                logger.Log(" * Unable to load the credentials data\n{0}\n", e.Message);
                return(null);
            }

            // We have an object
            return(credentials);
        }
Ejemplo n.º 4
0
        //
        // Starts authenticating against the Jira server
        //
        public static Credentials.Credentials Authenticate(Logging.Logging logger)
        {
            // Get our data
            string serverUrl  = Server.Names.Url[(int)Server.Names.Type.Jira];
            string serverName = Server.Names.Type.Jira.ToString();

            logger.Log("Starting authentication");
            logger.Log(" * Name: {0}", serverName);
            logger.Log(" * Url: {0}", serverUrl);

            // Kick off the RB authentation
            Dialogs.SimpleAuthentication authDialog = new Dialogs.SimpleAuthentication(serverName, serverUrl, Jira.Authenticate, logger);
            authDialog.ShowDialog();

            // Load in our credentials object
            Credentials.Credentials rbCredentials = Credentials.Credentials.Create(serverUrl, logger);
            return(rbCredentials);
        }
        //
        // Creates a new credentials file for a given server
        //
        public static Credentials Create(string server, string user, string password, Logging.Logging logger)
        {
            logger.Log("Creating credentials for {0} using username", server, user);

            // Encrypt the password
            password = Cipher.Encrypt(password, Identifiers.UUID);
            StoreCredentials(typeof(Simple).Name, server, new string[] { user, password }, logger);

            // Load the credentials in
            Credentials loadedCredentials = Create(server, logger);

            return(loadedCredentials);
        }
        //
        // Saves a given credentials file
        //
        private static void StoreCredentials(string type, string server, string[] data, Logging.Logging logger)
        {
            logger.Log("Storing credentials for {0} using credentials type {1}", server, type);

            // Get the file path
            string path = GetServerFilePath(server);

            // Write our the data
            using (StreamWriter file = new StreamWriter(path))
            {
                // Write out the header info
                file.WriteLine(type);
                file.WriteLine(server);

                // Write out the specific data
                foreach (string thisLine in data)
                {
                    file.WriteLine(thisLine);
                }
            }
            logger.Log(" * Credentials stored - {0}", path);
        }
        //
        // Returns the log for a specific revision
        //
        public static string GetLog(string workingDirectory, string revision, bool xml, Logging.Logging logger)
        {
            // Generate the info
            string infoPath = string.Format(@"log ""{0}"" --revision {1} {2}", workingDirectory, revision, xml == true ? "--xml" : "");

            logger.Log("Running SVN command '{0}'", infoPath);

            // Run the process
            Process.Output infoOutput = Process.Start(null, "svn", infoPath);
            if (string.IsNullOrWhiteSpace(infoOutput.StdOut) == true)
            {
                logger.Log("Log command generated no output");
                return(null);
            }

            // Sanitise it
            string sanitisedOutput = infoOutput.StdOut.Replace("\r\n", "\n");

            logger.Log("Command returned\n{0}\n", sanitisedOutput);

            // Done
            return(sanitisedOutput);
        }
        /// <summary>
        /// Load a single extension. Has the same usage value as <see cref="FolderSetup_listeners(string, Dictionary{int, ServerExtensionInitializer}, Logging.Logging)"/>
        /// </summary>
        /// <param name="asmPath">Path to the assembly extension</param>
        /// <param name="output">The dictionary to put the link between ports and extensions</param>
        /// <param name="logOutput">Default : null. Logger to log information (ex : listener set up)</param>
        public static void LoadAssembly(string asmPath, Dictionary <PEndPoint, ServerExtensionInitializer> output, Logging.Logging logOutput = null)
        {
            var asm = Assembly.Load(File.ReadAllBytes(asmPath));

            foreach (var tstr in INTERACTION_CLASSES)
            {
                Type t = asm.GetType(tstr);
                if (t == null)
                {
                    continue;
                }
                MethodInfo minfo = t.GetMethod(LOAD_METHOD);
                if (minfo == null)
                {
                    continue;
                }

                var dic = (Dictionary <PEndPoint, Action <Client> >)minfo.Invoke(null, new object[] { logOutput });
                foreach (var entry in dic)
                {
                    if (output.ContainsKey(entry.Key))
                    {
                        if (logOutput != null)
                        {
                            logOutput.Alert("Assembly " + Path.GetFileNameWithoutExtension(asmPath) + " tried to bind port " + entry.Key.Port + ". That port is already bound");
                        }
                        continue;
                    }

                    output.Add(entry.Key, new ServerExtensionInitializer(asm, entry.Value, asmPath));
                    Listener.Instantiate(entry.Key);
                    if (logOutput != null)
                    {
                        logOutput.Log("Listener set up on port " + entry.Key.Port + " for assembly " + Path.GetFileNameWithoutExtension(asmPath));
                    }
                }
            }

            LOADED_ASSEMBLYS.Add(asm.GetName().Name, asm);
            EXTENSIONS_PATH.Add(asm.GetName().Name, asmPath);

            if (logOutput != null)
            {
                logOutput.Info("Extension assembly " + asm.GetName().Name + " loaded");
            }
        }
Ejemplo n.º 9
0
        //
        // Authenticates against the given RB server
        //
        private static Result Authenticate(string server, string username, string password, Logging.Logging logger)
        {
            // Check we have the properties we need
            bool validServer   = string.IsNullOrWhiteSpace(server) == false;
            bool validUser     = string.IsNullOrWhiteSpace(username) == false;
            bool validPassword = string.IsNullOrWhiteSpace(password) == false;

            // If it's not valid, throw and we're done
            if (validServer == false || validUser == false || validPassword == false)
            {
                logger.Log("Invalid server, username or password requested");
                throw new ArgumentException("Invalid server, username or password requested");
            }

            // Attempt to authenticate with the server
            string commandOptions = string.Format(@"login --server {0} --username {1} --password {2}", server, username, password);
            string rbtPath        = RB_Tools.Shared.Targets.Reviewboard.Path();

            logger.Log("Requesting authentication");
            logger.Log(" * {0} {1}", rbtPath, commandOptions.Replace(password, @"*****"));

            // Run the process
            Utilities.Process.Output output = Utilities.Process.Start(string.Empty, rbtPath, commandOptions);
            string errorFlag    = "ERROR: ";
            string criticalFlag = "CRITICAL: ";

            // Annoyingly, rbt seems to only post to stderr
            bool succeeded = string.IsNullOrWhiteSpace(output.StdErr) == true;

            if (succeeded == false)
            {
                logger.Log("Querying Standard Error for actual error message");
                succeeded = (output.StdErr.StartsWith(errorFlag) == false && output.StdErr.StartsWith(criticalFlag) == false);
            }

            // How did we do?
            string messageToShow = output.StdErr;

            if (succeeded == true)
            {
                logger.Log("Authentication succeeded");
                messageToShow = @"Successfully authenticated against the Reviewboard server";
            }
            else
            {
                logger.Log("Authentication failed - {0}", messageToShow);
            }

            // Return the result
            return(new Result(succeeded, messageToShow.Trim()));
        }
        //
        // Populates any existing credentials
        //
        private void PopulateExistingCredentials(string server)
        {
            // Load our credentials, since this can take a while do it on another thread
            BackgroundWorker authThread = new BackgroundWorker();

            // Called when we need to trigger the authentication
            authThread.DoWork += (object objectSender, DoWorkEventArgs args) =>
            {
                m_logger.Log("Starting generation of Simple credentials");
                args.Result = Credentials.Credentials.Create(server, m_logger);
            };

            authThread.RunWorkerCompleted += (object objectSender, RunWorkerCompletedEventArgs args) =>
            {
                // Set up the default state before we try to load the credentials
                UpdateAuthenticateDialogState(true);

                // Try and load in the credentials
                Credentials.Credentials credentials = null;
                if (args.Error != null)
                {
                    m_logger.Log("Exception thrown when trying to load the existing credentials for {0}\n\n{1}\n", server, args.Error.Message);

                    string message = string.Format("Exception thrown when trying to load the existing credentials for {0}\n\nException: {1}\n\nDescription: {2}", server, args.Error.GetType().Name, args.Error.Message);
                    MessageBox.Show(this, message, @"Unable to authenticate", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    credentials = args.Result as Credentials.Credentials;
                    m_logger.Log("Credentials generated");
                }

                // Load our credentials
                UpdateFieldProperties(credentials);
            };
            // Kick off the request
            authThread.RunWorkerAsync();
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Log information relative to a client on the main server logger
 /// </summary>
 /// <param name="level">Level to log</param>
 /// <param name="message">Message to log</param>
 /// <param name="client">Client whose the information is relative to</param>
 public static void CLog(LogLevel level, string message, Client client)
 {
     logging.Log("[CLIENT ID " + client.Id + "] " + message, level);
 }