wraith/frontend/stores/auth.store.ts
Vantz Stockwell 6d76558bc3 feat: multi-user isolation with admin/user roles
Full per-user data isolation across all tables:
- Migration adds userId FK to hosts, host_groups, credentials, ssh_keys,
  connection_logs. Backfills existing data to admin@wraith.local.
- All services scope queries by userId from JWT (req.user.sub).
  Users can only see/modify their own data. Cross-user access returns 403.
- Two roles: admin (full access + user management) and user (own data only).
- Admin endpoints: list/create/edit/delete users, reset password, reset TOTP.
  Protected by AdminGuard. Admins cannot delete themselves or remove own role.
- JWT payload now includes role. Frontend auth store exposes isAdmin getter.
- Seed script fixed: checks for admin@wraith.local specifically (not any user).
  Uses upsert, seeds with role=admin. Migration cleans up duplicate users.
- Connection logs now attributed to the connecting user via WS auth.
- Deleting a user CASCADEs to all their hosts, credentials, keys, and logs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 12:57:38 -04:00

63 lines
1.5 KiB
TypeScript

import { defineStore } from 'pinia'
interface User {
id: number
email: string
displayName: string | null
role: string
totpEnabled?: boolean
}
interface LoginResponse {
access_token?: string
user?: User
requires_totp?: boolean
}
export const useAuthStore = defineStore('auth', {
state: () => ({
token: localStorage.getItem('wraith_token') || '',
user: null as User | null,
}),
getters: {
isAuthenticated: (state) => !!state.token,
isAdmin: (state) => state.user?.role === 'admin',
},
actions: {
async login(email: string, password: string, totpCode?: string): Promise<LoginResponse> {
const body: Record<string, string> = { email, password }
if (totpCode) body.totpCode = totpCode
const res = await $fetch<LoginResponse>('/api/auth/login', {
method: 'POST',
body,
})
if (res.requires_totp) {
return { requires_totp: true }
}
this.token = res.access_token!
this.user = res.user!
localStorage.setItem('wraith_token', res.access_token!)
return res
},
logout() {
this.token = ''
this.user = null
localStorage.removeItem('wraith_token')
navigateTo('/login')
},
async fetchProfile() {
if (!this.token) return
try {
this.user = await $fetch('/api/auth/profile', {
headers: { Authorization: `Bearer ${this.token}` },
})
} catch {
this.logout()
}
},
},
})