Skip to content

Commit

Permalink
Added the user preferences page [#723]
Browse files Browse the repository at this point in the history
 * Added a guard that checks if the user is logged in.
  • Loading branch information
mcpierce committed Apr 24, 2021
1 parent fd590f1 commit 630f819
Show file tree
Hide file tree
Showing 26 changed files with 598 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,25 @@ <h3 *ngIf="!!user" matSubheader>
<h3 *ngIf="!!user" matSubheader>
{{ "navigation.heading.account" | translate }}
</h3>
<mat-nav-list *ngIf="!!user">
<a
mat-list-item
routerLink="/account/preferences"
routerLinkActive="active"
>
{{ "navigation.option.user-preferences" | translate }}
</a>
</mat-nav-list>

<h3 *ngIf="isAdmin" matSubheader>
{{ "navigation.heading.admin" | translate }}
</h3>
<a *ngIf="isAdmin" mat-list-item routerLink="/admin/pages/blocked">
<a
*ngIf="isAdmin"
mat-list-item
routerLink="/admin/pages/blocked"
routerLinkActive="active"
>
{{ "navigation.option.blocked-pages" | translate }}
</a>
<a
Expand Down
135 changes: 135 additions & 0 deletions comixed-web/src/app/user/guards/user.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* ComiXed - A digital comic book library management application.
* Copyright (C) 2021, The ComiXed Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

import { TestBed } from '@angular/core/testing';

import { UserGuard } from './user.guard';
import {
initialState as initialUserState,
USER_FEATURE_KEY
} from '@app/user/reducers/user.reducer';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { LoggerModule } from '@angular-ru/logger';
import { Observable } from 'rxjs';
import { USER_ADMIN } from '@app/user/user.fixtures';

describe('UserGuard', () => {
const USER = USER_ADMIN;
const initialState = {
[USER_FEATURE_KEY]: initialUserState
};

let guard: UserGuard;
let store: MockStore<any>;
let router: Router;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([{ path: '*', redirectTo: '' }]),
LoggerModule.forRoot()
],
providers: [provideMockStore({ initialState })]
});
guard = TestBed.inject(UserGuard);
store = TestBed.inject(MockStore);
router = TestBed.inject(Router);
spyOn(router, 'navigateByUrl');
});

it('should be created', () => {
expect(guard).toBeTruthy();
});

describe('when the authentication system is not initialized', () => {
beforeEach(() => {
store.setState({
...initialState,
[USER_FEATURE_KEY]: {
...initialUserState,
initializing: true,
authenticated: false,
user: null
}
});
});

it('defers access', () => {
(guard.canActivate(
null,
null
) as Observable<boolean>).subscribe(response =>
expect(response).toBeTrue()
);
});

afterEach(() => {
store.setState({
...initialState,
[USER_FEATURE_KEY]: {
...initialUserState,
initializing: false,
authenticated: true,
user: USER_ADMIN
}
});
});
});

describe('when the user is not authenticated', () => {
beforeEach(() => {
store.setState({
...initialState,
[USER_FEATURE_KEY]: {
...initialUserState,
initializing: false,
authenticated: false,
user: null
}
});
});

it('redirects the browser to the login form', () => {
expect(router.navigateByUrl).toHaveBeenCalledWith('/login');
});

it('denies access', () => {
expect(guard.canActivate(null, null)).toBeFalse();
});
});

describe('when the user is authenticated', () => {
beforeEach(() => {
store.setState({
...initialState,
[USER_FEATURE_KEY]: {
...initialUserState,
initializing: false,
authenticated: true,
user: USER
}
});
});

it('allows access', () => {
expect(guard.canActivate(null, null)).toBeTrue();
});
});
});
70 changes: 70 additions & 0 deletions comixed-web/src/app/user/guards/user.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* ComiXed - A digital comic book library management application.
* Copyright (C) 2021, The ComiXed Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/

import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot
} from '@angular/router';
import { Observable, Subject } from 'rxjs';
import { LoggerService } from '@angular-ru/logger';
import { Store } from '@ngrx/store';
import { selectUserState } from '@app/user/selectors/user.selectors';
import { filter } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class UserGuard implements CanActivate {
initialized = false;
authenticated = false;
hasUser = false;
delayed$ = new Subject<boolean>();

constructor(
private logger: LoggerService,
private store: Store<any>,
private router: Router
) {
this.store
.select(selectUserState)
.pipe(filter(state => !!state && !state.initializing))
.subscribe(state => {
this.initialized = true;
this.logger.debug('Guard: user state updated:', state);
this.authenticated = state.authenticated;
this.delayed$.next(this.authenticated);
if (!this.authenticated) {
this.router.navigateByUrl('/login');
}
});
}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | boolean {
if (this.initialized) {
return this.authenticated;
} else {
return this.delayed$.asObservable();
}
}
}
3 changes: 1 addition & 2 deletions comixed-web/src/app/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ import {

export { getUserPreference } from '@app/user/user.functions';
export { AdminGuard } from '@app/user/guards/admin.guard';
export { Preference } from '@app/user/models/preference';
export { ReaderGuard } from '@app/user/guards/reader.guard';
export { User } from '@app/user/models/user';
export * from './user.models';

interface RouterStateUrl {
url: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
*/

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
import { LoginPageComponent } from './login-page.component';
import { LoggerModule } from '@angular-ru/logger';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
Expand All @@ -37,24 +37,24 @@ import { TitleService } from '@app/core';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

describe('LoginComponent', () => {
describe('LoginPageComponent', () => {
const USER = USER_READER;
const PASSWORD = 'this!is!my!password';

const initialState = {
[USER_FEATURE_KEY]: initialUserState
};

let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let component: LoginPageComponent;
let fixture: ComponentFixture<LoginPageComponent>;
let store: MockStore<any>;
let translateService: TranslateService;
let titleService: TitleService;
let router: Router;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent],
declarations: [LoginPageComponent],
imports: [
NoopAnimationsModule,
RouterTestingModule.withRoutes([{ path: '**', redirectTo: '' }]),
Expand All @@ -70,7 +70,7 @@ describe('LoginComponent', () => {
providers: [provideMockStore({ initialState })]
}).compileComponents();

fixture = TestBed.createComponent(LoginComponent);
fixture = TestBed.createComponent(LoginPageComponent);
component = fixture.componentInstance;
store = TestBed.inject(MockStore);
spyOn(store, 'dispatch');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ import { Router } from '@angular/router';

@Component({
selector: 'cx-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
export class LoginPageComponent implements OnInit, OnDestroy {
loginForm: FormGroup;
userSubscription: Subscription;
langChangeSubscription: Subscription;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="name">
<mat-header-cell mat-sort-header *matHeaderCellDef>
{{ "user.user-preferences.label.preference-name" | translate }}
</mat-header-cell>
<mat-cell *matCellDef="let entry">
<span class="cx-width-100 cx-text-nowrap">{{ entry.name }}</span>
</mat-cell>
</ng-container>

<ng-container matColumnDef="value">
<mat-header-cell mat-sort-header *matHeaderCellDef>
{{ "user.user-preferences.label.preference-value" | translate }}
</mat-header-cell>
<mat-cell *matCellDef="let entry">
<span class="cx-width-100 cx-text-nowrap">{{ entry.value }}</span>
</mat-cell>
</ng-container>

<ng-container matColumnDef="actions">
<mat-header-cell mat-sort-header *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let entry">
<button
id="'delete-preference-value-' + entry.name + '-button'"
mat-icon-button
color="warn"
[matTooltip]="
'user.user-preferences.tooltip.delete-preference' | translate
"
(click)="onDeletePreference(entry.name)"
>
<mat-icon>delete</mat-icon>
</button>
</mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
@import 'styles';

.mat-column-name {
width: $cx-column-large;
max-width: $cx-column-large;
}

.mat-column-value {
}

.mat-column-actions {
width: $cx-column-small;
max-width: $cx-column-small;
}

0 comments on commit 630f819

Please sign in to comment.