Example #1
0
        /// <summary>
        /// Sends a login request.
        /// </summary>
        /// <returns>The token if login was succesful, or null if not</returns>
        public string SendLoginRequest()
        {
            if (LoginInformation == null || LoginInformation.email == null || LoginInformation.email[0].Trim() == "" || LoginInformation.password == null || LoginInformation.password[0].Trim() == "")
            {
                throw new ArgumentNullException("You didn't supply login information!");
            }

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://discordapp.com/api/auth/login");

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";
            httpWebRequest.Timeout     = 30000;

            using (var sw = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                sw.Write(LoginInformation.AsJson());
                sw.Flush();
                sw.Close();
            }
            try
            {
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var sr = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result             = sr.ReadToEnd();
                    DiscordLoginResult dlr = JsonConvert.DeserializeObject <DiscordLoginResult>(result);
                    if (dlr.token != null || dlr.token.Trim() != "")
                    {
                        this.token = dlr.token;
                        try
                        {
                            string   sessionKeyHeader = httpResponse.Headers["set-cookie"].ToString();
                            string[] split            = sessionKeyHeader.Split(new char[] { '=', ';' }, 3);
                            sessionKey = split[1];
                        }
                        catch
                        { /*no session key fo u!*/ }
                        return(token);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (WebException e)
            {
                using (StreamReader s = new StreamReader(e.Response.GetResponseStream()))
                {
                    string             result  = s.ReadToEnd();
                    DiscordLoginResult jresult = JsonConvert.DeserializeObject <DiscordLoginResult>(result);
                    if (jresult.password != null)
                    {
                        throw new DiscordLoginException(jresult.password[0]);
                    }
                    if (jresult.email != null)
                    {
                        throw new DiscordLoginException(jresult.email[0]);
                    }
                }
            }
            return(null);
        }