private void confirmButton_Click(object sender, EventArgs e)
        {
            string code = codeText.Text;
            try
            {
                Credentials = CompanionAppService.Confirm(Credentials, code);
                Credentials.ToFile();
                CompanionAppService app = new CompanionAppService(Credentials);
                Commander Cmdr = app.Profile();
                Stage3 stage3 = new Stage3(Cmdr.Name);
                stage3.Show();
                this.Hide();

                }
                catch (EliteDangerousCompanionAppAuthenticationException ex)
            {
                Credentials.Clear();
                Credentials.ToFile();
                errorLabel.Text = ex.Message + "\r\nPlease restart this application to re-authenticate";
            }
            catch (EliteDangerousCompanionAppErrorException ex)
            {
                Credentials.Clear();
                Credentials.ToFile();
                errorLabel.Text = ex.Message + "\r\nPlease restart this application to re-authenticate";
            }
            catch (Exception ex)
            {
                Credentials.Clear();
                Credentials.ToFile();
                errorLabel.Text = "Unexpected problem\r\nPlease report this at http://github.com/CmdrMcDonald/EliteDangerousDataProvider/issues\r\n" + ex.Message + "\r\nPlease restart this application to re-authenticate";
            }
        }
        /// <summary>
        /// Obtain credentials from a file.  If the file name is not supplied the the default
        /// path of %APPDATA%\EDDI\credentials.json is used
        /// </summary>
        public static Credentials FromFile(string filename=null)
        {
            if (filename == null)
            {
                String dataDir = Environment.GetEnvironmentVariable("AppData") + "\\EDDI";
                Directory.CreateDirectory(dataDir);
                filename = dataDir + "\\credentials.json";
            }

            Credentials credentials;
            try
            {
                String credentialsData = File.ReadAllText(filename);
                credentials = JsonConvert.DeserializeObject<Credentials>(credentialsData);
            }
            catch
            {
                credentials = new Credentials();
            }

            credentials.dataPath = filename;
            return credentials;
        }
 public Stage2(Credentials Credentials)
 {
     InitializeComponent();
     this.Credentials = Credentials;
 }
 public CompanionAppService(Credentials credentials)
 {
     this.credentials = credentials;
 }
 private static void AddMachineTokenCookie(CookieContainer cookies, Credentials credentials)
 {
     var machineTokenCookie = new Cookie();
     machineTokenCookie.Domain = ".companion.orerve.net";
     machineTokenCookie.Path = "/";
     machineTokenCookie.Name = "mtk";
     machineTokenCookie.Value = credentials.machineToken;
     cookies.Add(machineTokenCookie);
 }
 private static void AddCompanionAppCookie(CookieContainer cookies, Credentials credentials)
 {
     var appCookie = new Cookie();
     appCookie.Domain = "companion.orerve.net";
     appCookie.Path = "/";
     appCookie.Name = "CompanionApp";
     appCookie.Value = credentials.appId;
     cookies.Add(appCookie);
 }
        public Commander Profile()
        {
            var cookieContainer = new CookieContainer();
            AddCompanionAppCookie(cookieContainer, credentials);
            AddMachineIdCookie(cookieContainer, credentials);
            AddMachineTokenCookie(cookieContainer, credentials);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverRoot + "/profile");
            request.AllowAutoRedirect = false;
            request.CookieContainer = cookieContainer;
            request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400)
            {
                // Redirect means the user needs to log in again
                throw new EliteDangerousCompanionAppAuthenticationException("You need to re-run the configuration application");
            }
            if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 500)
            {
                // Error probably means that the service is down
                throw new EliteDangerousCompanionAppErrorException("Elite: Dangerous service is down; please try later");
            }
            if ((int)response.StatusCode < 200 || (int)response.StatusCode > 299)
            {
                // Some other generic problem
                throw new EliteDangerousCompanionAppException("Error code " + response.StatusCode);
            }

            // Refresh the cookies from the raw information available to us
            String cookieHeader = response.Headers[HttpResponseHeader.SetCookie];
            if (cookieHeader != null)
            {
                Match companionAppMatch = Regex.Match(cookieHeader, @"CompanionApp=([^;]+)");
                if (companionAppMatch.Success)
                {
                    if (credentials == null) { credentials = new Credentials(); }
                    credentials.appId = companionAppMatch.Groups[1].Value;
                }
                Match machineIdMatch = Regex.Match(cookieHeader, @"mid=([^;]+)");
                if (machineIdMatch.Success)
                {
                    if (credentials == null) { credentials = new Credentials(); }
                    credentials.machineId = machineIdMatch.Groups[1].Value;
                }
                Match machineTokenMatch = Regex.Match(cookieHeader, @"mtk=([^;]+)");
                if (machineTokenMatch.Success)
                {
                    if (credentials == null) { credentials = new Credentials(); }
                    credentials.machineToken = machineTokenMatch.Groups[1].Value;
                }
            }

            // Update our credentials
            credentials.ToFile();

            // Obtain and parse our response
            var encoding = response.CharacterSet == ""
                        ? Encoding.UTF8
                        : Encoding.GetEncoding(response.CharacterSet);

            using (var stream = response.GetResponseStream())
            {
                var reader = new StreamReader(stream, encoding);
                return CommanderFromProfile(reader.ReadToEnd());
            }
        }
        ///<summary>Log in.  Returns credentials, or throws an exception if it fails</summary>
        public static Credentials Login(string username, string password)
        {
            Credentials credentials = null;
            string location = serverRoot + "/user/login";
            // Send the request.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location);
            request.AllowAutoRedirect = false;  // Don't redirect or we lose the cookies
            request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            string encodedUsername = WebUtility.UrlEncode(username);
            string encodedPassword = WebUtility.UrlEncode(password);
            byte[] data = Encoding.UTF8.GetBytes("email=" + encodedUsername + "&password="******"Username or password incorrect");
            }
            else if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 500)
            {
                // Problem with the service
                throw new EliteDangerousCompanionAppAuthenticationException("There is a problem with the Elite: Dangerous servers; please try again later");
            }
            else if ((int)response.StatusCode < 300 || (int)response.StatusCode > 399)
            {
                // We were expecting a redirect to the confirmation page and didn't get it; complain
                throw new EliteDangerousCompanionAppErrorException("Error code " + response.StatusCode);
            }

            // Obtain the cookies from the raw information available to us
            String cookieHeader = response.Headers[HttpResponseHeader.SetCookie];
            if (cookieHeader != null)
            {
                Match companionAppMatch = Regex.Match(cookieHeader, @"CompanionApp=([^;]+)");
                if (companionAppMatch.Success)
                {
                    if (credentials == null) { credentials = new Credentials(); }
                    credentials.appId = companionAppMatch.Groups[1].Value;
                }
                Match machineIdMatch = Regex.Match(cookieHeader, @"mid=([^;]+)");
                if (machineIdMatch.Success)
                {
                    if (credentials == null) { credentials = new Credentials(); }
                    credentials.machineId = machineIdMatch.Groups[1].Value;
                }
                Match machineTokenMatch = Regex.Match(cookieHeader, @"mtk=([^;]+)");
                if (machineTokenMatch.Success)
                {
                    if (credentials == null) { credentials = new Credentials(); }
                    credentials.machineToken = machineTokenMatch.Groups[1].Value;
                }
            }

            // At this stage we should have the CompanionApp and mid values
            if (credentials.appId == null)
            {
                throw new EliteDangerousCompanionAppAuthenticationException("Credentials are missing companion app ID");
            }
            if (credentials.machineId == null)
            {
                throw new EliteDangerousCompanionAppAuthenticationException("Credentials are missing machine ID");
            }

            return credentials;
        }