kazatca / fill headers

// ==UserScript==
// @name         fill headers
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  shows how to use babel compiler
// @author       kazatca
// @require      https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.2/babel.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.js
// @match        https://utcom-gateway.unitedtraders.work/graphql
// @license MIT
// @copyright 2018, kazatca (https://openuserjs.org//users/kazatca)
// ==/UserScript==

var inline_src = (<><![CDATA[

    const url = 'https://sso.unitedtraders.work/auth/realms/aurora/protocol/openid-connect/token';

    const username = '';
    const password = '';

    const timeout = 270000;

    const getForm = values =>
      Object.keys(values).map(key => key + '=' + encodeURIComponent(values[key])).join('&');

    const post = body =>
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: getForm(body)
      })
      .then(resp => resp.json());

    const getToken = (username, password) =>
      post({
        grant_type: 'password',
        client_id: 'utcom',
        username: username,
        password: password
      });

    const updateToken = refresh_token =>
      post({
        grant_type: 'refresh_token',
        client_id: 'utcom',
        refresh_token
      });

    const setAuthorization = access_token =>
      s.dispatch({type: 'EDIT_HEADERS', payload: {headers: JSON.stringify({Authorization: 'Bearer ' + access_token})}});

    const updateHeader = tokens =>
      (tokens ? updateToken(tokens.refresh_token): getToken(username, password))
      .then(tokens => {
        if(!tokens){
          return;
        }

        setAuthorization(tokens.access_token);
        setTimeout(() => updateHeader(tokens), timeout);
      })

    const until = (cond, cb) =>
      cond() ? cb() : setTimeout(() => until(cond, cb), 500);

    console.log('headers autofill started');
    until(() => !!s, updateHeader);

]]></>).toString();
var c = Babel.transform(inline_src, { presets: [ "es2015", "es2016" ] });
eval(c.code);