feat: add loggedIn checks for frontend

This commit is contained in:
wancat committed 2023-09-17 12:29:45 +08:00
1 parent 34c277c886
commit d939b7eb4d
5 files changed
+37 -21

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ const handleLogin = async () => {
async function check() {
const user = username.value.trim()
try {
const res = await api.get('/auth/check', {
const res = await api.get('/auth/check-username', {
params: { username: user },
})
// user not exists, try register
+20 -19
View File
@@ -1,6 +1,7 @@
import { createRouter, createWebHistory } from 'vue-router'
import GamePage from './views/GamePage.vue'
import AuthPage from './views/AuthPage.vue'
import { isLoggedIn } from './utils/auth'
const routes = [
{
@@ -26,24 +27,24 @@ const router = createRouter({
routes,
})
// router.beforeEach((to, from, next) => {
// console.log(to, from)
// const isAuthed = isAuthenticated.value
// // Check if the route requires authentication
// if (to.meta.requiresAuth && !isAuthed) {
// // Check if the user isn't authenticated
// // Redirect to the login page
// next({
// name: 'auth',
// query: { redirect: to.fullPath }, // Optionally pass a redirect parameter
// })
// } else if (to.meta.requiresGuest && isAuthed) {
// next({
// name: 'game', // Or any default authenticated user route
// })
// } else {
// next() // Always call next() at the end
// }
// })
router.beforeEach(async (to, from, next) => {
console.log(to, from)
const loggedIn = await isLoggedIn()
// Check if the route requires authentication
if (to.meta.requiresAuth && !loggedIn) {
// Check if the user isn't authenticated
// Redirect to the login page
next({
name: 'auth',
query: { redirect: to.fullPath }, // Optionally pass a redirect parameter
})
} else if (to.meta.requiresGuest && loggedIn) {
next({
name: 'game', // Or any default authenticated user route
})
} else {
next() // Always call next() at the end
}
})
export default router
+6
View File
@@ -1,5 +1,11 @@
import api from './api'
export async function isLoggedIn() {
const res = await api.get('/auth/check-session')
const { loggedIn } = res.data
return loggedIn
}
export const login = async (username, password) => {
try {
const res = await api.post('/auth/login', { username, password })