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

Rework auth to use jwts #2087

Merged
merged 15 commits into from
May 8, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions editor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@
"file-list-component": "1.3.2",
"hammerjs": "^2.0.8",
"just-snake-case": "^1.1.0",
"jwt-decode": "^2.2.0",
"material-design-icons-iconfont": "^3.0.3",
"moment": "^2.23.0",
"qrcode-generator-es6": "^1.1.4",
"rangen": "^1.0.0",
"redux": "^4.0.1",
"rxjs": "~6.5.4",
"rxjs-compat": "^6.5.5",
"tangy-form": "4.11.5",
"tangy-form-editor": "6.13.5",
"translation-web-component": "0.0.3",
Expand Down
203 changes: 96 additions & 107 deletions editor/src/app/app.component.html

Large diffs are not rendered by default.

81 changes: 46 additions & 35 deletions editor/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import { AuthenticationService } from './core/auth/_services/authentication.serv
import { RegistrationService } from './registration/services/registration.service';
import { WindowRef } from './core/window-ref.service';
import { MediaMatcher } from '@angular/cdk/layout';
import { HttpClient } from '@angular/common/http';
import { MatSidenav } from '@angular/material';
import { UserService } from './core/auth/_services/user.service';
import { AppConfigService } from './shared/_services/app-config.service';
import { _TRANSLATE } from './shared/_services/translation-marker';


@Component({
Expand All @@ -19,31 +20,31 @@ import { UserService } from './core/auth/_services/user.service';
})
export class AppComponent implements OnInit, OnDestroy {
loggedIn = false;
validSession: boolean;
user_id: string = localStorage.getItem('user_id');
private childValue: string;
canManageSitewideUsers = false
isAdminUser = false
history: string[] = [];
titleToUse: string;
mobileQuery: MediaQueryList;
window:any
window: any;
sessionTimeoutCheckTimerID;

@ViewChild('snav', {static: true}) snav: MatSidenav
@ViewChild('snav', { static: true }) snav: MatSidenav

private _mobileQueryListener: () => void;
constructor(
private windowRef: WindowRef,
private router: Router,
private _registrationService: RegistrationService,
private userService:UserService,
private menuService:MenuService,
private userService: UserService,
private menuService: MenuService,
private authenticationService: AuthenticationService,
private tangyFormService:TangyFormService,
private tangyFormService: TangyFormService,
translate: TranslateService,
changeDetectorRef: ChangeDetectorRef,
media: MediaMatcher,
private http: HttpClient
private appConfigService: AppConfigService
) {
translate.setDefaultLang('translation');
translate.use('translation');
Expand All @@ -54,45 +55,55 @@ export class AppComponent implements OnInit, OnDestroy {
this.window = this.windowRef.nativeWindow;
// Tell tangyFormService which groupId to use.
tangyFormService.initialize(window.location.pathname.split('/')[2])

}

async logout() {
clearInterval(this.sessionTimeoutCheckTimerID);
await this.authenticationService.logout();
this.router.navigate(['login']);
this.window.location.reload()
this.loggedIn = false;
this.isAdminUser = false;
this.canManageSitewideUsers = false;
this.user_id = null;
this.router.navigate(['/login']);
}

async ngOnInit() {
// Ensure user is logged in every 60 seconds.
await this.ensureLoggedIn();
this.isAdminUser = await this.userService.isCurrentUserAdmin()
setInterval(() => this.ensureLoggedIn(), 60 * 1000);
this.authenticationService.currentUserLoggedIn$.subscribe(async isLoggedIn => {
this.isAdminUser = await this.userService.isCurrentUserAdmin()
this.loggedIn = isLoggedIn;
this.user_id = localStorage.getItem('user_id');
this.canManageSitewideUsers = <boolean>await this.http.get('/user/permission/can-manage-sitewide-users').toPromise()
if (!isLoggedIn) { this.router.navigate(['login']); }
if (isLoggedIn) {
this.loggedIn = isLoggedIn;
this.isAdminUser = await this.userService.isCurrentUserAdmin();
this.user_id = localStorage.getItem('user_id');
this.canManageSitewideUsers = await this.userService.canManageSitewideUsers();
this.sessionTimeoutCheck();
this.sessionTimeoutCheckTimerID =
setInterval(await this.sessionTimeoutCheck.bind(this), 10 * 60 * 1000); // check every 10 minutes
} else {
this.loggedIn = false;
this.isAdminUser = false;
this.canManageSitewideUsers = false;
this.user_id = null;
this.router.navigate(['/login']);
}
});
fetch('assets/translation.json')
.then(response => response.json())
.then(json => {
this.window.translation = json
})
}

async ensureLoggedIn() {
this.loggedIn = await this.authenticationService.isLoggedIn();
if (this.loggedIn && await this.authenticationService.validateSession() === false) {
console.log('found invalid session');
this.isAdminUser = false
this.canManageSitewideUsers = false
this.logout();
}
this.window.translation = await this.appConfigService.getTranslations();
}
ngOnDestroy(): void {
this.mobileQuery.removeListener(this._mobileQueryListener);
}

async sessionTimeoutCheck() {
const token = localStorage.getItem('token');
const claims = JSON.parse(atob(token.split('.')[1]));
const expiryTimeInMs = claims['exp'] * 1000;
const minutesBeforeExpiry = expiryTimeInMs - (15 * 60 * 1000); // warn 15 minutes before expiry of token
if (Date.now() >= minutesBeforeExpiry) {
const extendSession = confirm(_TRANSLATE('You are about to be logged out from Tangerine. Should we extend your session?'));
if (extendSession) {
await this.authenticationService.extendUserSession();
} else {
await this.logout();
}
}
}

}
4 changes: 3 additions & 1 deletion editor/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
MatButtonModule, MatIconModule, MatCheckboxModule, MatCardModule, MatMenuModule,
MatSidenavModule, MatToolbarModule, MatDividerModule
} from '@angular/material';
import { httpInterceptorProviders } from './core/http/interceptors';


