add login, register, and auth
This commit is contained in:
parent
9d64ffcb41
commit
29f6b759f8
17 changed files with 436 additions and 55 deletions
70
src/modules/auth.ts
Normal file
70
src/modules/auth.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { reactive, watch, toRefs } from 'vue';
|
||||
import { useIpc } from './ipc';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
access_token: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
authenticating: boolean;
|
||||
user?: User;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
const state = reactive<AuthState>({
|
||||
authenticating: false,
|
||||
user: undefined,
|
||||
error: undefined,
|
||||
});
|
||||
|
||||
const AUTH_KEY = 'crimata_token';
|
||||
|
||||
const token = window.localStorage.getItem(AUTH_KEY);
|
||||
|
||||
if (token) {
|
||||
const { loading, error, data, send } = useIpc('auth-user');
|
||||
|
||||
state.authenticating = true;
|
||||
|
||||
// authenticate token against crimata-platform
|
||||
send([token]);
|
||||
|
||||
watch([loading], () => {
|
||||
if (error.value) {
|
||||
console.log('ERROR: failed authentication')
|
||||
window.localStorage.removeItem(AUTH_KEY);
|
||||
}
|
||||
else if (data.value) {
|
||||
state.user = data.value;
|
||||
}
|
||||
|
||||
state.authenticating = false;
|
||||
})
|
||||
}
|
||||
|
||||
export const useAuth = () => {
|
||||
const setUser = (payload: User, remember: boolean) => {
|
||||
if (remember) {
|
||||
// Save
|
||||
window.localStorage.setItem(AUTH_KEY, payload.access_token);
|
||||
}
|
||||
|
||||
state.user = payload;
|
||||
state.error = undefined;
|
||||
}
|
||||
|
||||
const logout = (): Promise<void> => {
|
||||
window.localStorage.removeItem(AUTH_KEY);
|
||||
return Promise.resolve(state.user = undefined);
|
||||
}
|
||||
|
||||
return {
|
||||
setUser,
|
||||
logout,
|
||||
...toRefs(state), // authenticating, user, error
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue