Error when refreshing the page with router vue.js - firebase-realtime-database

when I press F5 the components disappear.only happens when I use beforeEnter: auth. if I navigate within the pages with router-link it works well
router/Auth.js
import * as firebase from 'firebase';
export default (to, from, next) => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
next();
} else {
next('/user/login');
}
});
};
router/index.js
{
path: 'edit',
name: 'edit_profile',
component: edit,
beforeEnter: auth,
}
this happens when I press F5: Nothing is shown

Related

Sign in with Apple implementation with Angular

I am trying to implement Sign in with Apple in Angular website.
The flow of implementation starts with adding
in the index.html file.
Then created a service called apple-login-service.ts using scriptjs.
This is the code for apple button in sign-in-container.html file.
<!-- Apple button -->
<div class="row">
<div class="col-md-12 d-flex justify-content-center align-self-center">
<div id="appleid-signin" class="signin-button" data-color="black" data-border="true" data-type="sign in"></div>
</div>
</div>
sign-in-container.component.ts
/**
* On Apple button click
*/
onSocialAppleClick() {
console.log("inside social app")
const appleParams = {
clientId : '////////',
redirectURI : 'https://ppl-dev--fe--phx2.appspot.com/ajax/redirect',
scope : 'name email',
state : 'signin',
usePopup : true
};
this.appleLoginService.signIn();
}
apple-login.service.ts
import { Injectable } from '#angular/core';
import { AppleParams } from '../models/server-models/apple-params-interface';
declare var require: any
#Injectable({
providedIn: 'root'
})
export class AppleLoginService {
private readonly appleScriptUrl: string = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
private ready: Promise<boolean> = new Promise(resolve => {
if (typeof window !== 'undefined') {
const script = require('scriptjs');
script(this.appleScriptUrl, () => resolve(true));
} else {
resolve(false);
}
}
);
/**
* Error details
*/
signIn() {
console.log("inside sign in")
throw new Error('Method not implemented.');
}
constructor() {
this.ready.then(isReady => {
if (isReady) {
this.init();
}
});
}
/**
* Call init method
*/
private init(): void {
console.log("inside init method")
window['AppleID'].auth.init({
clientId: 'com.pizzapizza.web',
scope: 'name email',
redirectURI: 'https://ppl-dev--fe--phx2.appspot.com/ajax/redirect',
state: 'sign in'
});
window.addEventListener('AppleIDSignInOnSuccess', (event) => {
console.log('Got a message: ' + JSON.stringify(event));
})
}
}
When I click on the apple button from the html page, it redirects me to the appleid.apple.com
and ask for the appleid and password. After authenticating the credentials apple servers asks to redirect to the redirectURI (https://ppl-dev--fe--phx2.appspot.com/ajax/redirect) provided in the params.
But when this gets redirected i can only see the json data APPLE RESPONSE - JSON rather than opening the website with user logged in.
Apple will send a POST request directly to your redirect URI, depending on the response of that request you will be able to redirect the user back to the angular app. From what I'm reading you are listening to an event from that post request but the redirectURI is not emitting an event to the angular app window, thats why you are only able to see a json file

My Vue PWA app shows white blank page on iOS

I am currently working one a Vuejs PWA app (using Vue CLI 3). My app works fine on Android, Windows, and macOS, but it only shows a white blank page on ios. More specifically, when I use an iPhone and access my app with Safari or Chrome, it all shows a white page. When I add my app to the home screen of the iPhone, when I open it up, it still shows a white page.
this is link to my app.
White blank screen
I have tried many workarounds here but it not work.
here are some parts of my code:
vue.config.js
module.exports = {
transpileDependencies: ['vuetify'],
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: 'src/config/firebase-messaging-sw.js',
exclude: [/\.map$/, /_redirects/],
},
manifestOptions: {
start_url: 'index.html',
},
name: 'AppName',
appleMobileWebAppCapable: 'yes',
},
};
router
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "RenterMainView",
component: RenterView,
children: [
{
path: "index.html",
name: "Home",
component: Home,
meta: { guest: true },
alias: ""
},
{
path: "detail/:typeId",
name: "HostelDetail",
component: HostelDetail,
meta: { guest: true }
}
]
}
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (window.$cookies.get('jwt') === null) {
// not logged in
next({
name: 'Login',
params: { nextUrl: to.path, preUrl: from.path },
});
} else {
// logged in
const role = window.$cookies.get('role');
if (to.matched.some((record) => record.meta.is_vendor)) {
if (role === 'vendors') {
next();
} else {
next(from.path);
}
} else if (to.matched.some((record) => record.meta.is_admin)) {
if (role === 'admins') {
next();
} else {
next(from.path);
}
} else if (to.matched.some((record) => record.meta.is_renter)) {
if (role === 'renters') {
next();
} else {
next(from.path);
}
} else {
next();
}
}
} else if (to.matched.some((record) => record.meta.guest)) {
// not require authen
next();
} else {
// not require authen
next();
}
});
Try changing the start_url
I found that on
Chrome Windows
Chrome MacOS
Android
I was OK to use quite a wide variety of start_url values, such as the "index.html" that you have, or "/index.html", etc.
However on iOS, I had to use
start_url: "."
The other values were fine on the other platforms, but gave a blank white screen on iOS.
Try creating a blank PWA with the Vue CLI
Does that work correctly on iOS?
Then step by step change it to contain your app.
Find out where it breaks.
That's how I found the start_url issue.
I hope that this could help someone. In this project, I make an PWA app using Vue, and I use Firebase Cloud Messagging to send notification from server to client. Unfortunaly, due to some restrictions on iOS, FCM doesn't work on it, that is why the application show a white page on iOS. So, the solution is to disable FCM on iOS
if (firebase.messaging.isSupported()) { // your code go here }
using above code to disable FCM on firebase service worker file

Redirect to requested URL if already authorized in VueJS Router

I'm trying to understand the VueJS router model by building this tutorial app. The app redirects you to the home page if you try to open a direct link like https://example.com/meetups even if you already logged in and authorized. Why is that and how to open the requested URL instead?
auth-guard.js
import {store} from '../store'
export default (to, from, next) => {
if (store.getters.user) {
next()
} else {
next('/signin')
}
}
index.js
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/signup',
name: 'Signup',
component: Signup
},
{
path: '/signin',
name: 'Signin',
component: Signin
},
{
path: '/meetups',
name: 'Meetups',
component: Meetups,
beforeEnter: AuthGuard
},
{
path: '/meetup/new',
name: 'CreateMeetup',
component: CreateMeetup,
beforeEnter: AuthGuard
},
{
path: '/meetups/:id',
name: 'Meetup',
props: true,
component: Meetup,
beforeEnter: AuthGuard
},
{
path: '/profile',
name: 'Profile',
component: Profile,
beforeEnter: AuthGuard
}
],
mode: 'history'
})
The auth-guard.js will redirect someone to the sign in page if the store user is null.
When does the store user get updated?
Inside main.js:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.$store.dispatch('autoSignIn', user)
}
})
the onAuthStateChanged method is async, meaning that it might finish executing after you have asked the browser to go to a page that is guarded by auth-guard.js.
This is mostly what happens if you open a new tab or window and type in the url of a guarded page.
This behaviour would work properly if first, the site is fully loaded on an unguarded page (let's say /signin) and then the user would try to click on a guarded page (let's say /meetups). By the time the user clicks on the link, there is a good chance the onAuthStateChanged method will have returned and commited to the store ( this.$store.dispatch('autoSignIn', user) ), allowing onAuthStateChanged to execute properly.
EDIT
One way to solve this problem would be to instanciate the Vue app only once the onAuthStateChanged has returned a user like so:
main.js
firebase.initializeApp({
apiKey: 'AIzaSyCFYWd6FpR53u4hSPXQSjOYeZNPF1FxG2M',
authDomain: 'yt-devmeetup.firebaseapp.com',
databaseURL: 'https://yt-devmeetup.firebaseio.com',
projectId: 'yt-devmeetup',
storageBucket: 'gs://yt-devmeetup.appspot.com'
})
firebase.auth().onAuthStateChanged((user) => {
if (user) {
store.dispatch('autoSignIn', user)
store.dispatch('fetchUserData')
}
new Vue({
el: '#app',
router,
store,
render: h => h(App),
created() {
this.$store.dispatch('loadMeetups')
}
})
})

