create cookie service to find CSRF header data

This commit is contained in:
Jesse Lucas 2020-03-14 20:07:08 -04:00
parent 4727570870
commit 6b89991ba8
3 changed files with 65 additions and 7 deletions

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { CookieService } from './cookie.service';
describe('CookieService', () => {
let service: CookieService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CookieService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

44
src/app/cookie.service.ts Normal file
View File

@ -0,0 +1,44 @@
import { Injectable } from '@angular/core';
import { deviceID } from './api-utils';
@Injectable({
providedIn: 'root'
})
export class CookieService {
constructor() { }
getCSRFHeader(): any {
const dID: String = deviceID();
const csrfCookie = 'CSRF-Token-' + dID
const csrfHeader = {};
csrfHeader['X-CSRF-Token-' + dID] = this.getCookie(csrfCookie);
return csrfHeader;
}
getCookie(name: string): string {
let ca: Array<string> = document.cookie.split(';');
let caLen: number = ca.length;
let cookieName = `${name}=`;
let c: string;
for (let i: number = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) == 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
deleteCookie(name): void {
this.setCookie(name, "", -1);
}
setCookie(name: string, value: string, expireDays: number, path: string = ""): void {
let d: Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
let expires: string = "expires=" + d.toUTCString();
document.cookie = name + "=" + value + "; " + expires + (path.length > 0 ? "; path=" + path : "");
}
}

View File

@ -7,6 +7,8 @@ import { map } from 'rxjs/operators';
import { Folder } from './folder';
import { Device } from './device';
import { FOLDERS, DEVICES } from './mock-config-data';
import { CookieService } from './cookie.service';
import { apiURL } from './api-utils'
@Injectable({
providedIn: 'root'
@ -17,18 +19,14 @@ export class SystemConfigService {
private devices: Device[];
private foldersSubject: Subject<Folder[]> = new Subject();
private devicesSubject: Subject<Device[]> = new Subject();
private systemConfigUrl = apiURL + '/rest/system/config'; // URL to web api
private systemConfigUrl = 'http://127.0.0.1:8384/rest/system/config'; // URL to web api
httpOptions = {
// TODO find best way to get api key
// headers: new HttpHeaders({ 'X-API-Key': 'x' })
};
httpOptions = { headers: new HttpHeaders(this.cookieService.getCSRFHeader()) };
constructor(private http: HttpClient) { }
constructor(private http: HttpClient, private cookieService: CookieService) { }
ngOnInit(): void { }
getSystemConfig(): Observable<any> {
return this.http
.get(this.systemConfigUrl, this.httpOptions)