All files index.js

27.91% Statements 24/86
18.52% Branches 5/27
10% Functions 1/10
28.75% Lines 23/80
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 2511x 1x 1x   1x       1x                                 1x       2x 1x       1x   1x   1x 1x     1x   1x     1x   1x         1x                                                                                                                                                                                                     1x       1x 1x         1x       1x 1x                                                                                                                                                                    
import gql from 'graphql-tag';
import jwtDecode from 'jwt-decode';
import _ from 'lodash';
 
import openCenteredPopup from './popup';
 
// TODO check and warn if regenerator-runtime not installed / present
 
const discoveryQuery = gql`
{
  apDiscovery {
    ROOT_URL,
    authPath,
    services {
      name
      label
      type
      clientId
      scope
      urlStart
    }
  }
}
`;
 
let instance;
 
class ApolloPassport {
 
  constructor({ apolloClient }) {
    if (instance)
      Ithrow new Error("An ApolloPassport instance already exists");
 
    // Should we expose this via a getInstance static method?
    instance = this;
 
    this.apolloClient = apolloClient;
 
    this._subscribers = new Set();
    this.strategies = {};
 
    // Redux support.  This gets set this apolloClient.middleware().
    this.store = null;
 
    this._token = localStorage.getItem('apToken');
 
    // Set initial values
    this.setState(true);
 
    if (this._token) I{
      // constructor is a synchronous method, queue this for after.
      setTimeout(() => { this.assertToken() }, 1);
    }
 
    window.addEventListener("message", this.receiveMessage.bind(this), false);
 
    this.state = 'xxxSTATExxx';
 
    const self = this;
    apolloClient.query({ query: discoveryQuery }).then(({ errors, data }) => {
      if (errors) I{
        console.error(errors);
        throw new Error("Errors received from discovery query");
      }
 
      self.discovered = data.apDiscovery;
      console.log(self.discovered);
 
      self.discovered.services.forEach(service => {
        if (service.type === 'oauth' || service.type === 'oauth2') I{
          const url = service.urlStart +
            "?client_id=" + service.clientId +
            "&redirect_uri=" + self.discovered.ROOT_URL + self.discovered.authPath + service.name +
            "&scope=" + service.scope +
            "&state=" + self.state;
 
          console.log(url);
 
          // default width, height from meteor's oauth/oauth_browser.js
          service.open = openCenteredPopup.bind(null, url, 651, 331);
        }
      });
    });
  }
 
  assertToken() {
 
  }
 
  /* messages */
 
  receiveMessage(event) {
    if (event.origin !== window.location.origin ||
        typeof event.data !== 'string' ||
        event.data.substr(0, 15) !== 'apolloPassport ')
      Ireturn;
 
    const data = JSON.parse(event.data.substr(15));
    if (data.type === 'loginComplete') {
      this.loginComplete(data, data.key);
    } else {
      throw new Error("Unknown apolloPassport message: "
        + event.data.substr(15));
    }
  }
 
  /* modules */
 
  use(strategyName, Strategy) {
    this.strategies[strategyName] = new Strategy(this);
  }
 
  extendWith(obj) {
    _.extend(this, obj);
  }
 
  ////////////////////
  // Login / Logout //
  ////////////////////
 
  loginStart() {
 
  }
 
  loginComplete(result, dataKey) {
    if (result.errors) I{
      console.error("A server side error was thrown during the Apollo Passport GraphQL query:");
      console.error(result.errors);
      return;
      // should we still update state?
    }
 
    const queryResult = result.data[dataKey];
    const data = queryResult.token ? jwtDecode(queryResult.token) : {};
 
    localStorage.setItem('apToken', queryResult.token);
    this.setState({
      data: data,
      verified: !!queryResult.token,
      error: queryResult.error || null
    });
  }
 
  logout() {
    localStorage.removeItem('apToken');
    this.setState({ data: {}, verified: false, error: null });
  }
 
  ///////////
  // State //
  ///////////
 
  stateHash(state) {
    return JSON.stringify(state || this._state);
  }
 
  setState(nextState) {
    if (!this._state) {
      this._state = {
        data: this._token ? jwtDecode(this._token) : {},
        verified: false,
        error: null
      };
      this._stateHash = this.stateHash();
    }
 
    // Just set initial values and exit, used in constructor
    if (nextState === true)
      return;
 
    const nextStateHash = this.stateHash(nextState);
    const hasChanged = this._stateHash !== nextStateHash;
 
    if (hasChanged) I{
      this._state = nextState;
      this._stateHash = nextStateHash;
 
      // XXX todo debounce
      this.emitState();
    }
 
  }
 
  getState() {
    return this._state;
  }
 
  emitState() {
    const state = this.getState();
    this._subscribers.forEach(callback => callback(state));
  }
 
  ////////////////////////
  // Events (for state) //
  ////////////////////////
 
  subscribe(callback) {
    this._subscribers.add(callback);
  }
 
  unsubscribe(callback) {
    this._subscribers.delete(callback);
  }
 
  ////////////////////////////
  // Service login / popups //
  ////////////////////////////
 
  createServicePopup(service) {
    const url = 'xxx';
    return openCenteredPopup.bind(null, url, 651, 331);
  }
 
  ////////////////////////////
  // Optional Redux support //
  ////////////////////////////
 
  reducer() {
    var self = this;
 
    return function apolloPassportReducer(state, action) {
      if (action.type === 'APOLLO_PASSPORT_UPDATE')
        Ireturn action.state;
 
      // I guess this is anti-pattern in Redux but I like to populate the
      // initial value without a dispatch.
      return state || self.getState();
    }
  }
 
  middleware() {
    var self = this;
    return function apolloPassportMiddleware(store) {
      self.store = store;
 
      self.subscribe(state => {
        self.store.dispatch({
          type: 'APOLLO_PASSPORT_UPDATE',
          state: state
        });
      });
 
      // Don't do anything special, we just use middleware to get our store
      // with the same API as Apollo.
      return next => action => next(action);
    }
  }
}
 
export default ApolloPassport;