{"size": 2305, "ext": "js", "max_stars_repo_path": "dashboard/src/auth.js", "max_stars_repo_name": "jmangelson/hakatime-plusplus", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dashboard/src/auth.js", "max_issues_repo_name": "jmangelson/hakatime-plusplus", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dashboard/src/auth.js", "max_forks_repo_name": "jmangelson/hakatime-plusplus", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.8706896552, "max_line_length": 75, "alphanum_fraction": 0.6056399132}
import m from "mithril";

import OverviewState from "./models/State.js";
import ProjectState from "./models/ProjectState.js";
import TimeRange from "./models/TimeRange.js";

let inMemToken = {
  token: "",
  tokenExpiry: "",
  username: ""
};

function clearToken() {
  inMemToken = {
    token: "",
    tokenExpiry: "",
    username: ""
  };
}

export function login(r) {
  inMemToken = {
    token: r.token,
    tokenExpiry: r.tokenExpiry,
    username: r.tokenUsername
  };
}

export function tryToRefresh(errMsg, callback) {
  m.request({
    method: "POST",
    url: "/auth/refresh_token"
  })
    .then(function (r) {
      login(r);

      typeof callback === "function" && callback();
    })
    .catch(function (e) {
      clearTokens();

      if (errMsg) {
        m.route.set("/login", { msg: errMsg });
      } else {
        if (e) console.log("refresh_token failed:", e.code);
        m.route.set("/login");
      }
    });
}

export function clearTokens() {
  clearToken();

  // to support logging out from all windows.
  window.localStorage.setItem("logout", Date.now());
}

export function logout() {
  // Force log-out will invalidate all other tokens.
  m.request({
    method: "POST",
    url: "/auth/logout",
    headers: {
      authorization: getHeaderToken()
    }
  })
    .then(function () {
      clearTokens();
      clearData();

      m.route.set("/login", { msg: "You've been logged out" });
    })
    .catch(function (e) {
      m.route.set("/login", { msg: `Logout failed: ${e.response.error}` });
    });
}

function clearData() {
  OverviewState.clear();
  ProjectState.clear();
  TimeRange.reset();
}

export function checkInterval() {
  if (isLoggedIn()) {
    const now = new Date();
    const then = new Date(inMemToken.tokenExpiry - 5 * 60000);

    if (now > then) {
      tryToRefresh();
    }
  }
}

export function getUsername() {
  return inMemToken.username;
}

export function getHeaderToken() {
  return `Basic ${inMemToken.token}`;
}

export function isLoggedIn() {
  return inMemToken.token !== "" && inMemToken.tokenExpiry !== "";
}

export function retryCall(err, callback) {
  if (err.code == 403) {
    tryToRefresh("The session expired", callback);
    return;
  }

  console.log(err);
  console.log("call failed with", err.response, err.code);
}
