Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: app.auth is not a function #1696

Closed
ramen-mukherjee opened this issue Apr 13, 2019 · 39 comments
Closed

TypeError: app.auth is not a function #1696

ramen-mukherjee opened this issue Apr 13, 2019 · 39 comments
Assignees

Comments

@ramen-mukherjee
Copy link

ramen-mukherjee commented Apr 13, 2019

Introduction

After the recent updates (I update regularly), I am getting following error while running the application. Project is created with Angular CLI. As of now, no build errors.

System

  • Operating System version: Windows 10 (v1803 - OS Build 17134.753) & 8 x64
  • Browser version: Chrome v74.0.3729.131 x64
  • Firebase SDK version: v6.0.2
  • Firebase Product: auth
  • Node: v12.2.0
  • NPM: v6.9.0
  • Angular: v7.2.15
  • Angular CLI: v7.3.9
  • @angular/fire: v5.1.3

Steps to reproduce:

  1. Update your existing App.
  2. Either use JIT or AOT build of Angular.
  3. Observe the below error in browser console at runtime.

Screenshot

app variable

Code

`import { User } from './../models/user.model';
import { Observable, Observer } from 'rxjs';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';

@Injectable({
providedIn: 'root'
})
export class AuthService {
user: User = {
name: '',
email: '',
photo: '',
token: {
value: '',
uid: '',
createdOn: '',
expiredOn: '',
isAuthenticated: false,
isAdmin: false
}
};

constructor(public afAuth: AngularFireAuth) { }

observable$ = Observable.create((observer) => {
try {
this.getUserDetails();
observer.next(this.user);
} catch {
this.resetUserData();
observer.error();
} finally {
observer.complete();
}
});

getAuthUser(): Observable {
return this.observable$;
}

login(): User | void {
this.afAuth.auth.setPersistence(auth.Auth.Persistence.SESSION);
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider())
.then((user) => {
if (user) {
this.getUserDetails();
}
})
.catch((error) => {
this.resetUserData();
console.error(error);
});
return this.user;
}

logout(): void {
this.afAuth.auth.signOut()
.then(() => {
this.resetUserData();
})
.catch(
response => console.error('Error Occured While Logging Out' + response)
);
}

getUserDetails(): User | void {
this.afAuth.auth.onAuthStateChanged((currentUser) => {
if (currentUser) {
this.user.name = currentUser.displayName;
this.user.email = currentUser.email;
this.user.photo = currentUser.photoURL;
this.getUserToken();
} else {
this.resetUserData();
console.error('No user present. Please login');
}
});
return this.user;
}

async getUserToken(): Promise {
await this.afAuth.auth.currentUser.getIdTokenResult()
.then((token) => {
if (token) {
this.user.token.value = token.token ? token.token : '';
this.user.token.createdOn = token.issuedAtTime ? token.issuedAtTime : '';
this.user.token.expiredOn = token.expirationTime ? token.expirationTime : '';
this.user.token.uid = token.claims ? (token.claims.user_id ? token.claims.user_id : '') : '';
this.user.token.isAuthenticated = this.isAuthenticated();
}
})
.catch(() => {
this.resetUserData();
console.error('error while getting the token');
});
}

isAuthenticated(): boolean {
if (this.user.token.createdOn && this.user.token.expiredOn) {
const expiryTime = new Date(this.user.token.expiredOn).getTime();
const creationTime = new Date(this.user.token.createdOn).getTime();
const currentTime = new Date().getTime();
if (expiryTime > creationTime && expiryTime > currentTime) {
return true;
} else {
console.error('Evicting Unauthenticated user');
this.logout();
return false;
}
} else {
console.error('Evicting Unauthenticated user');
this.logout();
return false;
}
}

resetUserData(): User | void {
this.user = {
name: '',
email: '',
photo: '',
token: {
value: '',
uid: '',
createdOn: '',
expiredOn: '',
isAuthenticated: false,
isAdmin: false
}
};
return this.user;
}
}
`

Error 1:

AppComponent.html:1 ERROR TypeError: app.auth is not a function
at auth.js:24
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.js:7929)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (polyfills.js:7688)
at NgZone.push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular (core.js:17258)
at new AngularFireAuth (auth.js:22)
at createClass (core.js:21273)
at createProviderInstance (core.js:21235)
at resolveNgModuleDep (core.js:21199)
at NgModuleRef.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef.get (core.js:21907)
at resolveDep (core.js:22278)

