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

Make it compatible JWT Server and application REST requests #157

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
1 change: 0 additions & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {AuthInterceptor, RestService,} from './rest/rest.service';
import {ClusterRestService} from './rest/cluster.service';
import {SupportRestService} from './rest/support.service';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
//import { AuthInterceptor } from './rest/auth.interceptor';
import {ClipboardModule} from 'ngx-clipboard';
import {Locale} from './locale/locale';
import {AppPageComponent} from "./app.page/app.page.component";
Expand Down
3 changes: 2 additions & 1 deletion src/app/app.page/app.definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ export class ServerSettings {
constructor(public serverName: string,
public licenceKey: string,
public buildForMarket: boolean,
public logLevel: string
public logLevel: string,
public jwtServerControlEnabled: boolean
) {}
}

Expand Down
3 changes: 1 addition & 2 deletions src/app/app.page/app.page.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,6 @@ export class AppPageComponent implements OnInit, OnDestroy, AfterViewInit {
}

this.dataSource = new MatTableDataSource(this.broadcastTableData.dataRows);
console.log(this.dataSource)
this.cdr.detectChanges();

}, error => { show403Error(error); });
Expand Down Expand Up @@ -1323,7 +1322,7 @@ export class AppPageComponent implements OnInit, OnDestroy, AfterViewInit {
});

},
error =>
error =>
{
show403Error(error);
});
Expand Down
23 changes: 18 additions & 5 deletions src/app/pages/login/login.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,36 @@ <h3 class="card-title" i18n="@@loginTitle">Login</h3>
You can now login with your username and password
</div>

<div class="form-group">
<div *ngIf="serverJWTControlEnabled" class="form-group">
<label i18n="@@loginFormEmail">JWT Token</label>
<input (keydown)="JWTTokenChanged()" type="text" name="jwtToken" placeholder="JWT Token" class="form-control input-no-border" [(ngModel)]="serverJWTToken">
</div>

<div *ngIf="!serverJWTControlEnabled" class="form-group">
<label i18n="@@loginFormEmail">Username</label>
<input (keydown)="credentialsChanged()" type="email" name="email" i18n-placeholder="@@email_place_holder" placeholder="Username" class="form-control input-no-border" [(ngModel)]="email">

</div>
<div class="form-group">
<div *ngIf="!serverJWTControlEnabled" class="form-group">
<label i18n="@@loginFormPassword">Password</label>
<input (keydown)="credentialsChanged()" type="password" name="password" i18n-placeholder="@@password_place_holder" placeholder="Password" class="form-control input-no-border" [(ngModel)]="password">
</div>
<div class="form-group text-danger text-center" [hidden]="!showIncorrectCredentials"
i18n="@@loginFormIncorrectCredentials" >
<div *ngIf="!serverJWTControlEnabled" class="form-group text-danger text-center" [hidden]="!showIncorrectCredentials"
i18n="@@loginFormIncorrectCredentials" >
Username or password is incorrect
</div>
<div *ngIf="serverJWTControlEnabled" class="form-group text-danger text-center" [hidden]="!showIncorrectJWTToken">
JWT Token is incorrect
</div>
<div class="form-group text-danger text-center" *ngIf="blockLoginAttempt"
>
You have 3 invalid login attempts. Please try again to login after 5 minutes
</div>
<div class="checkbox">
<input [(ngModel)]="serverJWTControlEnabled" name="jwtTokenEnabled" id="jwtTokenEnabled" type="checkbox">
<label for="jwtTokenEnabled">
Login with JWT Server Token
</label>
</div>
</div>
<div class="card-footer text-center">
<button type="submit" i18n="@@loginFormSubmit" class="btn btn-fill btn-wd ">Let's go</button>
Expand Down
86 changes: 58 additions & 28 deletions src/app/pages/login/login.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@ export class LoginComponent implements OnInit{
public email = "";
public password = "";
public showIncorrectCredentials = false;
public showIncorrectJWTToken = false;
public blockLoginAttempt = false;
public firstLogin = false;
public firstUser: User;
public temp_model_password:string;
public firstUserIsCreating:boolean;
public showYouCanLogin:boolean;
public showFailedToCreateUserAccount:boolean;
public serverJWTToken: string;
public serverJWTControlEnabled: boolean;

constructor(private element : ElementRef, private auth: AuthService, private router: Router,private restService: RestService) {
this.nativeElement = element.nativeElement;
Expand Down Expand Up @@ -94,38 +97,60 @@ export class LoginComponent implements OnInit{

loginUser() {

this.auth.login(this.email, this.password).subscribe(data =>{

if (data["success"] == true)
{
this.auth.isAuthenticated = data["success"];
localStorage.setItem("authenticated", "true");
localStorage.setItem(LOCAL_STORAGE_EMAIL_KEY, this.email);

let scope = data["message"];
if (isScopeSystem(scope)) {
scope = "system";
}
localStorage.setItem(LOCAL_STORAGE_SCOPE_KEY, scope);
if (isScopeSystem(scope))
{
localStorage.clear();

if(this.serverJWTControlEnabled) {

//We need to define this value in this line
//server JWT tokens needs to be define before rest request
localStorage.setItem('serverJWTControlEnabled', "true");
localStorage.setItem('serverJWTToken', this.serverJWTToken);
this.restService.isInClusterMode().subscribe(data =>{

localStorage.setItem("authenticated", "true");
this.auth.isAuthenticated = true;

let scope = "system";
localStorage.setItem(LOCAL_STORAGE_SCOPE_KEY, scope);

this.router.navigateByUrl("/dashboard");
}
else
},
error =>{
this.showIncorrectJWTToken = true;
});
}
else{
this.auth.login(this.email, this.password).subscribe(data =>{
if (data["success"] == true)
{
this.router.navigateByUrl("/applications/" + scope);
this.auth.isAuthenticated = data["success"];
localStorage.setItem("authenticated", "true");
localStorage.setItem(LOCAL_STORAGE_EMAIL_KEY, this.email);

let scope = data["message"];
if (isScopeSystem(scope)) {
scope = "system";
}
localStorage.setItem(LOCAL_STORAGE_SCOPE_KEY, scope);
if (isScopeSystem(scope))
{
this.router.navigateByUrl("/dashboard");
}
else
{
this.router.navigateByUrl("/applications/" + scope);
}
}
else {
this.showIncorrectCredentials = true;
}
}
else {
this.showIncorrectCredentials = true;
}

}, error => { show403Error(error); });
this.restService.getBlockedStatus(this.email).subscribe(data => {
this.blockLoginAttempt = data["success"];
}, error => { show403Error(error); });

}, error => { show403Error(error); });

this.restService.getBlockedStatus(this.email).subscribe(data => {
this.blockLoginAttempt = data["success"];
}, error => { show403Error(error); });
}
}


Expand All @@ -152,6 +177,11 @@ export class LoginComponent implements OnInit{
credentialsChanged():void {
this.showIncorrectCredentials = false;
}

JWTTokenChanged():void {
this.showIncorrectJWTToken = false;
}

}

export const LOCAL_STORAGE_EMAIL_KEY = "email";
Expand Down
51 changes: 32 additions & 19 deletions src/app/rest/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,24 @@ export var isScopeSystem = function(scope) {
return scope == "" || scope == null || scope == "null" || scope == "system";
}

export var show403Error = function(error)
export var show403Error = function(error)
{
//if it's 403 error, show an alert
if (error && error.status == 403) {
//if it's 403 error, show an alert
if (error && error.status == 403) {
let message = "You are not allowed to access this resource. Contact your system administrator"

$.notify({
icon: "ti-alert",
message: message
}, {
type: 'warning',
delay: 3000,

placement: {
from: 'bottom',
align: 'center'
}

});
}
}
Expand Down Expand Up @@ -65,33 +65,32 @@ export class AuthService implements CanActivate {

setInterval(() => {
this.checkServerIsAuthenticated();

}, 5000);

//Check license every 300 seconds 5 minutes
setInterval(() => {
this.checkLicense();
}, 300000);


}

public checkLicense() {
let scope = localStorage.getItem(LOCAL_STORAGE_SCOPE_KEY);
if (this.isAuthenticated && scope == "system")
if (this.isAuthenticated && scope == "system")
{
if (this.serverSettings != null)
if (this.serverSettings != null)
{
this.restService.isEnterpriseEdition().subscribe(data =>
this.restService.isEnterpriseEdition().subscribe(data =>
{
this.isEnterpriseEdition = data["success"];
if (this.isEnterpriseEdition) {
this.getLicenceStatus(this.serverSettings.licenceKey);
}
}, error => {
}, error => {
show403Error(error);
});

} else {
this.getServerSettings();
}
Expand Down Expand Up @@ -129,8 +128,9 @@ export class AuthService implements CanActivate {
}

checkServerIsAuthenticated(): void {
let currentServerJwtStatus = localStorage.getItem('serverJWTControlEnabled');

if (localStorage.getItem('authenticated'))
if (localStorage.getItem('authenticated') && currentServerJwtStatus != "true")
{
this.restService.isAuthenticated().subscribe(data => {

Expand All @@ -157,17 +157,25 @@ export class AuthService implements CanActivate {
show403Error(error);
});
}
else if(localStorage.getItem('authenticated') && this.isAuthenticated && currentServerJwtStatus == "true" ){
this.isAuthenticated = true;

if(this.router.url=="/pages/login"){
this.router.navigateByUrl('/dashboard/overview');
}
}
else{
this.isAuthenticated = false;
}
}

canActivate(): boolean {
let currentServerJwtStatus = localStorage.getItem('serverJWTControlEnabled');

console.debug("AuthService: is authenticated: " + this.isAuthenticated
+ " local storage: " + localStorage.getItem('authenticated'));

if (localStorage.getItem('authenticated') && this.isAuthenticated) {

if (localStorage.getItem('authenticated') && this.isAuthenticated && currentServerJwtStatus != "true") {
this.restService.isAuthenticated().subscribe(data => {

this.isAuthenticated = data["success"];
Expand All @@ -186,7 +194,12 @@ export class AuthService implements CanActivate {
});
return true;
}
else {
else if(localStorage.getItem('authenticated') && this.isAuthenticated && currentServerJwtStatus == "true"){

this.isAuthenticated = true;
return true;
}
else{
console.debug("AuthService navigating login")
this.router.navigateByUrl('/pages/login');
this.isAuthenticated = false;
Expand All @@ -201,8 +214,8 @@ export class AuthService implements CanActivate {
this.serverSettings = <ServerSettings>data;
localStorage.setItem('hostAddress', data["hostAddress"]);
this.getLicenceStatus(this.serverSettings.licenceKey)
}, error => {
show403Error(error);
}, error => {
show403Error(error);
});
}

Expand Down
32 changes: 26 additions & 6 deletions src/app/rest/rest.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import {HttpClient, HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Endpoint,PlaylistItem} from "../app.page/app.definitions";
import { filter } from 'rxjs-compat/operator/filter';
import {SidebarComponent} from "../sidebar/sidebar.component";
import { show403Error } from './auth.service';

Expand Down Expand Up @@ -65,29 +64,50 @@ export class AuthInterceptor implements HttpInterceptor{

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let str = req.url;
let appName;
let appName = null;
let currentAppJwtToken = null;
let currentAppJwtStatus = null;

//For internal requests
if(str.includes("_path=")) {
var begin = str.indexOf("_path=");
var last = str.lastIndexOf("/rest/v2/");
appName = str.substring(begin+6, last);
}
//for remote requests
else if(str.includes("rest/v2")){
//It can be confuse from internal requests that's why I changed
else if(!str.includes(":5080/rest/v2")){
var begin = str.indexOf(":5080/");
var last = str.indexOf("/rest/v2");
appName = str.substring(begin+6, last);
}
let currentAppJwtToken = localStorage.getItem(appName+'jwtToken');
let currentAppJwtStatus = localStorage.getItem(appName+'jwtControlEnabled');
if(appName != null ){
currentAppJwtToken = localStorage.getItem(appName+'jwtToken');
currentAppJwtStatus = localStorage.getItem(appName+'jwtControlEnabled');
}

let currentServerJwtToken = localStorage.getItem('serverJWTToken');
let currentServerJwtStatus = localStorage.getItem('serverJWTControlEnabled');

if(appName != null && currentAppJwtToken != null && currentAppJwtStatus == "true" && currentServerJwtToken != null && currentServerJwtStatus == "true" ){
req = req.clone({
withCredentials: true,
headers: req.headers.append('ProxyAuthorization', currentServerJwtToken).append('Authorization', currentAppJwtToken)
});
}
// Check AppName, JWT Token status and JWT Token not null
if(appName != null && currentAppJwtToken != null && currentAppJwtStatus != "false"){
else if(appName != null && currentAppJwtToken != null && currentAppJwtStatus == "true"){
req = req.clone({
withCredentials: true,
headers: req.headers.append('Authorization', currentAppJwtToken)
});
}
else if(currentServerJwtToken != null || currentServerJwtStatus == "true"){
req = req.clone({
withCredentials: true,
headers: req.headers.append('ProxyAuthorization', currentServerJwtToken)
});
}
else {
req = req.clone({
withCredentials: true
Expand Down
Loading