export function HttpLoaderFactory(httpClient: HttpClient) {
Expand Down Expand Up @@ -64,7 +65,8 @@ export function HttpLoaderFactory(httpClient: HttpClient) {
}),
BrowserAnimationsModule
],
providers: [TangyErrorHandler, WindowRef, { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }],
providers: [httpInterceptorProviders, TangyErrorHandler,
WindowRef, { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }],
bootstrap: [AppComponent]
})
export class AppModule { }
20 changes: 7 additions & 13 deletions editor/src/app/core/auth/_components/login/login.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,24 @@ export class LoginComponent implements OnInit {
private authenticationService: AuthenticationService,
private route: ActivatedRoute,
private router: Router,
private windowRef: WindowRef
) { }

ngOnInit() {
async ngOnInit() {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || 'projects';
if (await this.authenticationService.isLoggedIn()) {
this.router.navigate([this.returnUrl]);
}
}

async loginUser() {
try {
const data = await this.authenticationService.login(this.user.username, this.user.password);
if (data) {
this.router.navigate(['projects']);
setTimeout(() => {
if (this.windowRef.nativeWindow.location.hash === '#/login') {
console.log('force navigation')
this.windowRef.nativeWindow.location.hash = ''
}
}, 3000)

if (await this.authenticationService.login(this.user.username, this.user.password)) {
this.router.navigate(['/projects']);
} else {
this.errorMessage = _TRANSLATE('Login Unsuccesful');
}
} catch (error) {
this.errorMessage = _TRANSLATE('Login Unsuccesful');
console.error(error);
}
}

Expand Down
50 changes: 37 additions & 13 deletions editor/src/app/core/auth/_services/authentication.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,33 @@ import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { UserService } from './user.service';
import { Subject } from 'rxjs';
import jwt_decode from 'jwt-decode';
@Injectable()
export class AuthenticationService {
public currentUserLoggedIn$: any;
private _currentUserLoggedIn: boolean;
constructor(private userService: UserService, private httpClient: HttpClient) {
constructor(private userService: UserService, private http: HttpClient) {
this.currentUserLoggedIn$ = new Subject();
}
async login(username: string, password: string) {
const result = this.httpClient.post('/login', { username, password });
result.subscribe(async (data: any) => {
if (data.statusCode === 200) {
await localStorage.setItem('token', data.name);
await localStorage.setItem('user_id', data.name);
await localStorage.setItem('password', data.statusMessage);
this._currentUserLoggedIn = true;
this.currentUserLoggedIn$.next(this._currentUserLoggedIn);
try {
const data = await this.http.post('/login', {username, password}, {observe: 'response'}).toPromise();
if (data.status === 200) {
const token = data.body['data']['token'];
const jwtData = jwt_decode(token);
localStorage.setItem('token', token);
localStorage.setItem('user_id', jwtData.username);
return true;
} else {
return false;
}
});
return await result.toPromise().then((data: any) => data.statusCode === 200);
} catch (error) {
console.error(error);
localStorage.removeItem('token');
localStorage.removeItem('user_id');
return false;
}
}

async isLoggedIn():Promise<boolean> {
this._currentUserLoggedIn = false;
this._currentUserLoggedIn = !!localStorage.getItem('user_id');
Expand All @@ -31,7 +37,7 @@ export class AuthenticationService {
}

async validateSession():Promise<boolean> {
const status = await this.httpClient.get(`/login/validate/${localStorage.getItem('user_id')}`).toPromise()
const status = await this.http.get(`/login/validate/${localStorage.getItem('user_id')}`).toPromise()
return status['valid']
}

Expand All @@ -43,4 +49,22 @@ export class AuthenticationService {
this._currentUserLoggedIn = false;
this.currentUserLoggedIn$.next(this._currentUserLoggedIn);
}

async extendUserSession() {
const username = localStorage.getItem('user_id');
try {
const data = await this.http.post('/extendSession', {username}, {observe: 'response'}).toPromise();
if (data.status === 200) {
const token = data.body['data']['token'];
const jwtData = jwt_decode(token);
localStorage.setItem('token', token);
localStorage.setItem('user_id', jwtData.username);
return true;
} else {
return false;
}
} catch (error) {
console.log(error);
}
}
}
28 changes: 28 additions & 0 deletions editor/src/app/core/http/interceptors/auth-token-interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Adapted from https://stackoverflow.com/questions/45735655/how-do-i-set-the-baseurl-for-angular-httpclient
*/
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import { AuthenticationService } from '../../auth/_services/authentication.service';
import { tap } from 'rxjs/operators';

@Injectable()
export class APIInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
const apiReq = token
? req.clone({ url: `${req.url}` , headers: req.headers.set('Authorization', token) })
: req.clone({ url: `${req.url}` });
return next.handle(apiReq).pipe( tap(() => {},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status !== 401) {
return;
}
this.authenticationService.logout();
}
}));
}
}
10 changes: 10 additions & 0 deletions editor/src/app/core/http/interceptors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { APIInterceptor } from './auth-token-interceptor';

