2023-11-04 14:31:48 +01:00
|
|
|
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)
|
2023-11-04 14:31:48 +01:00
|
|
|
|
|
|
|
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()
|
2023-11-07 18:55:20 +01:00
|
|
|
if (body.pubkey) {
|
|
|
|
pubkey.value = body.pubkey
|
|
|
|
console.log('authenticated as', body.pubkey)
|
|
|
|
} else console.log('unauthenticated')
|
|
|
|
initialized.value = true
|
2023-11-04 14:31:48 +01:00
|
|
|
return body
|
2023-11-07 18:55:20 +01:00
|
|
|
}).catch(err => {
|
|
|
|
console.error('error:', err.reason || err)
|
2023-11-04 14:31:48 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function login () {
|
|
|
|
const url = window.origin + '/api/login'
|
|
|
|
return fetch(url, { credentials: 'include' }).then(r => r.json())
|
|
|
|
}
|
|
|
|
|
2023-11-07 13:51:33 +01:00
|
|
|
function logout () {
|
|
|
|
const url = window.origin + '/api/logout'
|
|
|
|
return fetch(url, { method: 'POST', credentials: 'include' })
|
|
|
|
.then(async r => {
|
|
|
|
const body = await r.json()
|
|
|
|
if (body.status === 'OK') {
|
|
|
|
pubkey.value = null
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-11-07 18:55:20 +01:00
|
|
|
return { pubkey, isAuthenticated, initialized, checkSession, login, logout }
|
2023-11-04 14:31:48 +01:00
|
|
|
})
|