All files / src auth.ts

100% Statements 90/90
100% Branches 59/59
100% Functions 16/16
100% Lines 72/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  4x     4x                                         4x                       13x 13x 13x 13x   13x 13x         4x 17x         4x 12x         4x 15x   14x           14x         4x 19x           4x 4x 3x 1x 1x     2x 1x 1x             4x   17x   4x 4x     4x   3x 2x   1x           4x 15x           4x 7x 6x   5x 4x   3x 3x   2x         1x           4x 10x 9x   8x     8x   7x 7x       6x   4x         2x 2x   2x     4x         4x 10x 2x             4x 33x   33x             4x 5x 5x 4x   4x   3x         4x  
import { IncomingMessage } from 'http';
import Cookies, { CookieAttributes } from 'js-cookie';
import { FetchConnector } from './connectors/utils';
 
const AT_COOKIE = 'a_t';
 
export type CookieOptions =
  | CookieAttributes
  | ((accessToken?: string) => CookieAttributes);
 
export type GetTokens = (
  req: IncomingMessage
) => { refreshToken?: string; accessToken?: string } | void;
 
export type Decode = (accessToken: string) => object | null | void;
 
export interface AuthClientOptions {
  cookie?: string;
  cookieOptions?: CookieOptions;
  decode: Decode;
  fetchConnector?: FetchConnector;
  refreshTokenCookie?: string;
  getTokens?: GetTokens;
}
 
export class AuthClient {
  public cookie: string;
  public cookieOptions?: CookieOptions;
  public decode: Decode;
  public fetch?: FetchConnector;
 
  private refreshTokenCookie?: string;
  private getTokens: GetTokens;
  private clientATFetch?: Promise<string>;
 
  constructor(options: AuthClientOptions) {
    // Public
    this.cookie = options.cookie || AT_COOKIE;
    this.cookieOptions = options.cookieOptions;
    this.decode = options.decode;
    this.fetch = options.fetchConnector;
    // Private
    this.refreshTokenCookie = options.refreshTokenCookie;
    this.getTokens = options.getTokens || this._getTokens;
  }
  /**
   * Returns the accessToken from cookies
   */
  public getAccessToken() {
    return Cookies.get(this.cookie);
  }
  /**
   * Decodes an accessToken and returns his payload or null
   */
  public decodeAccessToken(accessToken: string) {
    return (accessToken && this.decode(accessToken)) || null;
  }
  /**
   * Sets an accessToken as a cookie and returns the accessToken
   */
  public setAccessToken(accessToken: string) {
    if (!accessToken) return;
 
    Cookies.set(this.cookie, accessToken, {
      expires: 365,
      secure: location.protocol === 'https:',
      ...this.getCookieOptions(accessToken)
    });
 
    return accessToken;
  }
  /**
   * Removes the accessToken from cookies
   */
  public removeAccessToken() {
    Cookies.remove(this.cookie, this.getCookieOptions());
  }
  /**
   * Logouts the user, this means remove both accessToken and refreshToken from
   * cookies
   */
  public async logout() {
    if (typeof window === 'undefined') return;
    if (!this.fetch) {
      this.removeAccessToken();
      return { done: true };
    }
 
    return this.fetch.logout({ credentials: 'same-origin' }).then(json => {
      this.removeAccessToken();
      return json;
    });
  }
  /**
   * Returns a new accessToken
   * @param req Sending a Request means the token will be created during SSR
   */
  public async fetchAccessToken(req?: IncomingMessage) {
    try {
      return await (req ? this.fetchServerToken(req) : this.fetchClientToken());
    } catch (err) {
      const isFetchError = err.name === 'FetchError';
      const isNetworkError = err.name === 'NetworkError';
 
      // Don't ignore unknown errors
      if (!isFetchError && !isNetworkError) throw err;
      // Ignore errors in the server
      if (req) return;
      if (!isFetchError) throw err;
      // Remove the accessToken that caused a FetchError
      this.removeAccessToken();
    }
  }
  /**
   * Returns true if a refreshToken cookie is defined
   */
  public withRefreshToken() {
    return !!this.refreshTokenCookie;
  }
  /**
   * Returns the accessToken on SSR from cookies, if no token exists or its
   * invalid then it will fetch a new accessToken
   */
  private async fetchServerToken(req: IncomingMessage) {
    if (!this.fetch) return;
    if (!this.withRefreshToken()) return;
 
    const tokens = this.getTokens(req);
    if (!tokens || !tokens.refreshToken) return;
 
    const accessToken = this.verifyAccessToken(tokens.accessToken || '');
    if (accessToken) return accessToken;
 
    const data = await this.fetch.createAccessToken({
      // This may have side effects
      headers: req.headers as { [key: string]: string }
    });
 
    return data.accessToken;
  }
  /**
   * Returns the accessToken from cookies, if no token exists or its
   * invalid then it will fetch a new accessToken
   */
  private async fetchClientToken() {
    if (!this.fetch) return;
    if (!this.withRefreshToken()) return;
 
    const _accessToken = this.getAccessToken();
    // If the browser doesn't have an accessToken in cookies then don't try to
    // create a new one
    if (!_accessToken) return;
 
    const accessToken = this.verifyAccessToken(_accessToken);
    if (accessToken) return accessToken;
    // In this case the accessToken in cookies is invalid and we should create
    // a new one, the promise is reused for the case of when the method is
    // called multiple times
    if (this.clientATFetch) return this.clientATFetch;
 
    this.clientATFetch = this.fetch
      .createAccessToken({
        credentials: 'same-origin'
      })
      .then(data => {
        this.clientATFetch = undefined;
        this.setAccessToken(data.accessToken);
 
        return data.accessToken;
      });
 
    return this.clientATFetch;
  }
  /**
   * Verifies and returns an accessToken if it's still valid
   */
  private verifyAccessToken(accessToken: string) {
    if (accessToken && this.decodeAccessToken(accessToken)) {
      return accessToken;
    }
  }
  /**
   * Returns the cookie options that will be used to set an accessToken,
   * accessToken will be undefined when removing a cookie
   */
  private getCookieOptions(accessToken?: string) {
    const { cookieOptions } = this;
 
    return cookieOptions && typeof cookieOptions === 'function'
      ? cookieOptions(accessToken)
      : cookieOptions;
  }
  /**
   * Gets the tokens from a Request
   */
  private _getTokens(req: IncomingMessage) {
    const parseCookie = require('cookie').parse;
    const { cookie } = req.headers;
    const cookies = cookie && parseCookie(cookie);
 
    if (!cookies) return;
 
    return {
      refreshToken: this.refreshTokenCookie && cookies[this.refreshTokenCookie],
      accessToken: cookies[this.cookie]
    };
  }
}