Fixing login issue by bypassing the login form and making a request directly.

This commit is contained in:
Mateusz Majewski 2017-01-18 11:08:45 +02:00
parent e06ff53210
commit cc655b9e00

View File

@ -1,6 +1,14 @@
'use strict';
import request = require('request');
import cheerio = require('cheerio');
var isAuthenticated = false;
var isPremium = false;
var defaultHeaders:request.Headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
'Connection': 'keep-alive'
};
/**
* Performs a GET request for the resource.
@ -33,21 +41,50 @@ export function post(config: IConfig, options: request.Options, done: (err: Erro
*/
function authenticate(config: IConfig, done: (err: Error) => void) {
if (isAuthenticated || !config.pass || !config.user) return done(null);
var options = {
form: {
formname: 'RpcApiUser_Login',
fail_url: 'https://www.crunchyroll.com/login',
name: config.user,
password: config.pass
},
/* Bypass the login page and send a login request directly */
var options =
{
headers: defaultHeaders,
jar: true,
url: 'https://www.crunchyroll.com/?a=formhandler'
gzip: false,
url: 'https://www.crunchyroll.com/?a=formhandler&formname=RpcApiUser_Login&name=' + config.user + '&password=' + config.pass
};
request.post(options, (err: Error) => {
request(options, (err: Error, rep: string, body: string) =>
{
if (err) return done(err);
isAuthenticated = true;
done(null);
});
/* The page return with a meta based redirection, as we wan't to check that everything is fine, reload
* the main page. A bit convoluted, but more sure.
*/
var options =
{
headers: defaultHeaders,
jar: true,
url: 'http://www.crunchyroll.com/'
}
request(options, (err: Error, rep: string, body: string) =>
{
if (err) return done(err);
var $ = cheerio.load(body);
/* Check if auth worked */
var regexps = /ga\(\'set\', \'dimension[5-8]\', \'([^']*)\'\);/g
var dims = regexps.exec($('script').text())
for(var i = 1; i < 5; i++)
{
if ((dims[i] != undefined) && (dims[i] != "") && (dims[i] != "not-registered")) { isAuthenticated = true; }
if ((dims[i] == "premium") || (dims[i] == "premiumplus")) { isPremium = true; }
}
if (isAuthenticated == false)
{
var error = $('ul.message, li.error').text();
return done(new Error("Authentication failed: " + error));
}
if (isPremium == false) { console.info("Do not use this app without a premium account."); }
else { console.info("You have a premium account! Good!"); }
done(null);
})
})
}
/**
@ -56,7 +93,8 @@ function authenticate(config: IConfig, done: (err: Error) => void) {
function modify(options: string|request.Options): request.Options {
if (typeof options !== 'string') {
options.jar = true;
options.headers = defaultHeaders;
return options;
}
return {jar: true, url: options.toString()};
return {jar: true, headers: defaultHeaders, url: options.toString()};
}