Reputation: 1
import { Injectable } from '@angular/core';
import { Application, feathers } from '@feathersjs/feathers';
import socketioClient from '@feathersjs/socketio-client';
import * as io from 'socket.io-client';
import { Router } from '@angular/router';
import * as CryptoJS from 'crypto-js';
import { environment } from 'src/environments/environment.prod';
@Injectable({
providedIn: 'root',
})
export class FeathersService {
app!: Application;
socket;
constructor(private router: Router) {
this.socket = io('http://localhost:3030');
this.app = feathers()
.configure(socketioClient(this.socket))
.configure(feathers);
this.socket.on('connect', () => console.log('Server connected'));
this.socket.on('connect_error', (err: any) => {});
this.reauthenticate();
}
on(event: string, serviceName: string, callback: (data: any) => void) {
this.app.service(serviceName).on(event, callback);
}
async reauthenticate() {
try {
const accessToken = await this.decryptToken();
if (!accessToken) {
console.log('No token found.');
sessionStorage.removeItem('token');
localStorage.removeItem('token');
return;
}
await this.app.service('authentication').create({
strategy: 'jwt',
accessToken: accessToken,
});
} catch (error) {
console.log(error);
}
}
decryptToken(): string {
return CryptoJS.AES.decrypt(
localStorage.getItem('token') || sessionStorage.getItem('token') || '',
environment.secretKey
).toString(CryptoJS.enc.Utf8);
}
}
async logIn(loginCredentials: any): Promise<any> {
try {
// const login = await this.feathers.app.authenticate({
// strategy: 'local',
// ...loginCredentials,
// });
const login = await this.feathers.app
.service('authentication')
.create({ strategy: 'local', ...loginCredentials });
console.log(login);
if (login['accessToken']) {
if (loginCredentials.keepmeLogin) {
localStorage.setItem(
'token',
CryptoJS.AES.encrypt(
login['accessToken'],
environment.secretKey
).toString()
);
} else {
sessionStorage.setItem(
'token',
CryptoJS.AES.encrypt(
login['accessToken'],
environment.secretKey
).toString()
);
}
}
I dont want to use feathers/authentication because i will store the token in local or session storage. So i want to manually handle the token on initiall login it fetch the data from the feathers server but when i refresh it throws error like not authentication. so i try to reauthticate the user but still it was fail.
Upvotes: 0
Views: 11