Error 2:

AppComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 1, nodeDef: {…}, elDef: {…}, elView: {…}}
View_AppComponent_0 @ AppComponent.html:1
proxyClass @ compiler.js:18239
push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:24139
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:15777
(anonymous) @ core.js:17870
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:17258
(anonymous) @ core.js:17870
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
onInvoke @ core.js:17299
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:390
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
(anonymous) @ zone.js:889
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:423
onInvokeTask @ core.js:17290
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:422
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:195
drainMicroTaskQueue @ zone.js:601
Promise.then (async)
scheduleMicroTask @ zone.js:584
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:413
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:238
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:258
scheduleResolveOrReject @ zone.js:879
ZoneAwarePromise.then @ zone.js:1012
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:17803
./src/main.ts @ main.ts:14
webpack_require @ runtime.js:84
0 @ polyfills.ts:81
webpack_require @ runtime.js:84
checkDeferredModules @ runtime.js:46
webpackJsonpCallback @ runtime.js:33
(anonymous) @ main.js:1

Dependency List

"dependencies": {
"@angular/animations": "^7.2.15",
"@angular/cdk": "^7.3.7",
"@angular/common": "^7.2.15",
"@angular/compiler": "^7.2.15",
"@angular/core": "^7.2.15",
"@angular/fire": "^5.1.3",
"@angular/flex-layout": "^7.0.0-beta.24",
"@angular/forms": "^7.2.15",
"@angular/http": "^7.2.15",
"@angular/material": "^7.3.7",
"@angular/platform-browser": "^7.2.15",
"@angular/platform-browser-dynamic": "^7.2.15",
"@angular/pwa": "^0.13.9",
"@angular/router": "^7.2.15",
"@angular/service-worker": "^7.2.15",
"@ngrx/core": "^1.2.0",
"@ngrx/effects": "^7.4.0",
"@ngrx/entity": "^7.4.0",
"@ngrx/router-store": "^7.4.0",
"@ngrx/schematics": "^7.4.0",
"@ngrx/store": "^7.4.0",
"@ngrx/store-devtools": "^7.4.0",
"@trademe/ng-defer-load": "^2.0.0",
"@types/angular": "^1.6.54",
"@types/angular-material": "^1.1.68",
"@types/firebase-client": "^0.1.32",
"@types/firebase-token-generator": "^2.0.28",
"classlist.js": "^1.1.20150312",
"core-js": "^2.6.5",
"firebase": "^6.0.2",
"firebase-admin": "^6.5.1",
"firebase-functions": "^2.3.1",
"firebase-tools": "^6.9.2",
"hammerjs": "^2.0.8",
"node-sass": "^4.12.0",
"rxjs": "^6.5.2",
"web-animations-js": "^2.3.1",
"zone.js": "^0.8.29"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.13.9",
"@angular/cli": "^7.3.9",
"@angular/compiler-cli": "^7.2.15",
"@angular/language-service": "^7.2.15",
"@types/jasmine": "^3.3.12",
"@types/jasminewd2": "^2.0.6",
"@types/node": "^10.14.6",
"codelyzer": "^4.5.0",
"jasmine-core": "~3.3.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^3.1.4",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^2.0.5",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"protractor": "^5.4.2",
"ts-node": "~7.0.1",
"tslint": "~5.11.0",
"tslint-angular": "^1.1.2",
"types-installer": "^1.6.3",
"typescript": "^3.2.4"
}

Thank You

Regards

@Feiyang1
Copy link
Member

Feiyang1 commented Apr 16, 2019

I'm not able to reproduce the issue, though I didn't use @angluar/fire.
Can you show me how you import and initialize firebase and auth?
Better yet, can you create a minimal repro?

@ramen-mukherjee
Copy link
Author

ramen-mukherjee commented Apr 19, 2019

Dear @Feiyang1 ,

I have updated the main issue with latest details. Along with that below is the code for my Auth Service by which I am importing firebase. This only got broke when the firebase got updated. My working code from master is available at - https://angular6-201.firebaseapp.com/dashboard

