Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/asset 81 restrict access to groups #90

Merged
merged 3 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/client-asset-sg/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<asset-sg-app-bar>
<ng-template [cdkPortalOutlet]="appPortalService.appBarPortalContent$ | push"></ng-template>
</asset-sg-app-bar>
<asset-sg-menu-bar />
<asset-sg-menu-bar *ngIf="!router.url.includes('/error')"/>
<div class="router-outlet">
<router-outlet></router-outlet>
</div>
<div class="drawer-portal">
<div class="drawer-portal" *ngIf="!router.url.includes('/error')">
<ng-template [cdkPortalOutlet]="appPortalService.drawerPortalContent$ | push"></ng-template>
</div>
2 changes: 2 additions & 0 deletions apps/client-asset-sg/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AuthService } from '@asset-sg/auth';
import { AppPortalService, appSharedStateActions, setCssCustomProperties } from '@asset-sg/client-shared';

import { AppState } from './state/app-state';
import { Router } from '@angular/router';

const fullHdWidth = 1920;

Expand All @@ -24,6 +25,7 @@ export class AppComponent {
private _httpClient = inject(HttpClient);
public appPortalService = inject(AppPortalService);
private store = inject(Store<AppState>);
public readonly router: Router = inject(Router)

constructor(private readonly _authService: AuthService) {
this._httpClient
Expand Down
14 changes: 13 additions & 1 deletion apps/client-asset-sg/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,19 @@ import { AppBarComponent, MenuBarComponent, NotFoundComponent, RedirectToLangCom
import { appTranslations } from './i18n';
import { AppSharedStateEffects } from './state';
import { appSharedStateReducer } from './state/app-shared.reducer';
import { ErrorComponent } from './components/error/error.component';

registerLocaleData(locale_deCH, 'de-CH');

@NgModule({
declarations: [AppComponent, RedirectToLangComponent, NotFoundComponent, AppBarComponent, MenuBarComponent],
declarations: [
AppComponent,
RedirectToLangComponent,
NotFoundComponent,
AppBarComponent,
MenuBarComponent,
ErrorComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
Expand All @@ -67,6 +75,10 @@ registerLocaleData(locale_deCH, 'de-CH');
loadChildren: () => import('@asset-sg/asset-editor').then(m => m.AssetEditorModule),
canActivate: [editorGuard],
},
{
path: ':lang/error',
component: ErrorComponent,
},
{
matcher: assetsPageMatcher,
loadChildren: () => import('@asset-sg/asset-viewer').then(m => m.AssetViewerModule),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

<div class="error-page">
<span >{{errorMessage}}</span>
<button asset-sg-warn (click)="logout()">Logout</button>
</div>

13 changes: 13 additions & 0 deletions apps/client-asset-sg/src/app/components/error/error.component.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.error-page {
display: flex;
flex-direction: column;
gap: 20px;
position: absolute;
padding: 40px;
width: 100%;
background-color: red;
color: white;
align-items: center;
font-size: 24px;
font-weight: bolder;
}
23 changes: 23 additions & 0 deletions apps/client-asset-sg/src/app/components/error/error.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '@asset-sg/auth';

@Component({
selector: 'asset-sg-error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.scss'],
})
export class ErrorComponent {
errorMessage: string;
private readonly _authService = inject(AuthService);

constructor(private route: ActivatedRoute, private router: Router) {
const navigation = this.router.getCurrentNavigation();
console.log(navigation?.extras.state?.['errorMessage']);
this.errorMessage = navigation?.extras.state?.['errorMessage'] ?? 'An error occurred, please try again later.';
}

public logout() {
this._authService.logOut();
}
}
6 changes: 6 additions & 0 deletions apps/server-asset-sg/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@ DATABASE_URL=db/01_roles + access url postgres
GOTRUE_JWT_SECRET=selber generieren, gleich wie in development
OCR_URL=
OCR_CALLBACK_URL=
OAUTH_ISSUER=
OAUTH_CLIENT_ID=
OAUTH_SCOPE=
OAUTH_SHOW_DEBUG_INFO=
OAUTH_TOKEN_ENDPOINT=
OAUTH_AUTHORIZED_GROUPS=
19 changes: 16 additions & 3 deletions apps/server-asset-sg/src/app/jwt/jwt-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Cache } from 'cache-manager';
import { NextFunction, Request, Response } from 'express';
import * as E from 'fp-ts/Either';
import { pipe } from 'fp-ts/function';
import * as O from 'fp-ts/Option';
import * as TE from 'fp-ts/TaskEither';
import * as jwt from 'jsonwebtoken';
import { Jwt, JwtPayload } from 'jsonwebtoken';
Expand All @@ -23,11 +24,11 @@ export class JwtMiddleware implements NestMiddleware {
await this.cacheManager.set('jwk', E.isRight(jwk) ? jwk.right : [], 60 * 1000);

const token = this.extractTokenFromHeaderE(req);

// Decode token, get JWK, convert JWK to PEM, and verify token
// Decode token, check groups permission, get JWK, convert JWK to PEM, and verify token
const result = pipe(
token,
E.chain(this.decodeTokenE),
E.chain(this.isAuthorizedByGroupE),
E.chain(decoded =>
pipe(
jwk,
Expand All @@ -44,7 +45,7 @@ export class JwtMiddleware implements NestMiddleware {
(req as AuthenticatedRequest).jwtPayload = result.right.jwtPayload as JwtPayload;
next();
} else {
throw result.left;
_res.status(403).json({ error: result.left.message });
}
}

Expand Down Expand Up @@ -81,6 +82,16 @@ export class JwtMiddleware implements NestMiddleware {
);
}

private isAuthorizedByGroupE(jwt: Jwt): E.Either<Error, Jwt> {
const authorizedGroups = process.env.OAUTH_AUTHORIZED_GROUPS?.split(',');
TIL-EBP marked this conversation as resolved.
Show resolved Hide resolved
if (!authorizedGroups) {
return E.left(new Error('An internal server error occurred. Please try again.'));
}
const userGroups = (jwt.payload as JwtPayload)['cognito:groups'] as string[];
daniel-va marked this conversation as resolved.
Show resolved Hide resolved
const isUserAuthorized = userGroups.some(group => authorizedGroups.includes(group));
return isUserAuthorized ? E.right(jwt) : E.left(new Error('You are not authorized to access this resource'));
}

private getJwkTE(): TE.TaskEither<Error, JwksKey[]> {
return pipe(
TE.tryCatch(
Expand All @@ -91,6 +102,8 @@ export class JwtMiddleware implements NestMiddleware {
);
}



private getSigningKeyE(decoded: Jwt, jwks: JwksKey[]): E.Either<Error, JwksKey> {
return pipe(
jwks.find((key: any) => key.kid === decoded.header.kid),
Expand Down
17 changes: 12 additions & 5 deletions libs/auth/src/lib/services/auth.interceptor.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { Observable, throwError } from 'rxjs';
import { catchError, EMPTY, Observable, tap, throwError } from 'rxjs';
import { Router } from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private _oauthService = inject(OAuthService);
private _router: Router = inject(Router);

intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const token = sessionStorage.getItem('access_token');
Expand All @@ -22,11 +24,16 @@ export class AuthInterceptor implements HttpInterceptor {
redirect_uri: window.location.origin,
response_type: this._oauthService.responseType,
});
return throwError(new HttpErrorResponse({ status: 401, statusText: 'Unauthorized' }));
} else if (!token) {
return throwError(new HttpErrorResponse({ status: 401, statusText: 'No Token' }));
return EMPTY;
} else if (!token) {
return EMPTY;
daniel-va marked this conversation as resolved.
Show resolved Hide resolved
} else {
return next.handle(req);
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
this._router.navigate(['de/error'], { state: { errorMessage: error.error.error } });
return EMPTY;
})
);
}
}
}