Skip to content

Instantly share code, notes, and snippets.

@klinki
Created February 23, 2018 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klinki/d6f7876ca595daaa56b0c78447a325d0 to your computer and use it in GitHub Desktop.
Save klinki/d6f7876ca595daaa56b0c78447a325d0 to your computer and use it in GitHub Desktop.
import { autoinject } from 'aurelia-framework';
import { Redirect } from 'aurelia-router';
import { FirebaseAuthService } from '../shared/firebase/authentication.service';
@autoinject()
export class AuthorizeStep {
protected static LOGIN_ADDRESS = '/login';
constructor(protected auth: FirebaseAuthService) {
}
public run(navigationInstruction, next) {
console.log('authorize step run');
return Promise.resolve()
.then(() => this.checkAuthorizationAsync(navigationInstruction, next))
.then((result) => result || this.checkOrigin(navigationInstruction, next))
.then((result) => result || this.afterAuthRedirect(navigationInstruction, next))
.then((result) => result || next());
}
public afterAuthRedirect(instruction, next) {
return this.auth.isUserLoggedInPromise.then(isLoggedIn => {
if (isLoggedIn) {
return next.cancel(new Redirect('/'));
}
});
}
public checkAuthorization(instruction, next) {
console.log('check auth');
if (instruction.getAllInstructions().some((i) => i.config.auth)) {
const isLoggedIn = this.auth.isUserLoggedIn;
if (!isLoggedIn) {
const currentUrl = instruction.fragment + (instruction.queryString ? `?${instruction.queryString}` : '');
localStorage.setItem('origin', currentUrl);
return next.cancel(new Redirect(AuthorizeStep.LOGIN_ADDRESS));
}
}
}
public checkAuthorizationAsync(instruction, next) {
console.log('check auth async');
console.log(this.auth.isUserLoggedInPromise);
console.log(instruction);
console.log(instruction.getAllInstructions());
console.log(instruction.getAllInstructions().some((i) => i.config.auth));
if (instruction.getAllInstructions().some((i) => i.config.auth)) {
console.log('Checking authentication.....');
return this.auth.isUserLoggedInPromise.then(isLoggedIn => {
console.log('Check auth async then');
console.log(isLoggedIn);
if (!isLoggedIn) {
const currentUrl = instruction.fragment + (instruction.queryString ? `?${instruction.queryString}` : '');
localStorage.setItem('origin', currentUrl);
return next.cancel(new Redirect(AuthorizeStep.LOGIN_ADDRESS));
}
}, error => console.error(error)).catch(error => {
console.log('Catch error');
console.log(error);
const currentUrl = instruction.fragment + (instruction.queryString ? `?${instruction.queryString}` : '');
localStorage.setItem('origin', currentUrl);
return next.cancel(new Redirect(AuthorizeStep.LOGIN_ADDRESS));
});
}
}
public checkOrigin(instruction, next) {
const origin = localStorage.getItem('origin');
// Check if we were not redirected to login page and have an origin
if (instruction.fragment !== AuthorizeStep.LOGIN_ADDRESS && origin) {
localStorage.removeItem('origin');
return next.cancel(new Redirect(origin));
}
}
}
import { EventAggregator } from 'aurelia-event-aggregator';
import { autoinject } from 'aurelia-framework';
import { AuthenticationMessage } from '../../auth/messages';
import { firebase } from './firebase-mock';
import { FirebaseBaseService } from './firebase-base.service';
@autoinject()
export class FirebaseAuthService extends FirebaseBaseService {
protected auth: any;
protected _isUserLoggedIn = false;
protected _user = null;
protected authToken;
isUserLoggedInPromise: Promise<any>;
public constructor(protected eventAggregator: EventAggregator) {
super();
console.log('authentication constructor');
this.auth = firebase.auth();
let loggedInCallback;
this.isUserLoggedInPromise = new Promise((resolve, reject) => {
loggedInCallback = resolve;
}).then(result => {
console.log('Inside promise: ', result);
return result
}, error => {
console.log('Inside promise: ', error);
}).catch(error => {
console.log('Inside promise: ', error);
});
if (this.auth.currentUser) {
console.log(this.auth.currentUser);
loggedInCallback(true);
}
this.auth.onAuthStateChanged((user) => {
console.log('onAuthStateChanged');
this._isUserLoggedIn = user ? true : false;
this._user = user;
loggedInCallback(this._isUserLoggedIn);
this.publishEvent();
});
firebase.auth().getRedirectResult().then((result) => {
console.log('Redirect result');
console.log(result);
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
this._isUserLoggedIn = user ? true : false;
this._user = user;
loggedInCallback(this._isUserLoggedIn);
}).catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
loggedInCallback(false);
});
}
public logIn(method: string, rememberMe: boolean = false, useRedirect: boolean = false): Promise<any> {
let provider;
switch (method) {
default:
throw new Error(`Unknown auth provider '${method}'`);
case 'google':
provider = new firebase.auth.GoogleAuthProvider();
break;
case 'facebook':
provider = new firebase.auth.FacebookAuthProvider();
break;
}
const persistence = rememberMe ? firebase.auth.Auth.Persistence.LOCAL : firebase.auth.Auth.Persistence.SESSION;
return this.auth.setPersistence(persistence).then(() => {
if (useRedirect) {
return this.auth.signInWithRedirect(provider).then((result) => {
this.authToken = result.credential.accessToken;
this._user = result.user;
this._isUserLoggedIn = true;
});
} else {
return this.auth.signInWithPopup(provider).then((result) => {
this.authToken = result.credential.accessToken;
this._user = result.user;
this._isUserLoggedIn = true;
});
}
});
}
protected handleSuccessfulLogIn(result) {
this.authToken = result.credential.accessToken;
this._user = result.user;
this._isUserLoggedIn = true;
}
public register(username: string, password: string): Promise<any> {
return this.auth.createUserWithEmailAndPassword(username, password).then(() => {
if (!this.auth.currentUser.emailVerified) {
return this.auth.currentUser.sendEmailVerification();
}
});
}
public logInWithCredentials(username: string, password: string, rememberMe: boolean = false) {
const persistence = rememberMe ? firebase.auth.Auth.Persistence.LOCAL : firebase.auth.Auth.Persistence.SESSION;
return this.auth.setPersistence(persistence).then(() => {
return this.auth.signInWithEmailAndPassword(username, password).then((result) => {
this._user = result.user;
this._isUserLoggedIn = true;
});
});
}
protected publishEvent() {
this.eventAggregator.publish(new AuthenticationMessage(this._isUserLoggedIn, this.user));
}
public logOut(): Promise<any> {
return this.auth.signOut().then((result) => {
this._isUserLoggedIn = false;
this._user = null;
}).catch((error) => {
throw new Error(error);
});
}
public linkCredentialsProvider(username: string, password: string): Promise<any> {
const credentials = firebase.auth.EmailAuthProvider.credential(username, password);
return this.auth.currentUser.linkWithCredential(credentials).then((user) => {
console.log(user);
});
}
public get isUserLoggedIn(): boolean {
return this._isUserLoggedIn;
}
public get user() {
return this.auth.currentUser;
}
}
import { FirebaseAuthService } from './authentication.service';
import { firebase } from "./firebase-mock";
import environment from "../../environment";
export class FirebaseBaseService {
protected static isInitialized = false;
public constructor() {
FirebaseBaseService.initialize();
}
public static initialize() {
if (!FirebaseBaseService.isInitialized) {
console.log('[Firebase] Initializing firebase.....');
console.log(environment.firebase);
// Initialize Firebase
firebase.initializeApp(environment.firebase);
console.log(firebase.firestore);
if (firebase.firestore) {
// Enable firebase offline persistence
firebase.firestore().enablePersistence().then(function () {
// Initialize Cloud Firestore through firebase
var db = firebase.firestore();
}).catch(function (err) {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
}
});
} else {
console.error('firebase.firestore() not loaded');
}
FirebaseBaseService.isInitialized = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment