From fc9dcfbdf9558ac95c939609a30e567b0d8d2f74 Mon Sep 17 00:00:00 2001 From: starnakin Date: Wed, 8 Nov 2023 13:16:58 +0100 Subject: [PATCH] add: documentation and init post --- src/client.js | 91 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 85 insertions(+), 6 deletions(-) diff --git a/src/client.js b/src/client.js index e37f815..fbb9cc6 100644 --- a/src/client.js +++ b/src/client.js @@ -1,24 +1,102 @@ +/** + * return the token from response + * + * @param {Response} response - The reponse +*/ + +function extract_csrf_token(response) +{ + let cookies = response.headers.get("set-cookie"); + csrf_token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';')) + return csrf_token; +} + class Client { + /** + * Create a client to interract with the api + * + * @param {string} url - The url of the backend + */ + constructor(url) { + /** + * The api token to be logged + * @type string */ this.token = undefined; + + /** + * The django csrftoken to send post data + * @type string */ this.csrf_token = undefined; + + /** + * The django csrfmiddlewaretoken to send post data + * @type string */ + this.csrfmiddlewaretoken = undefined + + /** + * The api url + * @type string */ this.url = url; } + /** + * return if the client is logged + */ get isAuthentificate() { return this.token != undefined; } + /** + * A no consummer function to send get requests + * + * @param {string} uri - The path want to get + */ async _get(uri) { let url = this.url + uri - console.log(url) - let response; - response = await fetch(url); - return response; + let response = await fetch(url); + this.csrf_token = extract_csrf_token(response); + return response; + } + + /** + * A no consummer function to send post requests + * + * @param {string} uri - The path want to post + */ + async _post(uri, data) + { + let url = this.url + uri + if (this.csrf_token === undefined) + { + let response = await fetch(url); + this.csrf_token = extract_csrf_token(response); + } + let response = await fetch(url, { + method: "POST", + headers: { + 'Referer': url, + }, + body: objectToFormData(data), + }); + console.log(response.status) + return response; + } + + /** + * Login your client with username and password + * + * @param {string} username - The username of the client + * @param {string} password - The password of the client + */ + async login(username, password) + { + let response = this._post(accounts_login, {'username': username, 'password': password}) + return response; } } @@ -28,6 +106,7 @@ let url = "http://0.0.0.0:8000/" let client = new Client(url) -console.log((await client._get(accounts_login))) +await client._get(accounts_login) +await client.login("bozoman", "man") -export {client} \ No newline at end of file +export {Client} \ No newline at end of file