Vue - watch url without VueRouter

Is it possible to react on URL changes in a Vue component, without including VueRouter?
In case VueRouter is present, we can watch $route, however, my application does not rely on VueRouter.
export default {
watch: { '$route': route => console.log(window.location.href) }
}
Before I used vue router, I did something like this...
data: function() {
return {
route: window.location.hash,
page: 'home'
}
},
watch: {
route: function(){
this.page = window.location.hash.split("#/")[1];
}
}

Login Authentication with Devise (rails) & Angular

I currently have a mobile application where you can create issues, and view a list of issues others have created around your location.
The mobile app is is talking to a rails server and properly creating issues, and I have followed this guide covering Authentication with Rails & Devise.
In my controllers/app.js file, I have a local variable stored isLoggedIn that is set to false by default. When the application is loaded, I check to see whether the variable is true and if so, send the user to app.issues. Otherwise, the user is sent to app.auth.login.
$scope.$storage = $localStorage.$default({
isLoggedIn: false
});
$scope.$watch('$storage.isLoggedIn', function() {
if ($scope.$storage.isLoggedIn){
console.log('is logged in');
$state.go('app.issues');
}
else {
console.log('isnt logged in');
$state.go('app.auth.login');
}
});
Here is my root app.js file in my js folder.
angular.module('orangecone', ['ionic', 'orangecone.controllers', 'orangecone.services', 'ngCordova', 'ngStorage', 'ngResource'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.value('Constants', {
serverUrl: 'http://localhost:3000/'
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$stateProvider
// setup an abstract state for the tabs directive
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('app.issues', {
url: '/issues',
views: {
'app-issues': {
templateUrl: 'templates/issues.html',
controller: 'IssuesCtrl'
}
}
})
.state('app.issue', {
url: '/issues/:issueId',
views: {
'app-issues': {
templateUrl: 'templates/issue.html',
controller: 'IssueCtrl'
}
}
})
.state('app.auth', {
url: '/auth',
abstract: true,
templateUrl: 'templates/auth/tabs.html'
})
.state('app.auth.login', {
url: '/login',
views: {
'login': {
templateUrl: 'templates/auth/login.html',
controller: 'AuthCtrl'
}
}
})
.state('app.auth.register', {
url: '/register',
views: {
'register': {
templateUrl: 'templates/auth/register.html',
controller: 'AuthCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/auth/login');
});
I have a waning feeling that I am overlooking something rather trivial. The application always console.logs logged in even though the rails server is wiped and there are no users in the system at all. The application should be redirecting the user to app/auth/login but never does. Whenever I type this URL into the browser it also redirects me to the app/issues page.
Any thoughts or opinions would be greatly appreciated.

Resources