{"size": 1459, "ext": "js", "max_stars_repo_path": "lib/models/github-login-model.js", "max_stars_repo_name": "iPherian/github", "max_stars_repo_stars_event_min_datetime": "2019-12-13T03:10:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T03:10:05.000Z", "max_issues_repo_path": "lib/models/github-login-model.js", "max_issues_repo_name": "akonwi/github", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/models/github-login-model.js", "max_forks_repo_name": "akonwi/github", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.1449275362, "max_line_length": 74, "alphanum_fraction": 0.643591501}
import {Emitter} from 'event-kit';

import {UNAUTHENTICATED, createStrategy} from '../shared/keytar-strategy';

let instance = null;

export default class GithubLoginModel {
  static get() {
    if (!instance) {
      instance = new GithubLoginModel();
    }
    return instance;
  }

  constructor(Strategy) {
    this._Strategy = Strategy;
    this._strategy = null;
    this.emitter = new Emitter();
  }

  async getStrategy() {
    if (this._strategy) {
      return this._strategy;
    }

    if (this._Strategy) {
      this._strategy = new this._Strategy();
      return this._strategy;
    }

    this._strategy = await createStrategy();
    return this._strategy;
  }

  async getToken(account) {
    const strategy = await this.getStrategy();
    let password = await strategy.getPassword('atom-github', account);
    if (!password) {
      // User is not logged in
      password = UNAUTHENTICATED;
    }
    return password;
  }

  async setToken(account, token) {
    const strategy = await this.getStrategy();
    await strategy.replacePassword('atom-github', account, token);
    this.didUpdate();
  }

  async removeToken(account) {
    const strategy = await this.getStrategy();
    await strategy.deletePassword('atom-github', account);
    this.didUpdate();
  }

  didUpdate() {
    this.emitter.emit('did-update');
  }

  onDidUpdate(cb) {
    return this.emitter.on('did-update', cb);
  }

  destroy() {
    this.emitter.dispose();
  }
}
