Soy bastante novato tanto en angular como firebase / firestore y me encuentro encallado con el siguiente error.
Este fragmento de código permite realizar un registro nuevo de un usuario dentro de mi aplicación.
register() {
// console.log(this.registerCode);
this.authService.checkKey(this.registerCode).subscribe((dSnap) => {
if (dSnap.data() !== undefined){
const data = dSnap.data();
this.regDoc.used = data.used;
this.regDoc.user = data.user;
// console.log(this.regDoc.used);
if (!this.regDoc.used && this.regDoc.user === '') {
this.authService.register(this.username, this.password1).subscribe(
resData => {
console.log(resData);
// let newUsr = new User(resData.localId, this.username, resData.refreshToken, null);
let authObs: Observable<AuthResponseData>;
authObs = this.authService.login(this.username, this.password1);
authObs.subscribe(
resData => {
console.log(resData);
this.authService.createUser(this.username, resData.localId).then(uSnap => {
console.log(uSnap);
this.regDoc.user = this.username;
this.regDoc.used = true;
this.authService.updateKey(this.registerCode, this.regDoc);
this.router.navigateByUrl('tasks');
});
},
errRes => {
const code = errRes.error.error.message;
let message = 'No se ha podido iniciar sesion, vuelve a intentarlo';
if (code === 'INVALID_EMAIL'){
message = 'Email no encontrado';
} else if (code === 'INVALID_PASSWORD'){
message = 'Contraseña incorrecta';
}
alert(message);
}
);
// this.router.navigateByUrl('tasks');
},
errRes => {
const code = errRes.error.error.message;
let message = 'No se ha podido registrar, vuelve a intentarlo.';
if (code === 'EMAIL_EXISTS') {
message = 'Esta direccion de correo ya existe.';
}
alert(message);
}
)
// console.log(this.regDoc.user);
}
else {
alert('El codigo no es válido.')
}
} else {
alert('El codigo no es válido.');
}
});
}
Su funcionamiento es el siguiente:
- Primero se comprueba si existe una clave de registro dentro de la colección de
registerKeys
en firebase - Si es correcta la clave, se registra el usuario
- Se realiza un login
- Se crea un registro dentro de la colección
users
con los datos de ese usuario. - Se actualizan los datos de la clave de registro en la colección
registerKeys
Con las reglas de firestore de test (permiso total de escritura y lectura) no existe problema y todo el proceso se realiza correctamente.
El error surge cuando en la base de datos de producción, se realiza el mismo proceso, estas son las reglas:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /registerKeys/{key} {
allow read;
allow write;
}
match /users/{userId} {
allow create: if request.auth.uid == userId;
allow update: if request.auth.uid == userId;
allow read: if request.auth != null
&& (resource == null
|| request.auth.uid == userId);
}
match /users/{uid}/tasks/{task} {
allow read, write: if request.auth.uid == uid;
}
match /users/{uid}/customers/{customer} {
allow read, write: if request.auth.uid == uid;
}
}
}
Como se puede ver, solo se permite el crear y actualizar si el id
de la request
coincide con el id del documento que se quiere modificar.
Pero con esta configuración, cuando intento ejecutarlo, recibo el siguiente error:
ERROR Error: Uncaught (in promise): FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
e@http://localhost:8100/vendor.js:92229:23
430/So</u.prototype.Oi/<@http://localhost:8100/vendor.js:102005:34
T/<@http://localhost:8100/vendor.js:101953:22
tb@http://localhost:8100/vendor.js:113128:22
E@http://localhost:8100/vendor.js:113108:50
2870/Z.prototype.sa@http://localhost:8100/vendor.js:114119:34
qc@http://localhost:8100/vendor.js:113463:138
sc@http://localhost:8100/vendor.js:113356:31
2870/h.Ca@http://localhost:8100/vendor.js:113329:35
2870/h.Xa@http://localhost:8100/vendor.js:113291:83
tb@http://localhost:8100/vendor.js:113128:22
E@http://localhost:8100/vendor.js:113108:50
zd@http://localhost:8100/vendor.js:113761:19
2870/h.Ua@http://localhost:8100/vendor.js:113756:24
2870/h.za@http://localhost:8100/vendor.js:113755:78
wrapFn@http://localhost:8100/polyfills.js:10652:43
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:8100/polyfills.js:10283:35
onInvokeTask@http://localhost:8100/vendor.js:68267:33
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:8100/polyfills.js:10282:64
9140/</Zone$1</Zone</Zone.prototype.runTask@http://localhost:8100/polyfills.js:10054:51
9140/</Zone$1</ZoneTask</ZoneTask.invokeTask@http://localhost:8100/polyfills.js:10365:38
invokeTask@http://localhost:8100/polyfills.js:11505:18
globalZoneAwareCallback@http://localhost:8100/polyfills.js:11531:31
EventListener.handleEvent*customScheduleGlobal@http://localhost:8100/polyfills.js:11657:47
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.scheduleTask@http://localhost:8100/polyfills.js:10270:30
onScheduleTask@http://localhost:8100/polyfills.js:10160:84
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.scheduleTask@http://localhost:8100/polyfills.js:10263:55
9140/</Zone$1</Zone</Zone.prototype.scheduleTask@http://localhost:8100/polyfills.js:10097:47
9140/</Zone$1</Zone</Zone.prototype.scheduleEventTask@http://localhost:8100/polyfills.js:10123:29
makeAddListener/<@http://localhost:8100/polyfills.js:11814:37
patchProperty/desc.set@http://localhost:8100/polyfills.js:10713:24
2870/h.ba@http://localhost:8100/vendor.js:113723:33
lc@http://localhost:8100/vendor.js:113290:419
Md@http://localhost:8100/vendor.js:114000:361
2870/h.Aa@http://localhost:8100/vendor.js:113993:39
Fb@http://localhost:8100/vendor.js:113155:13
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:8100/polyfills.js:10249:30
onInvoke@http://localhost:8100/vendor.js:68280:33
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:8100/polyfills.js:10248:56
9140/</Zone$1</Zone</Zone.prototype.run@http://localhost:8100/polyfills.js:10009:47
scheduleResolveOrReject/<@http://localhost:8100/polyfills.js:11167:38
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:8100/polyfills.js:10283:35
onInvokeTask@http://localhost:8100/vendor.js:68267:33
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:8100/polyfills.js:10282:64
9140/</Zone$1</Zone</Zone.prototype.runTask@http://localhost:8100/polyfills.js:10054:51
drainMicroTaskQueue@http://localhost:8100/polyfills.js:10469:39
9140/</Zone$1</ZoneTask</ZoneTask.invokeTask@http://localhost:8100/polyfills.js:10369:25
invokeTask@http://localhost:8100/polyfills.js:11505:18
globalZoneAwareCallback@http://localhost:8100/polyfills.js:11531:31
EventListener.handleEvent*customScheduleGlobal@http://localhost:8100/polyfills.js:11657:47
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.scheduleTask@http://localhost:8100/polyfills.js:10270:30
onScheduleTask@http://localhost:8100/polyfills.js:10160:84
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.scheduleTask@http://localhost:8100/polyfills.js:10263:55
9140/</Zone$1</Zone</Zone.prototype.scheduleTask@http://localhost:8100/polyfills.js:10097:47
9140/</Zone$1</Zone</Zone.prototype.scheduleEventTask@http://localhost:8100/polyfills.js:10123:29
makeAddListener/<@http://localhost:8100/polyfills.js:11814:37
patchProperty/desc.set@http://localhost:8100/polyfills.js:10713:24
2870/h.ba@http://localhost:8100/vendor.js:113723:33
lc@http://localhost:8100/vendor.js:113290:377
jc@http://localhost:8100/vendor.js:113289:70
2870/h.Ba@http://localhost:8100/vendor.js:113960:94
Fb@http://localhost:8100/vendor.js:113155:13
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:8100/polyfills.js:10249:30
onInvoke@http://localhost:8100/vendor.js:68280:33
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:8100/polyfills.js:10248:56
9140/</Zone$1</Zone</Zone.prototype.run@http://localhost:8100/polyfills.js:10009:47
scheduleResolveOrReject/<@http://localhost:8100/polyfills.js:11167:38
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:8100/polyfills.js:10283:35
onInvokeTask@http://localhost:8100/vendor.js:68267:33
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:8100/polyfills.js:10282:64
9140/</Zone$1</Zone</Zone.prototype.runTask@http://localhost:8100/polyfills.js:10054:51
drainMicroTaskQueue@http://localhost:8100/polyfills.js:10469:39
9140/</Zone$1</ZoneTask</ZoneTask.invokeTask@http://localhost:8100/polyfills.js:10369:25
ZoneTask/this.invoke@http://localhost:8100/polyfills.js:10354:52
scheduleTask/data.args[0]@http://localhost:8100/polyfills.js:12912:36
setTimeout handler*scheduleTask@http://localhost:8100/polyfills.js:12914:39
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.scheduleTask@http://localhost:8100/polyfills.js:10270:30
onScheduleTask@http://localhost:8100/polyfills.js:10160:84
9140/</Zone$1</ZoneDelegate</ZoneDelegate.prototype.scheduleTask@http://localhost:8100/polyfills.js:10263:55
Servicio auth.service.ts
:
import { AngularFirestore } from '@angular/fire/firestore';
import { environment } from './../../environments/environment';
import { User } from './../models/user';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { BehaviorSubject, from} from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { Storage } from '@capacitor/storage';
export interface AuthResponseData {
kind: string;
idToken: string;
email: string;
refreshToken: string;
localId: string;
expiresIn: string;
registered?: boolean;
}
export interface RegisterKeyData {
used : boolean;
user : string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
private _user = new BehaviorSubject<User>(null);
private userDataLogged = new BehaviorSubject<any>('');
currentEvent = this.userDataLogged.asObservable();
publish(param):void{
this.userDataLogged.next(param);
}
get userIsAuthenticated() {
return this._user.asObservable().pipe(
map(user => {
if (user) {
return !!user.token;
} else {
return false;
}
})
);
}
get userEmail() {
return this._user.asObservable().pipe(
map(user => {
if (user) {
return user.email;
} else {
return null;
}
})
);
}
get userId() {
return this._user.asObservable().pipe(
map(user => {
if (user) {
return user.id;
} else {
return null;
}
})
);
}
constructor(
private http: HttpClient,
private router: Router,
private angularFirestore: AngularFirestore
) { }
autoLogin() {
return from(Storage.get({key: 'authData'}))
.pipe(map(storedData => {
if (!storedData || !storedData.value) {
return null;
}
const parsedData = JSON.parse(storedData.value) as {
userId: string;
token: string;
tokenExpirationDate: string;
email: string;
}
const expirationTime = new Date(parsedData.tokenExpirationDate);
if (expirationTime <= new Date()) {
return null;
}
const user = new User(
parsedData.userId,
parsedData.email,
parsedData.token,
expirationTime
)
return user;
}),
tap(user => {
if (user) {
this._user.next(user);
}
}),
map(user => {
this.publish({user:"logged"});
return !!user;
})
)
}
login(user: string, password: string){
return this.http.post<AuthResponseData>(
`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${environment.firebaseConfig.apiKey}`,
{email: user, password, returnSecureToken: true})
.pipe(tap(this.setUserData.bind(this)));
}
logout() {
// this._userIsAuthenticated = false;
this._user.next(null);
}
private setUserData(userData: AuthResponseData) {
const expirationTime = new Date(
new Date().getTime() + +userData.expiresIn * 1000
);
this._user.next(
new User(
userData.localId,
userData.email,
userData.idToken,
expirationTime
)
);
this.storeAuthData(
userData.localId,
userData.idToken,
expirationTime.toISOString(),
userData.email
);
this.publish({user:"logged"});
}
private storeAuthData(
userId: string,
token: string,
tokenExpirationDate: string,
email: string
){
const data = JSON.stringify({userId, token, tokenExpirationDate, email});
Storage.set({key: 'authData', value: data});
}
//Register new user
register(email: string, password: string){
return this.http.post<AuthResponseData>(
`https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=
${environment.firebaseConfig.apiKey}`,
{email: email, password: password, returnSecureToken: true}
);
}
createUser(userName: string, usrId: string){
console.log(userName, usrId);
let currentId;
this.userId.subscribe(userId=> currentId = userId );
console.log('current id: ' + currentId);
return this.angularFirestore.collection('users').doc(usrId).set(
{
user: userName,
active: true,
tier: ''
});
}
checkKey(regKey: string){
return this.angularFirestore.collection('registerKeys').doc<RegisterKeyData>(regKey).get();
}
updateKey(regKey: string, regData: RegisterKeyData){
return this.angularFirestore.collection('registerKeys').doc<RegisterKeyData>(regKey).update(regData);
}
}
this.authService.createUser(this.username, resData.localId)
authService