0

I use the fetch client of Aurelia to fetch data from a REST-service. My problem is that, even though the HttpClient is only imported once in the AuthService Class, I have to pass it the configuration object before every single request, or it falls back to defaults.

It seems my interceptors don't fall off, I only have to configure them once. But my baseurl tends to fall off. The weird thing is, I'm having problems isolating when the baseurl stops working. Sometimes it does, sometimes it doesn't.

Here is my auth.service.ts

import { APP_CONSTANTS } from '../app.constants';

import { Aurelia } from 'aurelia-framework';
import { HttpClient, json } from 'aurelia-fetch-client';
import { inject } from 'aurelia-framework';

@inject(HttpClient, Aurelia)
export class AuthService {

    isRequesting: boolean = false;
    isAuthenticated: boolean = false;
    company: any;
    user: any;
    token: string;
    httpConfig: any;

    constructor(private http: HttpClient, private app: Aurelia) {
        let self = this;
        this.httpConfig = config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL);
        }
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withInterceptor({
                    request(request) {
                        self.isRequesting = true;
                        return request;
                    },
                    response(response) {
                        if(response.status === 401) {
                            self.logout();
                        }
                        self.isRequesting = false;
                        return response;
                    }
                })
        });
        let token = window.localStorage.getItem('ol_token');
        let companyName = window.location.pathname;
        companyName = companyName.replace('/', '');
        if(!companyName.length) {
            this.getCompany('onlinelog')
                .then(response => response.json())
                .then(result => {
                    self.company = result.data;
                })
        } else {
            this.getCompany(companyName)
                .then(response => response.json())
                .then(result => {
                    self.company = result.data;
                });
        }
        if(token) {
            this.token = token;
            this.http.configure(config => {
                config.withDefaults({
                    headers: {
                        'Authorization': token,
                    }
                })
            })
            this.getUserCredentials()
                .then(response => response.json())
                .then(result => {
                    self.user = result.data;
                })
            this.isAuthenticated = true;
        }
    }

    getCompany(name) {
        this.http.configure(this.httpConfig);
        return this.http.fetch(`company/info/${name}`);
    }

    loadingTest() {
        let self = this;
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': this.token
                    }
                })
        });
        this.http.fetch('isauthed')
            .then(response => response.json())
            .then(result => {
                console.log(result);
            })
    }

    getUserCredentials() {
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': this.token
                    }
                })
        });
        return this.http.fetch(`isauthed`);
    }

    authenticate(user, password) {
        let obj = {
            login: user,
            password: password
        }
        this.http.fetch(`authenticate`, {
            method: 'post',
            body: json(obj)
        }).then(response => response.json())
        .then(result => {
            this.user = result.data;
            this.token = result.token;
            this.setToken(result.token);
            window.localStorage.setItem('ol_token', result.token);
            this.app.setRoot('app');
        })
    }

    setToken(token) {
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': token
                    }
                })
        })
    }

    logout() {
        this.http.configure(config => {
            config
                .withBaseUrl(APP_CONSTANTS.API_URL)
                .withDefaults({
                    headers: {
                        'Authorization': null
                    }
                })
        });
        this.token = '';
        window.localStorage.removeItem('ol_token');
        this.user = null;
        this.app.setRoot('auth/auth');
    }

}

As you can see, the "authenticate" method, does not need to reconfigure the baseurl. But if I try to call the getUserCredentials method without reconfiguring, it gives a JSON-parsing error because it tries to send the request to "localhost:9000/isauthed/" instead of "localhost:4000/api/isauthed/" like it should.

Any help would be appreciated!

The way I want it to work, is that I configure the HttpClient with baseUrl and interceptors ONCE, and to be able to dynamically edit the configuration of headers sent based on if the user is authenticated or not.

Stian Bakken
  • 673
  • 1
  • 5
  • 15

0 Answers0