6c86f0f571
- integrated request-module into module registry - moved backend into modules/request-module - added manifest.json and module.py - implemented dynamic router mounting - implemented dynamic static mounting - removed direct dependencies from platform core - verified startup with request-module - verified startup without request-module - added implementation_report_003.md
77 lines
2.0 KiB
TypeScript
77 lines
2.0 KiB
TypeScript
import { createContext, useContext, useState, useEffect } from 'react'
|
|
import type { ReactNode } from 'react'
|
|
import axios from 'axios'
|
|
import type { User } from '../types'
|
|
|
|
const TOKEN_KEY = 'sd_token' // Service Desk specific key
|
|
|
|
interface AuthContextType {
|
|
user: User | null
|
|
loading: boolean
|
|
setToken: (token: string) => void
|
|
logout: () => void
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const [user, setUser] = useState<User | null>(null)
|
|
const [loading, setLoading] = useState(true)
|
|
|
|
useEffect(() => {
|
|
// Check for token in URL (from platform iframe)
|
|
const params = new URLSearchParams(window.location.search)
|
|
const urlToken = params.get('token')
|
|
if (urlToken) {
|
|
localStorage.setItem(TOKEN_KEY, urlToken)
|
|
// Clean URL but keep the path
|
|
window.history.replaceState({}, '', window.location.pathname)
|
|
}
|
|
|
|
const token = localStorage.getItem(TOKEN_KEY)
|
|
if (!token) {
|
|
setLoading(false)
|
|
return
|
|
}
|
|
|
|
axios.get('/api/v1/auth/me', {
|
|
headers: { Authorization: `Bearer ${token}` }
|
|
})
|
|
.then(res => setUser(res.data))
|
|
.catch(() => {
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
setUser(null)
|
|
})
|
|
.finally(() => setLoading(false))
|
|
}, [])
|
|
|
|
const setToken = (token: string) => {
|
|
localStorage.setItem(TOKEN_KEY, token)
|
|
axios.get('/api/v1/auth/me', {
|
|
headers: { Authorization: `Bearer ${token}` }
|
|
})
|
|
.then(res => setUser(res.data))
|
|
.catch(() => {
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
setUser(null)
|
|
})
|
|
}
|
|
|
|
const logout = () => {
|
|
localStorage.removeItem(TOKEN_KEY) // Only remove SD token
|
|
setUser(null)
|
|
}
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ user, loading, setToken, logout }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useAuth() {
|
|
const ctx = useContext(AuthContext)
|
|
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
|
|
return ctx
|
|
}
|