Newer
Older
import { filter, map, switchMap, take } from 'rxjs/operators';
Giuseppe Digilio
committed
import { Injectable } from '@angular/core';
Giuseppe Digilio
committed
import { HttpHeaders } from '@angular/common/http';
import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service';
import { AuthStatus } from './models/auth-status.model';
import { isEmpty, isNotEmpty } from '../../shared/empty.util';
import { AuthService, LOGIN_ROUTE } from './auth.service';
Giuseppe Digilio
committed
import { AuthTokenInfo } from './models/auth-token-info.model';
import { CheckAuthenticationTokenAction } from './auth.actions';
import { EPerson } from '../eperson/models/eperson.model';
Giuseppe Digilio
committed
/**
* The auth service.
*/
@Injectable()
export class ServerAuthService extends AuthService {
/**
* Returns the authenticated user
* @returns {User}
Giuseppe Digilio
committed
*/
public authenticatedUser(token: AuthTokenInfo): Observable<EPerson> {
// Determine if the user has an existing auth session on the server
Giuseppe Digilio
committed
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Accept', 'application/json');
headers = headers.append('Authorization', `Bearer ${token.accessToken}`);
// NB this is used to pass server client IP check.
const clientIp = this.req.get('x-forwarded-for') || this.req.connection.remoteAddress;
headers = headers.append('X-Forwarded-For', clientIp);
Giuseppe Digilio
committed
options.headers = headers;
return this.authRequestService.getRequest('status', options).pipe(
map((status) => this.rdbService.build(status)),
Giuseppe Digilio
committed
if (status.authenticated) {
return status.eperson.pipe(map((eperson) => eperson.payload));
Giuseppe Digilio
committed
} else {
throw(new Error('Not authenticated'));
Giuseppe Digilio
committed
}
Giuseppe Digilio
committed
}
/**
* Checks if token is present into browser storage and is valid. (NB Check is done only on SSR)
*/
Giuseppe Digilio
committed
this.store.dispatch(new CheckAuthenticationTokenAction())
}
/**
* Redirect to the route navigated before the login
*/
public redirectAfterLoginSuccess(isStandalonePage: boolean) {
take(1))
Giuseppe Digilio
committed
.subscribe((redirectUrl) => {
if (isNotEmpty(redirectUrl)) {
// override the route reuse strategy
this.router.routeReuseStrategy.shouldReuseRoute = () => {
return false;
};
this.router.navigated = false;
const url = decodeURIComponent(redirectUrl);
this.router.navigateByUrl(url);
} else {
// If redirectUrl is empty use history. For ssr the history array should contain the requested url.
this.routeService.getHistory().pipe(
filter((history) => history.length > 0),
take(1)
).subscribe((history) => {
this.navigateToRedirectUrl(history[history.length - 1] || '');
});