Refactored POST request

pull/73/head
MillenniumEarl 2021-03-02 11:47:55 +01:00
parent 36f6075e32
commit 6e1e86a983
1 changed files with 62 additions and 24 deletions

View File

@ -68,25 +68,25 @@ export async function authenticate(credentials: credentials, force: boolean = fa
const secureURL = enforceHttpsUrl(f95url.F95_LOGIN_URL); const secureURL = enforceHttpsUrl(f95url.F95_LOGIN_URL);
// Prepare the parameters to send to the platform to authenticate // Prepare the parameters to send to the platform to authenticate
const params = new URLSearchParams(); const params = {
params.append("login", credentials.username); "login": credentials.username,
params.append("url", ""); "url": "",
params.append("password", credentials.password); "password": credentials.password,
params.append("password_confirm", ""); "password_confirm": "",
params.append("additional_security", ""); "additional_security": "",
params.append("remember", "1"); "remember": "1",
params.append("_xfRedirect", "https://f95zone.to/"); "_xfRedirect": "https://f95zone.to/",
params.append("website_code", ""); "website_code": "",
params.append("_xfToken", credentials.token); "_xfToken": credentials.token,
};
try { try {
// Try to log-in // Try to log-in
let config = Object.assign({}, commonConfig); const response = await fetchPOSTResponse(f95url.F95_LOGIN_URL, params, force);
if (force) delete config.jar;
const response = await axios.post(secureURL, params, config);
if (response.isSuccess()) {
// Parse the response HTML // Parse the response HTML
const $ = cheerio.load(response.data); const $ = cheerio.load(response.value.data as string);
// Get the error message (if any) and remove the new line chars // Get the error message (if any) and remove the new line chars
const errorMessage = $("body").find(f95selector.LOGIN_MESSAGE_ERROR).text().replace(/\n/g, ""); const errorMessage = $("body").find(f95selector.LOGIN_MESSAGE_ERROR).text().replace(/\n/g, "");
@ -95,6 +95,8 @@ export async function authenticate(credentials: credentials, force: boolean = fa
const result = errorMessage.trim() === ""; const result = errorMessage.trim() === "";
const message = errorMessage.trim() === "" ? "Authentication successful" : errorMessage; const message = errorMessage.trim() === "" ? "Authentication successful" : errorMessage;
return new LoginResult(result, message); return new LoginResult(result, message);
}
else throw response.value;
} catch (e) { } catch (e) {
shared.logger.error(`Error ${e.message} occurred while authenticating to ${secureURL}`); shared.logger.error(`Error ${e.message} occurred while authenticating to ${secureURL}`);
return new LoginResult(false, `Error ${e.message} while authenticating`); return new LoginResult(false, `Error ${e.message} while authenticating`);
@ -119,7 +121,7 @@ export async function getF95Token() {
/** /**
* Performs a GET request to a specific URL and returns the response. * Performs a GET request to a specific URL and returns the response.
*/ */
export async function fetchGETResponse(url: string): Promise<Result<GenericAxiosError, AxiosResponse<any>>>{ export async function fetchGETResponse(url: string): Promise<Result<GenericAxiosError, AxiosResponse<any>>> {
// Secure the URL // Secure the URL
const secureURL = enforceHttpsUrl(url); const secureURL = enforceHttpsUrl(url);
@ -128,10 +130,10 @@ export async function fetchGETResponse(url: string): Promise<Result<GenericAxios
const response = await axios.get(secureURL, commonConfig); const response = await axios.get(secureURL, commonConfig);
return success(response); return success(response);
} catch (e) { } catch (e) {
shared.logger.error(`Error ${e.message} occurred while trying to fetch ${secureURL}`); shared.logger.error(`(GET) Error ${e.message} occurred while trying to fetch ${secureURL}`);
const genericError = new GenericAxiosError({ const genericError = new GenericAxiosError({
id: 1, id: 1,
message:`Error ${e.message} occurred while trying to fetch ${secureURL}`, message:`(GET) Error ${e.message} occurred while trying to fetch ${secureURL}`,
error: e error: e
}); });
return failure(genericError); return failure(genericError);
@ -199,6 +201,42 @@ export async function getUrlRedirect(url: string): Promise<string> {
const response = await axios.head(url); const response = await axios.head(url);
return response.config.url; return response.config.url;
} }
/**
* Performs a POST request through axios.
* @param url URL to request
* @param params List of value pairs to send with the request
* @param force If `true`, the request ignores the sending of cookies already present on the device.
*/
export async function fetchPOSTResponse(url: string, params: { [s: string]: string }, force: boolean = false): Promise<Result<GenericAxiosError, AxiosResponse<any>>> {
// Secure the URL
const secureURL = enforceHttpsUrl(url);
// Prepare the parameters for the POST request
const urlParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) urlParams.append(key, value);
// Shallow copy of the common configuration object
const config = Object.assign({}, commonConfig);
// Remove the cookies if forced
if (force) delete config.jar;
// Send the POST request and await the response
try {
const response = await axios.post(secureURL, urlParams, config);
return success(response);
} catch (e) {
shared.logger.error(`(POST) Error ${e.message} occurred while trying to fetch ${secureURL}`);
const genericError = new GenericAxiosError({
id: 3,
message: `(POST) Error ${e.message} occurred while trying to fetch ${secureURL}`,
error: e
});
return failure(genericError);
}
}
//#endregion Utility methods //#endregion Utility methods
//#region Private methods //#region Private methods