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);
}
}