Frontend Nuxt Login 개발
Nuxt middleware 설명
Nuxt 공식 사이트 middleware
Pinia 설명
Pinia 공식 사이트 core-concepts
00) 사전 파일 추가
00-01) 백엔드 프레임워크
demo1_add_security
00-02) 프론트 프레임워크
login.zip
- public/images/login.png
- pages/admin/Login.vue
01) mod nuxt.config.ts
runtimeConfig: {
// Private keys are only available on the server
// Public keys that are exposed to the client
public: {
apiBase: 'http://localhost:8080',
},
},
Nuxt 공식 사이트 runtime-config
02) create store/auth.ts
interface UserPayloadInterface {
username: string
password: string
}
export const useAuthStore = defineStore('auth', {
state: () => ({
authenticated: useCookie('authenticated'),
accessToken: useCookie('accessToken'),
refreshToken: useCookie('refreshToken'),
}),
actions: {
async authenticateUser({ username, password }: UserPayloadInterface) {
const result = {
data: {},
pending: {},
error: {},
}
const options = {
method: 'post',
headers: { 'Content-Type': 'application/json' },
}
const { data, pending, error }: any = await usePostFetch('/security/jwt/authenticate', {
username,
password,
}, options, false)
result.data = data
result.pending = pending
result.error = error
if (data.value) {
const accessTokenVal = data?.value?.data?.accessToken
const refreshTokenVal = data?.value?.data?.refreshToken
useCookie('accessToken').value = accessTokenVal
useCookie('refreshToken').value = refreshTokenVal
useCookie('authenticated').value = 'true'
this.accessToken = accessTokenVal
this.refreshToken = refreshTokenVal
this.authenticated = 'true'
}
return result
},
},
})
03) create auth.global.ts
export default defineNuxtRouteMiddleware((to: any) => {
const accessToken = useCookie('accessToken') // get token from cookies
// if token exists and url is /login redirect to homepage
if (accessToken.value && to?.path === '/admin/Login') {
useRouter().replace('/')
return
}
// if token doesn't exist redirect to log in
if (!accessToken.value && to?.path !== '/admin/Login') {
abortNavigation()
return navigateTo('/admin/Login')
}
})