Skip to content

Instantly share code, notes, and snippets.

@probinso
Created May 1, 2019 16:31
Show Gist options
  • Save probinso/ca759cf988d1709c443b030345542d3e to your computer and use it in GitHub Desktop.
Save probinso/ca759cf988d1709c443b030345542d3e to your computer and use it in GitHub Desktop.
Cookie intercepting for authentication on NativeScript angular
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import {
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpEvent
} from "@angular/common/http";
import { StorageService } from "./storage.service";
@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(private store: StorageService) {
}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
enum Key {
Login,
Logout,
Credentialed,
Other
}
let requestType = Key.Other;
const loginAPI = "/api/user/login";
const logoutAPI = "/api/user/logout";
if (req["url"]) {
if (req["url"].endsWith(logoutAPI)) {
requestType = Key.Logout;
} else if (req["url"].endsWith(loginAPI)) {
requestType = Key.Login;
} else if (req["withCredentials"]) {
requestType = Key.Credentialed;
}
}
if (requestType === Key.Credentialed) {
const cache = this.store.get(this.constructor.name);
if (cache) {
let token: string = "";
for (const key in cache) {
token = `${token}${key}=${cache[key]}; `;
}
const newReq = req.clone({
headers: req.headers.append("Cookie", token.trim())
});
return next.handle(newReq);
} else {
requestType = Key.Other;
}
}
if (requestType === Key.Logout) {
this.store.remove(this.constructor.name);
return next.handle(req);
}
if (requestType === Key.Login) {
return next.handle(req).pipe(
tap(
response => {
if (requestType === Key.Login && response["headers"]) {
const cookies = response["headers"].get(
"Set-Cookie"
);
let target = this.store.get(this.constructor.name);
if (!target) {
target = {};
}
let idx;
let reg = RegExp("(\\S*?)=(\\S*?);", "g");
while ((idx = reg.exec(cookies)) !== null) {
let key = idx[1];
let value = idx[2];
if (value === "deleteMe") {
if (key in target) {
delete target[key];
continue;
}
} else {
target[key] = value;
}
}
this.store.set(this.constructor.name, target);
}
},
error => {
console.log(
`Error in Response`
);
}
)
);
}
return next.handle(req);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment