Skip to content

Commit

Permalink
feat(iam): done iam
Browse files Browse the repository at this point in the history
  • Loading branch information
Haze272 committed Dec 17, 2024
1 parent 696e436 commit b16470b
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 27 deletions.
13 changes: 8 additions & 5 deletions backend/src/iam/authentication/authentication.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export class AuthenticationController {
) {
const { accessToken, refreshToken, user } =
await this.authService.signIn(signInDto);

response.cookie('access_token', accessToken, {
secure: true,
httpOnly: true,
Expand All @@ -58,7 +59,7 @@ export class AuthenticationController {
@Req() request: Request,
) {
console.log('- - - - /authentication/autologin');
const { user } = await this.authService.autoLogin(
const { refreshToken, user } = await this.authService.autoLogin(
request.cookies['access_token'],
);

Expand All @@ -69,7 +70,7 @@ export class AuthenticationController {
roles: user.roles,
};

return { userData };
return { refreshToken, userData };
}

@HttpCode(HttpStatus.OK)
Expand All @@ -79,8 +80,10 @@ export class AuthenticationController {
}

@HttpCode(HttpStatus.OK)
@Get('signout')
async logout(@Res({ passthrough: true }) res: Response) {
res.cookie('access_token', '', { expires: new Date() });
@Post('logout')
logout(@Res({ passthrough: true }) res: Response) {
res.clearCookie('access_token');

return;
}
}
7 changes: 4 additions & 3 deletions backend/src/iam/authentication/authentication.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ export class AuthenticationService {
if (!user) {
throw new UnauthorizedException('Пользователь не существует!');
}
return { user };

const { refreshToken } = await this.generateTokens(user);
return { refreshToken, user };
}

async generateTokens(user: User) {
Expand Down Expand Up @@ -119,7 +121,7 @@ export class AuthenticationService {
}

private async signToken<T>(userId: number, expiresIn: number, payload?: T) {
const accessToken = await this.jwtService.signAsync(
return await this.jwtService.signAsync(
{
sub: userId,
...payload,
Expand All @@ -131,6 +133,5 @@ export class AuthenticationService {
expiresIn,
},
);
return accessToken;
}
}
2 changes: 1 addition & 1 deletion frontend/src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<div>Account: {{ user?.email ?? 'N/A' }}</div>
<div>id: {{ user?.id ?? 'N/A' }}</div>
<div>Roles: {{ user?.roles ?? 'N/A' | json }}</div>
<button (click)="authService.logout()">Exit</button>
<button (click)="logout()">Exit</button>
</div>

<ul>
Expand Down
11 changes: 9 additions & 2 deletions frontend/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {RouterLink, RouterOutlet} from '@angular/router';
import {AuthService} from './features/iam/services/auth.service';
import {AsyncPipe, JsonPipe} from '@angular/common';
import {map} from 'rxjs';
import {map, Subject, takeUntil} from 'rxjs';
import {User} from './features/iam/models/user.model';

@Component({
selector: 'app-root',
Expand All @@ -14,13 +15,19 @@ import {map} from 'rxjs';
export class AppComponent {
authService = inject(AuthService);

#destroy$ = new Subject<void>()

activeUser$ = this.authService.activeUser$
.pipe(
map(user => {
return {
...user,
roles: user?.roles.map(role => role.name)
}
} as unknown as User;
})
)

logout() {
this.authService.logout().pipe(takeUntil(this.#destroy$)).subscribe();
}
}
2 changes: 0 additions & 2 deletions frontend/src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ export const appConfig: ApplicationConfig = {
});
}


console.info('App initialized!');
console.log('config:', configService.config);

return true;
}),
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/app/features/iam/guards/no-login.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export const noLoginGuard: CanActivateFn = (route, state) => {
take(1),
map((user: User | null) => {
if (user) {
router.navigate([`/`]);
console.log('[no-login.guard.ts]: person already logged!')
router.parseUrl(`/`);
return false;
}

Expand Down
53 changes: 40 additions & 13 deletions frontend/src/app/features/iam/services/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {LocalStorageService} from '../../storage/local-storage.service';
import {User} from '../models/user.model';
import {BehaviorSubject, of, switchMap, throwError} from 'rxjs';
import {BehaviorSubject, of, switchMap, tap, throwError} from 'rxjs';
import {ConfigService} from '../../config/config.service';
import {HttpClient} from '@angular/common/http';

Expand All @@ -17,17 +17,21 @@ export class AuthService {
activeUser$ = new BehaviorSubject<User | null>(null)

signIn(login: string, password: string) {
return this.http.post(
return this.http.post<{ userData: User, refreshToken: string }>(
this.configService.config.auth.url + '/authentication/sign-in',
{
email: login,
password: password
},
{
withCredentials: true
}
).pipe(
switchMap((response: any) => {
switchMap((response) => {
if (response) {
this.activeUser$.next(response.userData)
this.localStorageService.saveData('user', JSON.stringify(response.userData));
sessionStorage.setItem('refreshToken', response.refreshToken);

return of({});
} else {
Expand All @@ -47,6 +51,9 @@ export class AuthService {
username: username,
email: email,
password: password
},
{
withCredentials: true
}
).pipe(
switchMap((response: any) => {
Expand All @@ -65,23 +72,43 @@ export class AuthService {
}

autoLogin() {
const userJSON = this.localStorageService.getData('user');
return this.http.post<{ userData: User, refreshToken: string }>(
this.configService.config.auth.url + '/authentication/autologin',
{},
{
withCredentials: true
}
).pipe(
switchMap(response => {
if (response) {
this.activeUser$.next(response.userData);
this.localStorageService.saveData('user', JSON.stringify(response.userData));
sessionStorage.setItem('refreshToken', response.refreshToken);

if (userJSON) {
const user = JSON.parse(userJSON);
this.activeUser$.next(user);
return of(user);
} else {
return throwError(() => {
return new Error('Пользователь не авторизирован');
return of(response.userData);
} else {
return throwError(() => {
return new Error('Пользователь не авторизирован');
})
}
})
}
);
}

logout() {
this.localStorageService.removeData('user');

window.location.reload();
return this.http.post(
this.configService.config.auth.url + '/authentication/logout',
{},
{
withCredentials: true
}
).pipe(
tap(() => {
window.location.reload();
})
);
}

hasRole(requiredRoles: number[]): boolean {
Expand Down

0 comments on commit b16470b

Please sign in to comment.