Last active
October 22, 2019 08:30
-
-
Save tajuszk/60051340f579d61ca3447ecef0890ac6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue' | |
import Router from 'vue-router' | |
// 認証済みの状態で入れるページ | |
import Home from '@/components/Home' | |
// 認証前の状態で入れるページ | |
import Welcome from '@/components/Welcome' | |
import firebase from 'firebase' | |
Vue.use(Router) | |
const router = new Router({ | |
routes: [ | |
{ | |
path: '/', | |
name: 'Welcome', | |
component: Welcome | |
}, | |
{ | |
path: '/home', | |
name: 'Home', | |
component: Home, | |
meta: { | |
requiresAuth: true // 「認証が必要」ということを示すフラグ | |
} | |
}, | |
] | |
}) | |
// ルーティングする時のチェック | |
router.beforeEach((to, from, next) => { | |
// リダイレクト先が設定されていれば取得しておく | |
let redirect = null | |
if (to.query.redirect) { | |
redirect = to.query.redirect | |
} | |
// 現在ログインしているユーザーを取得する | |
firebase.auth().onAuthStateChanged(user => { | |
// ユーザが認証済みの場合(userが取得できた場合) | |
if (user) { | |
// リダイレクトが設定されていればリダイレクト先に | |
if (redirect != null) { | |
next(redirect) | |
return | |
} | |
// Welcomeページに入る時、ログインされているならHome画面に行く | |
if(to.name == "Welcome") { | |
next({ | |
name: 'Home', | |
}) | |
} | |
// 認証済みならどこでも行ってもOK | |
next() | |
} | |
// ユーザが認証されていない場合 | |
else { | |
// 認証が必要かチェックし、必要であればWelcomeページに強制遷移 | |
if(to.matched.some(record => record.meta.requiresAuth)){ | |
next({ | |
name: 'Welcome', | |
query: { | |
redirect: to.fullPath | |
}, | |
}) | |
} | |
// 認証が必要ない場合はそのままでOK | |
next() | |
} | |
}) | |
}) | |
export default router |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment