Skip to content

Instantly share code, notes, and snippets.

@sp90
Created November 17, 2023 13:16
Show Gist options
  • Save sp90/8ae089c520aa4f835916b6098be3a438 to your computer and use it in GitHub Desktop.
Save sp90/8ae089c520aa4f835916b6098be3a438 to your computer and use it in GitHub Desktop.
Auth state example - angular v17
@Injectable({
providedIn: 'root',
})
export class AuthState {
private authService = inject(AuthService);
private router = inject(Router);
private tokenStorage = localStorage.get('token') ?? null;
private activeUserStorage = JSON.parse(localStorage.get('activeUser')) ?? {};
private isLoggedIn = signal<boolean>(this.tokenStorage ? true : false);
private tokenTimestamp = signal<number | null>(
this.tokenStorage ? new Date().getTime() : null
);
private token = signal<string | null>(
this.tokenStorage ? this.tokenStorage : null
);
private activeUser = signal<User | null>(this.activeUserStorage ?? null);
$activeUser = this.activeUser.asReadonly();
$tokenTimestamp = this.tokenTimestamp.asReadonly();
$token = this.token.asReadonly();
$isLoggedIn = this.isLoggedIn.asReadonly();
$isLoggedInAdmin = computed(
() => this.isLoggedIn() && this.activeUser()?.permissionGroup === 'admin'
);
login(data: LoginCredentials) {
return this.authService
.login(data)
.pipe(tap(res => this.actionsOnLogin(res)));
}
register(data: RegisterCredentials) {
return this.authService
.register(data)
.pipe(tap(res => this.actionsOnLogin(res)));
}
logout() {
this.activeUser.set(null);
localStorage.clear();
this.token.set(null);
this.isLoggedIn.set(false);
this.router.navigate(['/']);
}
actionsOnLogin(res: AuthRes) {
this.updateActiveUser(res.data);
this.setToken(res.token);
this.router.navigate(['/']);
}
setToken(token: string) {
this.isLoggedIn.set(true);
this.token.set(token);
this.tokenTimestamp.set(new Date().getTime());
localStorage.set('token', token);
}
patchActiveUser(partialUser: Partial<User>) {
const activeUser = this.activeUser() as User;
this.updateActiveUser({
...activeUser,
...partialUser,
});
}
private updateActiveUser(activeUser: User) {
localStorage.set('activeUser', JSON.stringify(activeUser));
this.activeUser.set(activeUser);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment