refactor: get appropriate provider via auth helper

This commit is contained in:
Jovan Krunić
2022-02-14 11:12:02 +01:00
parent a5e5a5b407
commit eaf9da3c84
21 changed files with 141 additions and 182 deletions

View File

@@ -29,6 +29,7 @@ import {NGXLogger} from 'ngx-logger';
import {RouterTestingModule} from '@angular/router/testing';
import {ScheduleSyncService} from './modules/background/schedule/schedule-sync.service';
import {sampleAuthConfiguration} from './_helpers/data/sample-configuration';
import {StorageProvider} from './modules/storage/storage.provider';
describe('AppComponent', () => {
let platformReadySpy: any;
@@ -40,6 +41,7 @@ describe('AppComponent', () => {
let ngxLogger: jasmine.SpyObj<NGXLogger>;
let scheduleSyncServiceSpy: jasmine.SpyObj<ScheduleSyncService>;
let platformIsSpy;
let storageProvider: jasmine.SpyObj<StorageProvider>;
beforeEach(
waitForAsync(() => {
@@ -75,6 +77,12 @@ describe('AppComponent', () => {
return sampleAuthConfiguration;
});
ngxLogger = jasmine.createSpyObj('NGXLogger', ['log', 'error', 'warn']);
storageProvider = jasmine.createSpyObj('StorageProvider', [
'init',
'get',
'has',
'put',
]);
TestBed.configureTestingModule({
imports: [
@@ -91,6 +99,7 @@ describe('AppComponent', () => {
{provide: SettingsProvider, useValue: settingsProvider},
{provide: ConfigProvider, useValue: configProvider},
{provide: NGXLogger, useValue: ngxLogger},
{provide: StorageProvider, useValue: storageProvider},
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();

View File

@@ -18,8 +18,6 @@ import {App, URLOpenListenerEvent} from '@capacitor/app';
import {SplashScreen} from '@capacitor/splash-screen';
import {Platform, ToastController} from '@ionic/angular';
import {SettingsProvider} from './modules/settings/settings.provider';
import {PAIAAuthService} from './modules/auth/paia/paia-auth.service';
import {DefaultAuthService} from './modules/auth/default-auth.service';
import {AuthHelperService} from './modules/auth/auth-helper.service';
import {ScheduleSyncService} from './modules/background/schedule/schedule-sync.service';
import {environment} from '../environments/environment';
@@ -52,9 +50,7 @@ export class AppComponent implements AfterContentInit {
* @param settingsProvider TODO
* @param router The angular router
* @param zone The angular zone
* @param defaultAuth Auth Service
* @param paiaAuth Auth Service
* @param authHelperService Helper service for OAuth providers
* @param authHelper Helper service for OAuth providers
* @param toastController Toast controller
* @param scheduleSync TODO
*/
@@ -63,9 +59,7 @@ export class AppComponent implements AfterContentInit {
private readonly settingsProvider: SettingsProvider,
private readonly router: Router,
private readonly zone: NgZone,
private readonly defaultAuth: DefaultAuthService,
private readonly paiaAuth: PAIAAuthService,
private readonly authHelperService: AuthHelperService,
private readonly authHelper: AuthHelperService,
private readonly toastController: ToastController,
private readonly scheduleSync: ScheduleSyncService,
) {
@@ -92,8 +86,6 @@ export class AppComponent implements AfterContentInit {
});
this.platform.ready().then(async () => {
await this.authInit();
await this.defaultAuth.init();
await this.paiaAuth.init();
await SplashScreen.hide();
// set order of categories in settings
@@ -107,16 +99,18 @@ export class AppComponent implements AfterContentInit {
}
private async authInit() {
await this.defaultAuth.init();
await this.paiaAuth.init();
this.defaultAuth.events$.subscribe(action =>
this.showMessage(
this.authHelperService.getAuthMessage('default', action),
),
);
this.paiaAuth.events$.subscribe(action =>
this.showMessage(this.authHelperService.getAuthMessage('paia', action)),
);
await this.authHelper.getProvider('default').init();
await this.authHelper.getProvider('paia').init();
this.authHelper
.getProvider('default')
.events$.subscribe(action =>
this.showMessage(this.authHelper.getAuthMessage('default', action)),
);
this.authHelper
.getProvider('paia')
.events$.subscribe(action =>
this.showMessage(this.authHelper.getAuthMessage('paia', action)),
);
}
private async showMessage(message?: string) {

View File

@@ -56,7 +56,6 @@ import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AboutModule} from './modules/about/about.module';
import {FavoritesModule} from './modules/favorites/favorites.module';
import {ProfilePageModule} from './modules/profile/profile.module';
import {EndSessionPageModule} from './modules/auth/end-session/end-session.module';
import {FeedbackModule} from './modules/feedback/feedback.module';
import {DebugDataCollectorService} from './modules/data/debug-data-collector.service';
import {Browser} from './util/browser.factory';
@@ -140,7 +139,6 @@ export function createTranslateLoader(http: HttpClient) {
ConfigModule,
DataModule,
HebisModule,
EndSessionPageModule,
IonicModule.forRoot(),
FavoritesModule,
LibraryModule,

View File

@@ -1,3 +1,5 @@
<div class="centeredMessageContainer">
<p>{{ 'auth.messages.default.authorizing' | translate }}</p>
<p>
{{ 'auth.messages' + '.' + providerType + '.' + 'authorizing' | translate }}
</p>
</div>

View File

@@ -1,33 +1,52 @@
import {Component, OnInit, OnDestroy} from '@angular/core';
/*
* Copyright (C) 2022 StApps
* 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, version 3.
*
* 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 <https://www.gnu.org/licenses/>.
*/
import {OnInit, OnDestroy, Component} from '@angular/core';
import {NavController} from '@ionic/angular';
import {Router} from '@angular/router';
import {AuthActions, IAuthAction} from 'ionic-appauth';
import {Subscription} from 'rxjs';
import {DefaultAuthService} from '../../default-auth.service';
import {SCAuthorizationProviderType} from '@openstapps/core';
import {AuthHelperService} from '../../auth-helper.service';
@Component({
selector: 'auth-callback',
templateUrl: './auth-callback-page.component.html',
styleUrls: ['./auth-callback-page.component.scss'],
templateUrl: 'auth-callback-page.component.html',
styleUrls: ['auth-callback-page.component.scss'],
})
export class AuthCallbackPageComponent implements OnInit, OnDestroy {
sub: Subscription;
providerType: SCAuthorizationProviderType = 'default';
private authEvents: Subscription;
constructor(
private auth: DefaultAuthService,
private navCtrl: NavController,
private router: Router,
private authHelper: AuthHelperService,
) {}
ngOnInit() {
this.sub = this.auth.events$.subscribe(action => this.postCallback(action));
this.auth.authorizationCallback(window.location.origin + this.router.url);
this.authEvents = this.authHelper
.getProvider(this.providerType)
.events$.subscribe((action: IAuthAction) => this.postCallback(action));
this.authHelper
.getProvider(this.providerType)
.authorizationCallback(window.location.origin + this.router.url);
}
ngOnDestroy() {
this.sub.unsubscribe();
this.authEvents.unsubscribe();
}
async postCallback(action: IAuthAction) {

View File

@@ -5,38 +5,23 @@ import {
Router,
RouterStateSnapshot,
} from '@angular/router';
import {DefaultAuthService} from './default-auth.service';
import {PAIAAuthService} from './paia/paia-auth.service';
import {IAuthService} from 'ionic-appauth';
import {ActivatedProtectedRouteSnapshot} from './protected.routes';
import {AuthHelperService} from './auth-helper.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuardService implements CanActivate {
authService: IAuthService | PAIAAuthService;
constructor(
private defaultAuth: DefaultAuthService,
private paiaAuth: PAIAAuthService,
private router: Router,
) {}
constructor(private authHelper: AuthHelperService, private router: Router) {}
public async canActivate(
route: ActivatedProtectedRouteSnapshot,
_state: RouterStateSnapshot,
) {
switch (route.data.authProvider) {
case 'paia':
this.authService = this.paiaAuth;
break;
default:
this.authService = this.defaultAuth;
break;
}
try {
await this.authService.getValidToken();
await this.authHelper
.getProvider(route.data.authProvider)
.getValidToken();
} catch {
const originNavigation = this.router.getCurrentNavigation();
let extras: NavigationExtras = {};

View File

@@ -12,6 +12,8 @@ import {
} from '@openstapps/core';
import {ConfigProvider} from '../config/config.provider';
import {StorageProvider} from '../storage/storage.provider';
import {DefaultAuthService} from './default-auth.service';
import {PAIAAuthService} from './paia/paia-auth.service';
const AUTH_ORIGIN_PATH = 'stapps.auth.origin_path';
@Injectable({
@@ -24,6 +26,8 @@ export class AuthHelperService {
private translateService: TranslateService,
private configProvider: ConfigProvider,
private storageProvider: StorageProvider,
private defaultAuth: DefaultAuthService,
private paiaAuth: PAIAAuthService,
) {
this.userConfigurationMap = (
this.configProvider.getAnyValue('auth') as {
@@ -83,4 +87,18 @@ export class AuthHelperService {
}
return originPath;
}
getProvider<B extends SCAuthorizationProviderType>(
providerType: B,
): B extends 'paia' ? PAIAAuthService : DefaultAuthService;
/**
* Provides appropriate auth service instance based on type (string) parameter
*/
getProvider(
providerType: SCAuthorizationProviderType,
): DefaultAuthService | PAIAAuthService {
return providerType === 'paia'
? (this.paiaAuth as PAIAAuthService)
: (this.defaultAuth as DefaultAuthService);
}
}

View File

@@ -15,9 +15,9 @@
import {RouterModule, Routes} from '@angular/router';
import {NgModule} from '@angular/core';
import {AuthCallbackPageComponent} from './auth-callback/page/auth-callback-page.component';
import {PAIAAuthCallbackPageComponent} from './paia/auth-callback/page/auth-callback-page.component';
import {authPaths} from './auth-paths';
import {AuthCallbackPageComponent} from './auth-callback/page/auth-callback-page.component';
import {PAIAAuthCallbackPageComponent} from './paia/auth-callback/page/paiaauth-callback-page.component';
const authRoutes: Routes = [
{

View File

@@ -11,9 +11,9 @@ import {HttpClient} from '@angular/common/http';
import {PAIAAuthService} from './paia/paia-auth.service';
import {AuthRoutingModule} from './auth-routing.module';
import {TranslateModule} from '@ngx-translate/core';
import {AuthCallbackPageComponent} from './auth-callback/page/auth-callback-page.component';
import {PAIAAuthCallbackPageComponent} from './paia/auth-callback/page/auth-callback-page.component';
import {ConfigProvider} from '../config/config.provider';
import {AuthCallbackPageComponent} from './auth-callback/page/auth-callback-page.component';
import {PAIAAuthCallbackPageComponent} from './paia/auth-callback/page/paiaauth-callback-page.component';
@NgModule({
declarations: [AuthCallbackPageComponent, PAIAAuthCallbackPageComponent],

View File

@@ -1,26 +0,0 @@
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {Routes, RouterModule} from '@angular/router';
import {IonicModule} from '@ionic/angular';
import {EndSessionPageComponent} from './page/end-session-page.component';
const routes: Routes = [
{
path: 'logout',
component: EndSessionPageComponent,
},
];
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes),
],
declarations: [EndSessionPageComponent],
})
export class EndSessionPageModule {}

View File

@@ -1 +0,0 @@
<p>Signing out...</p>

View File

@@ -1,20 +0,0 @@
import {Component, OnInit} from '@angular/core';
import {NavController} from '@ionic/angular';
import {DefaultAuthService} from '../../default-auth.service';
@Component({
selector: 'end-session',
templateUrl: './end-session-page.component.html',
styleUrls: ['./end-session-page.component.scss'],
})
export class EndSessionPageComponent implements OnInit {
constructor(
private auth: DefaultAuthService,
private navCtrl: NavController,
) {}
async ngOnInit() {
this.auth.endSessionCallback();
await this.navCtrl.navigateRoot('profile');
}
}

View File

@@ -1,3 +0,0 @@
<div class="centeredMessageContainer">
<p>{{ 'auth.messages.paia.authorizing' | translate }}</p>
</div>

View File

@@ -1,43 +0,0 @@
import {Component, OnInit, OnDestroy} from '@angular/core';
import {NavController} from '@ionic/angular';
import {Router} from '@angular/router';
import {AuthActions, IAuthAction} from 'ionic-appauth';
import {Subscription} from 'rxjs';
import {PAIAAuthService} from '../../paia-auth.service';
import {AuthHelperService} from '../../../auth-helper.service';
@Component({
selector: 'auth-callback',
templateUrl: './auth-callback-page.component.html',
styleUrls: ['./auth-callback-page.component.scss'],
})
export class PAIAAuthCallbackPageComponent implements OnInit, OnDestroy {
sub: Subscription;
constructor(
private auth: PAIAAuthService,
private navCtrl: NavController,
private router: Router,
private authHelper: AuthHelperService,
) {}
ngOnInit() {
this.sub = this.auth.events$.subscribe(action => this.postCallback(action));
this.auth.authorizationCallback(window.location.origin + this.router.url);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
async postCallback(action: IAuthAction) {
if (action.action === AuthActions.SignInSuccess) {
const originPath = await this.authHelper.getOriginPath();
this.navCtrl.navigateRoot(originPath ?? 'profile');
this.authHelper.deleteOriginPath();
}
if (action.action === AuthActions.SignInFailed) {
this.navCtrl.navigateRoot('profile');
}
}
}

View File

@@ -0,0 +1,22 @@
import {Component} from '@angular/core';
import {AuthCallbackPageComponent} from '../../../auth-callback/page/auth-callback-page.component';
import {SCAuthorizationProviderType} from '@openstapps/core';
import {NavController} from '@ionic/angular';
import {Router} from '@angular/router';
import {AuthHelperService} from '../../../auth-helper.service';
@Component({
templateUrl: '../../../auth-callback/page/auth-callback-page.component.html',
styleUrls: ['../../../auth-callback/page/auth-callback-page.component.scss'],
})
export class PAIAAuthCallbackPageComponent extends AuthCallbackPageComponent {
providerType = 'paia' as SCAuthorizationProviderType;
constructor(
navCtrl: NavController,
router: Router,
authHelper: AuthHelperService,
) {
super(navCtrl, router, authHelper);
}
}

View File

@@ -134,7 +134,7 @@ export class MapProvider {
/**
* Provide places (buildings and canteens) const result = await this.dataProvider.search(query);
*
* @param contextFilter Additional contextual filter (e.g. from the context menu)
* @param queryText Query (text) of the search query

View File

@@ -46,11 +46,13 @@
</ion-row>
<ion-row>
<ion-col class="login">
<a *ngIf="!data.default.loggedIn; else loggedIn" (click)="signIn()">{{
'profile.buttons.default.log_in' | translate | titlecase
}}</a>
<a
*ngIf="!data.default.loggedIn; else loggedIn"
(click)="signIn('default')"
>{{ 'profile.buttons.default.log_in' | translate | titlecase }}</a
>
<ng-template #loggedIn
><a (click)="signOut()">{{
><a (click)="signOut('default')">{{
'profile.buttons.default.log_out' | translate | titlecase
}}</a></ng-template
>
@@ -60,11 +62,11 @@
<ion-col class="login">
<a
*ngIf="!data.paia.loggedIn; else paiaLoggedIn"
(click)="signInPAIA()"
(click)="signIn('paia')"
>{{ 'profile.buttons.paia.log_in' | translate | titlecase }}</a
>
<ng-template #paiaLoggedIn
><a (click)="signOutPAIA()">{{
><a (click)="signOut('paia')">{{
'profile.buttons.paia.log_out' | translate | titlecase
}}</a></ng-template
>

View File

@@ -22,17 +22,25 @@ import {ProfilePageComponent} from './profile-page.component';
import {TranslateModule} from '@ngx-translate/core';
import {ConfigProvider} from '../../config/config.provider';
import {sampleAuthConfiguration} from '../../../_helpers/data/sample-configuration';
import {StorageProvider} from '../../storage/storage.provider';
describe('ProfilePage', () => {
let component: ProfilePageComponent;
let fixture: ComponentFixture<ProfilePageComponent>;
let configProvider: ConfigProvider;
let storageProvider: jasmine.SpyObj<StorageProvider>;
beforeEach(async(() => {
configProvider = jasmine.createSpyObj('ConfigProvider', [
'init',
'getAnyValue',
]);
storageProvider = jasmine.createSpyObj('StorageProvider', [
'init',
'get',
'has',
'put',
]);
configProvider.getAnyValue = jasmine.createSpy().and.callFake(function () {
return sampleAuthConfiguration;
});
@@ -45,7 +53,10 @@ describe('ProfilePage', () => {
AuthModule,
TranslateModule.forRoot(),
],
providers: [{provide: ConfigProvider, useValue: configProvider}],
providers: [
{provide: ConfigProvider, useValue: configProvider},
{provide: StorageProvider, useValue: storageProvider},
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
}));

View File

@@ -15,9 +15,7 @@
import {Component, OnDestroy, OnInit} from '@angular/core';
import {IonicUserInfoHandler} from 'ionic-appauth';
import {DefaultAuthService} from '../../auth/default-auth.service';
import {Requestor, TokenResponse} from '@openid/appauth';
import {PAIAAuthService} from '../../auth/paia/paia-auth.service';
import {Subscription} from 'rxjs';
import {AuthHelperService} from '../../auth/auth-helper.service';
import {
@@ -44,8 +42,6 @@ export class ProfilePageComponent implements OnInit, OnDestroy {
subscriptions: Subscription[] = [];
constructor(
private defaultAuth: DefaultAuthService,
private paiaAuth: PAIAAuthService,
private requestor: Requestor,
private authHelper: AuthHelperService,
private route: ActivatedRoute,
@@ -53,8 +49,9 @@ export class ProfilePageComponent implements OnInit, OnDestroy {
ngOnInit() {
this.subscriptions.push(
this.defaultAuth.token$.subscribe(_token => {
this.defaultAuth
this.authHelper.getProvider('default').token$.subscribe(_token => {
this.authHelper
.getProvider('default')
.getValidToken()
.then(token => {
this.data.default.loggedIn = true;
@@ -64,8 +61,9 @@ export class ProfilePageComponent implements OnInit, OnDestroy {
this.data.default.loggedIn = false;
});
}),
this.paiaAuth.token$.subscribe(_token => {
this.paiaAuth
this.authHelper.getProvider('paia').token$.subscribe(_token => {
this.authHelper
.getProvider('paia')
.getValidToken()
.then(_token => {
this.data.paia.loggedIn = true;
@@ -74,8 +72,8 @@ export class ProfilePageComponent implements OnInit, OnDestroy {
this.data.paia.loggedIn = false;
});
}),
this.route.queryParamMap.subscribe(queryParams => {
this.originPath = queryParams.get('origin_path');
this.route.queryParamMap.subscribe(queryParameters => {
this.originPath = queryParameters.get('origin_path');
}),
);
}
@@ -84,31 +82,25 @@ export class ProfilePageComponent implements OnInit, OnDestroy {
const userInfoHandler = new IonicUserInfoHandler(this.requestor);
userInfoHandler
.performUserInfoRequest(this.defaultAuth.localConfiguration, token)
.performUserInfoRequest(
this.authHelper.getProvider('default').localConfiguration,
token,
)
.then(userInfo => {
this.userInfo = this.authHelper.getUserFromUserInfo(userInfo);
});
}
async signIn() {
async signIn(providerType: SCAuthorizationProviderType) {
await this.handleOriginPath();
this.defaultAuth.signIn();
this.authHelper.getProvider(providerType).signIn();
}
async signInPAIA() {
await this.handleOriginPath();
this.paiaAuth.signIn();
}
async signOut() {
await this.defaultAuth.signOut();
async signOut(providerType: SCAuthorizationProviderType) {
await this.authHelper.getProvider(providerType).signOut();
this.userInfo = undefined;
}
async signOutPAIA() {
await this.paiaAuth.signOut();
}
ngOnDestroy(): void {
for (const subscription of this.subscriptions) {
subscription.unsubscribe();