/** Http interceptor providers in outside-in order */
/**
* Gotten from https://angular.io/guide/http#advanced-usage
*/
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: APIInterceptor, multi: true },
];
7 changes: 7 additions & 0 deletions editor/src/app/shared/_services/app-config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,11 @@ export class AppConfigService {
const result:any = await this.getAppConfig(groupName);
return result.homeUrl;
}
async getTranslations() {
try {
return await this.http.get('assets/translation.json').toPromise();
} catch (error) {
console.error(error);
}
}
}
1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"flat": "^4.0.0",
"fs-extra": "^4.0.3",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.5.1",
"junk": "^2.1.0",
"lodash": "^4.17.10",
"multer": "^1.4.1",
Expand Down
37 changes: 37 additions & 0 deletions server/src/auth-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const jwt = require('jsonwebtoken');
const expiresIn ='1h';
const issuer = 'Tangerine';
const jwtTokenSecret = require('crypto').randomBytes(256).toString('base64');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@evansdianga This looks similar to the approach laid out here. Was there another article that you found that talked about this approach?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @rjsteinert , most approaches coalesced around using a 256 bit cryptographically secure hashes. There is a link in the PR description which links to a discussion on the hapi.js repo as they used a similar approach. The discussion there also lists quite a number of links and gives further info on the approach.


const createLoginJWT = ({ username }) => {
const signingOptions = {
expiresIn,
issuer,
subject: username,
};
return jwt.sign({ username }, jwtTokenSecret, signingOptions);
};

const verifyJWT = (token) => {
try {
const jwtPayload = jwt.verify(token, jwtTokenSecret, { issuer });
return !!jwtPayload;
} catch (error) {
return false;
}
};

const decodeJWT = (token) => {
try {
const jwtPayload = jwt.verify(token, jwtTokenSecret, { issuer });
return jwtPayload;
} catch (error) {
return undefined;
}
};

module.exports = {
createLoginJWT,
decodeJWT,
verifyJWT,
};
Loading