All files / src/auth/scopes index.ts

100% Statements 44/44
100% Branches 14/14
100% Functions 13/13
100% Lines 42/42

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  22x 22x 22x 22x   290x 290x 44x   246x 245x   290x 312x 312x 290x 290x 290x 310x 290x   22x 29x   29x 3x     26x   38x   22x   13x 8x     5x   13x 19x   22x 24x   22x 313x   22x 290x 310x 310x 57x   310x     22x 22x   22x                                      
class AuthScopes {
  public static SCOPE_DELIMITER = ',';
 
  private compressedScopes: Set<string>;
  private expandedScopes: Set<string>;
 
  constructor(scopes: string | string[] | undefined) {
    let scopesArray: string[] = [];
    if (typeof scopes === 'string') {
      scopesArray = scopes.split(
        new RegExp(`${AuthScopes.SCOPE_DELIMITER}\\s*`),
      );
    } else if (scopes) {
      scopesArray = scopes;
    }
 
    scopesArray = scopesArray
      .map((scope) => scope.trim())
      .filter((scope) => scope.length);
 
    const impliedScopes = this.getImpliedScopes(scopesArray);
 
    const scopeSet = new Set(scopesArray);
    const impliedSet = new Set(impliedScopes);
 
    this.compressedScopes = new Set(
      [...scopeSet].filter((x) => !impliedSet.has(x)),
    );
    this.expandedScopes = new Set([...scopeSet, ...impliedSet]);
  }
 
  public has(scope: string | string[] | AuthScopes | undefined) {
    let other: AuthScopes;
 
    if (scope instanceof AuthScopes) {
      other = scope;
    } else {
      other = new AuthScopes(scope);
    }
 
    return (
      other.toArray().filter((x) => !this.expandedScopes.has(x)).length === 0
    );
  }
 
  public equals(otherScopes: string | string[] | AuthScopes | undefined) {
    let other: AuthScopes;
 
    if (otherScopes instanceof AuthScopes) {
      other = otherScopes;
    } else {
      other = new AuthScopes(otherScopes);
    }
 
    return (
      this.compressedScopes.size === other.compressedScopes.size &&
      this.toArray().filter((x) => !other.has(x)).length === 0
    );
  }
 
  public toString() {
    return this.toArray().join(AuthScopes.SCOPE_DELIMITER);
  }
 
  public toArray() {
    return [...this.compressedScopes];
  }
 
  private getImpliedScopes(scopesArray: string[]): string[] {
    return scopesArray.reduce((array: string[], current: string) => {
      const matches = current.match(/^(unauthenticated_)?write_(.*)$/);
      if (matches) {
        array.push(`${matches[1] ? matches[1] : ''}read_${matches[2]}`);
      }
 
      return array;
    }, []);
  }
}
 
export {AuthScopes};