Angular
Handle authentication with Secrecy in a Angular app
Get an authenticated Secrecy client
First initialize the Secrecy library with setup
method. if it hasn't been done yet.
Then, attempt to retrieve an authenticated client, either from the current session or local storage with getSecrecyClient
.
If no client is found, initiates a login process with the login
. Finally, on success the client SecrecyClient
is returned.
If there's an error or the login is not completed, it returns null.
secrecy.service.ts
import { Injectable } from '@angular/core';
import { getSecrecyClient, login, SecrecyClient, setup } from '@secrecy/lib';
import { environment } from '../environments/environment'; // for accessing env variables
@Injectable({
providedIn: 'root',
})
export class SecrecyService {
private client: SecrecyClient | null = null;
constructor() {
// Initialize the Secrecy library
setup();
}
// Retrieve the client from session or local storage
async initializeClient(): Promise<SecrecyClient | null> {
if (this.client !== null) {
return this.client;
}
const sessionClient = getSecrecyClient(true);
const localStorageClient = getSecrecyClient(false);
this.client = sessionClient ?? localStorageClient;
// If a client is found, return it
if (this.client) {
return this.client;
}
// Otherwise, initiate the login process
try {
this.client = await login({
appId: environment.SECRECY_APP_ID,
redirect: true,
path: window.location.pathname,
scopes: {
email: true,
},
backPath: document.referrer,
});
return this.client;
} catch (error) {
console.error('Login failed', error);
return null;
}
}
}
Get user from Secrecy client
The method secrecyClient.me
is used for fetching the user's data once the client is initialized to get the user data. It returns a SelfUser
object.
user.service.ts
import { Injectable } from '@angular/core';
import { SecrecyClient, SelfUser } from '@secrecy/lib';
@Injectable({
providedIn: 'root',
})
export class SecrecyService {
private client: SecrecyClient | null = null;
private user: SelfUser | null = null;
// Setter for the Secrecy client
setClient(client: SecrecyClient): void {
this.client = client;
}
// Getter for the client
getClient(): SecrecyClient | null {
return this.client;
}
// Fetch the current user
async getUser(): Promise<SelfUser | null> {
if (this.user !== null || this.client === null) {
return this.user;
}
try {
this.user = await this.client.me();
return this.user;
} catch (error) {
console.error('Error fetching user', error);
return null;
}
}
}