All checks were successful
Dev Build & Deploy Portal / build-deploy (push) Successful in 2m34s
85 lines
2.3 KiB
TypeScript
85 lines
2.3 KiB
TypeScript
import { computed } from 'vue'
|
|
import { useAuthStore } from '@/stores/authStore'
|
|
import { usePrefeituraStore } from '@/stores/prefeituraStore'
|
|
|
|
interface MeResponse {
|
|
name: string
|
|
documento: string
|
|
email: string
|
|
roles: string[]
|
|
}
|
|
|
|
const FETCH_HEADERS = { 'X-Requested-With': 'fetch' }
|
|
|
|
const TEMPLATE_COLORS: Record<string, string> = {
|
|
tutoia: 'f97316',
|
|
amber: 'f59e0b',
|
|
blue: '3b82f6',
|
|
indigo: '6366f1',
|
|
violet: '8b5cf6',
|
|
emerald: '10b981',
|
|
teal: '14b8a6',
|
|
rose: 'f43f5e',
|
|
zinc: '71717a',
|
|
}
|
|
|
|
export function useAuth() {
|
|
const store = useAuthStore()
|
|
const router = useRouter()
|
|
|
|
async function login(documento?: string, returnTo?: string) {
|
|
const template = usePrefeituraStore().template as string | null
|
|
const primary = template ? (TEMPLATE_COLORS[template] ?? '') : ''
|
|
const dark = import.meta.client
|
|
? (window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false)
|
|
: false
|
|
|
|
const res = await $fetch<{ authUrl: string }>('/api/auth/login', {
|
|
method: 'POST',
|
|
headers: FETCH_HEADERS,
|
|
body: { documento, returnTo, primary: primary || undefined, dark },
|
|
})
|
|
if (import.meta.client) {
|
|
window.location.href = res.authUrl
|
|
}
|
|
}
|
|
|
|
async function fetchMe(): Promise<MeResponse | null> {
|
|
try {
|
|
const me = await $fetch<MeResponse>('/api/auth/me')
|
|
store.setUser(me)
|
|
return me
|
|
} catch {
|
|
store.clearUser()
|
|
return null
|
|
}
|
|
}
|
|
|
|
async function logout() {
|
|
try {
|
|
const res = await $fetch<{ logoutUrl: string }>('/api/auth/logout', {
|
|
method: 'POST',
|
|
headers: FETCH_HEADERS,
|
|
})
|
|
store.clearUser()
|
|
if (import.meta.client) {
|
|
window.location.href = res.logoutUrl
|
|
}
|
|
} catch {
|
|
store.clearUser()
|
|
await router.push('/')
|
|
}
|
|
}
|
|
|
|
return {
|
|
user: computed(() => store.user),
|
|
isAuthenticated: computed(() => store.isAuthenticated),
|
|
nomeUsuario: computed(() => store.nomeUsuario),
|
|
documento: computed(() => store.documento),
|
|
roles: computed(() => store.roles),
|
|
login,
|
|
logout,
|
|
fetchMe,
|
|
}
|
|
}
|