`import { User } from './../models/user.model';
import { Observable, Observer } from 'rxjs';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';

@Injectable({
providedIn: 'root'
})
export class AuthService {
user: User = {
name: '',
email: '',
photo: '',
token: {
value: '',
uid: '',
createdOn: '',
expiredOn: '',
isAuthenticated: false,
isAdmin: false
}
};

constructor(public afAuth: AngularFireAuth) { }

observable$ = Observable.create((observer) => {
try {
this.getUserDetails();
observer.next(this.user);
} catch {
this.resetUserData();
observer.error();
} finally {
observer.complete();
}
});

getAuthUser(): Observable {
return this.observable$;
}

login(): User | void {
this.afAuth.auth.setPersistence(auth.Auth.Persistence.SESSION);
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider())
.then((user) => {
if (user) {
this.getUserDetails();
}
})
.catch((error) => {
this.resetUserData();
console.error(error);
});
return this.user;
}

logout(): void {
this.afAuth.auth.signOut()
.then(() => {
this.resetUserData();
})
.catch(
response => console.error('Error Occured While Logging Out' + response)
);
}

getUserDetails(): User | void {
this.afAuth.auth.onAuthStateChanged((currentUser) => {
if (currentUser) {
this.user.name = currentUser.displayName;
this.user.email = currentUser.email;
this.user.photo = currentUser.photoURL;
this.getUserToken();
} else {
this.resetUserData();
console.error('No user present. Please login');
}
});
return this.user;
}

async getUserToken(): Promise {
await this.afAuth.auth.currentUser.getIdTokenResult()
.then((token) => {
if (token) {
this.user.token.value = token.token ? token.token : '';
this.user.token.createdOn = token.issuedAtTime ? token.issuedAtTime : '';
this.user.token.expiredOn = token.expirationTime ? token.expirationTime : '';
this.user.token.uid = token.claims ? (token.claims.user_id ? token.claims.user_id : '') : '';
this.user.token.isAuthenticated = this.isAuthenticated();
}
})
.catch(() => {
this.resetUserData();
console.error('error while getting the token');
});
}

isAuthenticated(): boolean {
if (this.user.token.createdOn && this.user.token.expiredOn) {
const expiryTime = new Date(this.user.token.expiredOn).getTime();
const creationTime = new Date(this.user.token.createdOn).getTime();
const currentTime = new Date().getTime();
if (expiryTime > creationTime && expiryTime > currentTime) {
return true;
} else {
console.error('Evicting Unauthenticated user');
this.logout();
return false;
}
} else {
console.error('Evicting Unauthenticated user');
this.logout();
return false;
}
}

resetUserData(): User | void {
this.user = {
name: '',
email: '',
photo: '',
token: {
value: '',
uid: '',
createdOn: '',
expiredOn: '',
isAuthenticated: false,
isAdmin: false
}
};
return this.user;
}
}
`

@hsubox76
Copy link
Contributor

I created a fresh angularfire project with auth using the steps here: https://github.com/angular/angularfire2/blob/master/docs/auth/getting-started.md

It seemed to work, I wasn't able to reproduce the error.

I went to the url you provided above, which seems to be your deployed project, and it seems to be working. Did you get this working since you last posted, or is that an older version that's deployed?

If it's still not working, can you share the code for initializing your app, such as:

    AngularFireModule.initializeApp(environment.firebase)

Thanks!

@hsubox76 hsubox76 self-assigned this Apr 26, 2019
@ramen-mukherjee
Copy link
Author

Dear @hsubox76 ,

  1. I updated Node and all packages as well. Issue is still reproducible.
  2. The link which I have provided is from my master branch which holds the old code where authentication is working.
  3. There is no code (logic) change from my side. All I did is to upgrade everything, because that was the NFR for the work.
  4. This is the code I used to initialize my app-
    AngularFireModule.initializeApp(environment.firebase, 'angular6-201'),

Thank You
Regards

@hsubox76
Copy link
Contributor

hsubox76 commented May 7, 2019

Unfortunately, I still can't seem to reproduce it. Can you create a bare-bones repo that reproduces this error? I've made a minimal AngularFire project repo here (that does not show the error): https://github.com/hsubox76/angularfire-test

It is a fully functional repo except for your Firebase config (API key, etc.) needing to be pasted into environment.ts.

