add logic
This commit is contained in:
@@ -3,7 +3,7 @@ import type { AuthSession } from './auth.models';
|
||||
const SESSION_KEY = 'gorodar.session';
|
||||
|
||||
export function readAuthSession(): AuthSession | null {
|
||||
const raw = sessionStorage.getItem(SESSION_KEY);
|
||||
const raw = localStorage.getItem(SESSION_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return null;
|
||||
@@ -13,7 +13,7 @@ export function readAuthSession(): AuthSession | null {
|
||||
const expired = !!session && typeof session.expiresAt === 'number' && session.expiresAt <= Date.now();
|
||||
|
||||
if (!session || !isEmail(session.email) || !session.accessToken || expired) {
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
localStorage.removeItem(SESSION_KEY);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ export function readAuthSession(): AuthSession | null {
|
||||
}
|
||||
|
||||
export function writeAuthSession(session: AuthSession): void {
|
||||
sessionStorage.setItem(SESSION_KEY, JSON.stringify(session));
|
||||
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
|
||||
}
|
||||
|
||||
export function clearAuthSession(): void {
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
localStorage.removeItem(SESSION_KEY);
|
||||
}
|
||||
|
||||
function parseSession(raw: string): AuthSession | null {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { HttpInterceptorFn } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Store } from '@ngrx/store';
|
||||
|
||||
import { selectAuth } from '../state/gorodar.selectors';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
class AccessTokenReader {
|
||||
private readonly auth = inject(Store).selectSignal(selectAuth);
|
||||
|
||||
token(): string | null {
|
||||
return this.auth().accessToken;
|
||||
}
|
||||
}
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
if (req.url.includes('/oauth2/')) {
|
||||
return next(req);
|
||||
}
|
||||
|
||||
const token = inject(AccessTokenReader).token();
|
||||
|
||||
if (!token) {
|
||||
return next(req);
|
||||
}
|
||||
|
||||
return next(
|
||||
req.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` },
|
||||
}),
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user