Guest User

Untitled

a guest
Dec 4th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. /**
  2. * Written in Typescript (v3+).
  3. *
  4. * Dependencies:
  5. * - rxjs >= 6
  6. * - firebase-tools >= 6
  7. *
  8. * Have fun!
  9. *
  10. */
  11.  
  12. import { auth } from 'firebase-admin';
  13. import { ReadLine, createInterface } from 'readline';
  14. import { from, Observable, empty } from 'rxjs';
  15. import { catchError, mergeMap, map } from 'rxjs/operators';
  16.  
  17. export class FirebaseUsers {
  18.  
  19. constructor(private auth: auth.Auth, private ignoreFirstLine: boolean) {}
  20.  
  21. /**
  22. * Import all users found inside the CSV stream into Firebase Authentication.
  23. *
  24. * Note: Lines that cannot be parsed are skipped. Also users that cannot be imported
  25. * because they exist already or do not meet other criterias are skipped over as well.
  26. * Errors are written to the console.
  27. *
  28. * @param stream to parse the CSV from
  29. * @returns string observable delivering user names
  30. */
  31. create(stream: NodeJS.ReadableStream): Observable<string> {
  32. return new Observable<User>(obs => {
  33. const lineReader = createInterface(stream);
  34. let isFirstLine = true;
  35. lineReader.on('line', (line: string) => {
  36. if (isFirstLine && this.ignoreFirstLine) {
  37. isFirstLine = false;
  38. return;
  39. }
  40. const user = parseUserFromCsvLine(line);
  41. obs.next(user);
  42. });
  43. lineReader.on('close', () => obs.complete());
  44.  
  45. }).pipe(
  46. mergeMap(user => {
  47. return from(this.auth.createUser(user))
  48. .pipe(catchError(err => {
  49. console.error(`Cannot create user "${user.email}". ${err.errorInfo.message}`);
  50. return empty();
  51. }));
  52. }),
  53. map(userRecord => userRecord.email),
  54. );
  55. }
  56. }
  57.  
  58. /**
  59. * Parses either colon or semicolon separated values (4 columns) from a text line.
  60. * Windows, Linux and OSX line endings do work automatically.
  61. */
  62. export function parseUserFromCsvLine(line: string): User {
  63. let lineItems = line.split(';');
  64. if (lineItems.length < 4) {
  65. lineItems = line.split(',');
  66. if (lineItems.length < 4)
  67. throw new Error('Cannot parse user. No ; line separator found.');
  68. }
  69. if (lineItems[2].indexOf(' ') > -1)
  70. throw new Error('Cannot parse user. User name column 3 must not contain space.');
  71. return {
  72. email: `${lineItems[2]}@team-challenge.at`,
  73. password: lineItems[3]
  74. };
  75. }
  76.  
  77. /**
  78. * The user object that gets parsed from the CSV file and eventually
  79. * is imported into Firebase Authentication.
  80. */
  81. export interface User {
  82. email: string;
  83. password: string;
  84. }
Add Comment
Please, Sign In to add comment