41 lines
1007 B
JavaScript
41 lines
1007 B
JavaScript
|
import { defineStore } from 'pinia'
|
||
|
import { computed, ref } from 'vue'
|
||
|
|
||
|
export const useSession = defineStore('session', () => {
|
||
|
let pubkey = ref(null)
|
||
|
// eslint-disable-next-line vue/no-ref-as-operand
|
||
|
const isAuthenticated = computed(() => !!pubkey)
|
||
|
|
||
|
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)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function checkSession () {
|
||
|
const url = window.origin + '/api/session'
|
||
|
return fetch(url, {
|
||
|
credentials: 'include'
|
||
|
})
|
||
|
.then(r => {
|
||
|
const body = r.json()
|
||
|
pubkey = body.pubkey
|
||
|
return body
|
||
|
})
|
||
|
}
|
||
|
|
||
|
function login () {
|
||
|
const url = window.origin + '/api/login'
|
||
|
return fetch(url, { credentials: 'include' }).then(r => r.json())
|
||
|
}
|
||
|
|
||
|
return { pubkey, isAuthenticated, init, checkSession, login }
|
||
|
})
|