first commit
This commit is contained in:
43
src/stores/auth.ts
Normal file
43
src/stores/auth.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { ref, computed } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { dispatchNotification } from '@/components/Notification'
|
||||
import router from '@/router'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
// token from localStorage
|
||||
const token = ref(localStorage.getItem('token') || '')
|
||||
// create a shared state
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const isLoading = ref(false)
|
||||
const isLoggedIn = computed(() => token.value !== '')
|
||||
|
||||
// define your actions
|
||||
function login() {
|
||||
if (username.value == '' || password.value == '') {
|
||||
dispatchNotification({ title: 'Perhatian', content: 'Username atau password tidak boleh kosong', type: 'warning' })
|
||||
} else {
|
||||
isLoading.value = true
|
||||
setTimeout(() => {
|
||||
isLoading.value = false
|
||||
if (username.value == 'demo' && password.value == 'demo') {
|
||||
// store token in localStorage
|
||||
localStorage.setItem('token', 'secret-token')
|
||||
dispatchNotification({ title: 'Berhasil', content: 'Login berhasil, selamat datang kembali!', type: 'success' })
|
||||
// redirect to home page after login
|
||||
// router.replace('/')
|
||||
router.go(0)
|
||||
} else {
|
||||
dispatchNotification({ title: 'Login Gagal', content: 'Username atau password salah', type: 'error' })
|
||||
}
|
||||
}, 3000)
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('token')
|
||||
}
|
||||
|
||||
// expose everything
|
||||
return { token, username, password, isLoggedIn, login, logout, isLoading }
|
||||
})
|
Reference in New Issue
Block a user