Can you either clone that repo and cause it to fail, or strip down your own code (remove anything proprietary or private) to create a similar minimal repo that fails? This would be the best way for us to narrow down what's wrong. And if you're able to make that, then can you give us a link to the source code (Github repo)? The link above (https://angular6-201.firebaseapp.com/dashboard) seems to be to a deployment, not code.

@agustin107
Copy link

I've fixed with this comment

#752 (comment)

@curtgrimes
Copy link

curtgrimes commented May 13, 2019

I was previously using:

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";

and needed to change this to:

import firebase from "@firebase/app";
import "@firebase/auth";
import "@firebase/firestore";

This actually didn't fix my issue. I'm still having the same issue as you where auth is not a member of firebase. Downgrading to 5.11.1 at the moment solves it for me until I can look into it further.

@ramen-mukherjee
Copy link
Author

ramen-mukherjee commented May 14, 2019

Dear @curtgrimes,

Thank You for your effort to look into my issue. Unfortunately it is still unresolved.

#1 for "import firebase from "firebase/app";" I am getting following error-
ERROR in src/app/services/auth.service.ts(44,46): error TS2339: Property 'Auth' does not exist on type 'FirebaseNamespace'.
src/app/services/auth.service.ts(45,51): error TS2339: Property 'GoogleAuthProvider' does not exist on type 'FirebaseNamespace'.

#2 If I try "import firebase from "@firebase/auth";" I am getting the following error - "Module '"../../../../../../PROJECTS/Angular6_201/any-time-library/node_modules/@firebase/auth"' has no exported member 'firebase'.ts(2305)"

Also whenever I am installing firebase or running "npm update" using "npm i firebase" (as per npmjs) after deleting folder in node_modules, it is loading tons of .c and .cc files and trying to build which it is eventually failing. I have node gyp, python 2.7 and MS VS Build Tool 2017 installed.

Maybe total noob in this, but this is not something proper. never happened earlier in this way, i keep updating my app because that is one of the requirement from app owner.

I seriously need help because my app is now messed up.

Thank You

Regards
Ramen

@curtgrimes
Copy link

This actually didn't fix my issue. I'm still having the same issue as you where auth is not a member of firebase. Downgrading to 5.11.1 at the moment solves it for me until I can look into it further.

@ramen-mukherjee
Copy link
Author

Dear @curtgrimes,

I was using v5.11.1 and problem started from that time.

Thank You
Regards

@ramen-mukherjee
Copy link
Author

Updated to Firebase SDK version: v6.0.2 but the issue is still there.

@curtgrimes
Copy link

It looks like this issue is caused by the firebase-admin package being installed in the same project using the firebase JS SDK.

@ramen-mukherjee
Copy link
Author

Dear @curtgrimes ,

Tried by removing that also. Not working :(

Thank You
Regards

@hsubox76
Copy link
Contributor

hsubox76 commented Jun 3, 2019

I'm afraid it's too difficult to pinpoint the exact problem without getting a look at the rest of your setup. Can you please provide a minimal repro as described in the above comment? Once you've created it, you can upload it to a public Github repo and I'll clone it and try to debug.

It should look something like the example repo I linked above - complete but minimal, except that it results in the errors you're seeing.

@buzzware
Copy link

buzzware commented Jun 11, 2019

I'm having this problem too, in node. I've been using both the admin and client sdks together, for example to create a custom token and then login with it, especially for testing.
Since updating to 6.1.1 from 5.5.9, auth is no longer on the firebase sdk namespace.
See clientForUser() here https://github.com/buzzware/firebase-extra/blob/master/src/FirebaseExtraAdmin.js

@buzzware
Copy link

@Feiyang1 thanks for your detailed response, and it is working for me with firebase 5.11.1 like you say.
Long term, I think firebase-admin should offer a complete superset of firebase, if it is not feasible to maintain the ability to install both. If that is not feasible, then please provide solutions for firebase-admin to

  1. login as a user with the same limited permissions, for testing security rules
  2. user.getIdToken()
  3. other things missing from firebase-admin I'm not aware of.

@Feiyang1
Copy link
Member

Feiyang1 commented Jun 13, 2019

@inorganik in your repo https://github.com/inorganik/angularfire-test, firebase packages are excluded in the bundle since you made firebase packages external dependencies in the webpack config. You need to list firebase as a dependency in the package.json under functions folder, so node can find it at runtime.

@inorganik
Copy link

Installing firebase in my functions folder at v 5.11.1 fixed this issue for me. Thanks @Feiyang1 !

It seems clear now the issue is understanding which versions of firebase are compatible with each other. Having major versions synced up would be nice. At the very least can we have a REAME that shows compatible versions of everything? It would save us a lot of pain and suffering.

@Feiyang1
Copy link
Member

Closing since it seems the issue has been resolved.

@buzzware
Copy link

@Feiyang1 I don't think it is resolved. The fact that you need to select particular version combinations of the two will cause headaches for new users, and closing this suggests Google is ok with it not being reliable to use the firebase package in node (which there are good reasons for doing). If I build my product based on this, will I be at risk in the future of not being able to upgrade, because there is no pair of versions that works? e.g. currently, I'm stuck on 5.x

@ramen-mukherjee
Copy link
Author

Dear @Feiyang1 ,

Closing without a proper/stable solution is unfair. Don't you think?

Thank You
Regards

@Feiyang1
Copy link
Member

@buzzware @ramen-mukherjee
Any version of firebase and firebase-admin will work together after [email protected] and [email protected].

@Mcebrera
Copy link

Mcebrera commented Aug 7, 2019

@Feiyang1 your above comment doesn't seem to work for me.

@donaldaverill
Copy link

I have the following package versions and the functions emulator work as expected:

"firebase": "6.3.5",
"firebase-admin": "8.3.0",
"firebase-functions": "3.2.0",
"firebase-tools": "7.2.3",

If I update the firebase package to 6.4.0 and run the emulator, it reports the following error:
FirebaseError: Firebase: Firebase service named 'database' already registered (app/duplicate-service).

@Feiyang1
Copy link
Member

@donaldaverill please take a look at the conversation in #2054

@donaldaverill
Copy link

Thank you @Feiyang1. Yes, I've read through that thread a few times. I'm not importing or requiring anything directly from the firebase package. This is happening in firebase functions (and emulator) but only with firebase 6.4.0. Version 6.3.5 works fine. Also, I'm initializing the app by

import * as admin from 'firebase-admin'
admin.initializeApp()

Does that seem okay?

@Feiyang1
Copy link
Member

That looks fine. I don't see any change in 6.4.0 that could cause the issue.
If you don't use firebase package in functions, can you remove it from package.json and try again?

@donaldaverill
Copy link

@Feiyang1 As it turns out, I don't need the firebase package for the firebase functions, but I have other apps in my repo that require firebase. I think I may be running into this issue: #1696 (comment). firebase 6.3.5 seems to be a valid combo with the other firebase packages (listed above) but not 6.4.0 for whatever reason. Note that I always remove package-lock.json and node_modules folder before running npm install again.

@Feiyang1
Copy link
Member

#1696 (comment) describes a different issue than yours.

The issue is that firebase-admin and firebase-functions both imports @firebase/database (firebase-functions depends on firebase-admin). It's not a problem if firebase is not present, but since it is, there are 2 attempts to register database with firebase, thus the error.

Do you have separate package.json for the main app and functions? something like:

- your-app
   - functions
       - package.json
   - src
   - package.json

then you can remove firebase from functions's package.json.

@Feiyang1
Copy link
Member

And we are removing this error (app/duplicate-service) in the next version of the SDK, so duplicate service registering will just be ignored.

@donaldaverill
Copy link

Thanks again @Feiyang1

#1696 (comment) describes a different issue than yours.

The issue is that firebase-admin and firebase-functions both imports @firebase/database (firebase-functions depends on firebase-admin). It's not a problem if firebase is not present, but since it is, there are 2 attempts to register database with firebase, thus the error.

Ok, makes sense.

Do you have separate package.json for the main app and functions? something like:

- your-app
   - functions
       - package.json
   - src
   - package.json

then you can remove firebase from functions's package.json.

I have one package.json. Additionally, one of my functions is an Angular Universal app that includes AngularFire. This function/universal app has broken as well due to the (app/duplicate-service) issue.

@Feiyang1
Copy link
Member

I see. I still don't understand why 6.3.5 works though. Anyway, a new version will come out later today that won't cause this issue anymore.

@donaldaverill
Copy link

@Feiyang1 firebase 6.4.1 has fixed my issues for the functions build, emulator, and Angular Universal app. 👍👍

@firebase firebase locked and limited conversation to collaborators Oct 12, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

10 participants