42 lines
1.0 KiB
JavaScript
Raw Normal View History

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useSession = defineStore('session', () => {
2023-11-07 09:48:01 +01:00
const pubkey = ref(null)
const isAuthenticated = computed(() => !!pubkey.value)
2023-11-07 10:15:53 +01:00
const initialized = ref(false)
async function init () {
try {
const { pubkey } = await checkSession()
if (pubkey) {
console.log('authenticated as', pubkey)
return
}
console.log('unauthenticated')
} catch (err) {
console.error('error:', err.reason || err)
}
2023-11-07 10:15:53 +01:00
initialized.value = true
}
function checkSession () {
const url = window.origin + '/api/session'
return fetch(url, {
credentials: 'include'
})
2023-11-07 09:48:01 +01:00
.then(async r => {
const body = await r.json()
pubkey.value = body.pubkey
return body
})
}
function login () {
const url = window.origin + '/api/login'
return fetch(url, { credentials: 'include' }).then(r => r.json())
}
2023-11-07 10:15:53 +01:00
return { pubkey, isAuthenticated, initialized, init, checkSession, login }
})