mirror of https://github.com/msgbyte/tailchat
refactor(admin-next): use builtin createAuthProvider replace custom auth provider
parent
11154f735b
commit
ab6dc6275d
@ -1,66 +1,8 @@
|
|||||||
import type { AuthProvider } from 'tushan';
|
import { AuthProvider, createAuthProvider } from 'tushan';
|
||||||
|
|
||||||
export const authStorageKey = 'tailchat:admin:auth';
|
export const authStorageKey = 'tailchat:admin:auth';
|
||||||
|
|
||||||
export const authProvider: AuthProvider = {
|
export const authProvider: AuthProvider = createAuthProvider({
|
||||||
login: ({ username, password }) => {
|
authStorageKey,
|
||||||
const request = new Request('/admin/api/login', {
|
loginUrl: '/admin/api/login',
|
||||||
method: 'POST',
|
});
|
||||||
body: JSON.stringify({ username, password }),
|
|
||||||
headers: new Headers({ 'Content-Type': 'application/json' }),
|
|
||||||
});
|
|
||||||
|
|
||||||
return fetch(request)
|
|
||||||
.then((response) => {
|
|
||||||
return response.json();
|
|
||||||
})
|
|
||||||
.then((auth) => {
|
|
||||||
console.log(auth);
|
|
||||||
localStorage.setItem(authStorageKey, JSON.stringify(auth));
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
throw new Error('Login Failed');
|
|
||||||
});
|
|
||||||
},
|
|
||||||
logout: () => {
|
|
||||||
localStorage.removeItem(authStorageKey);
|
|
||||||
return Promise.resolve();
|
|
||||||
},
|
|
||||||
checkAuth: () => {
|
|
||||||
const auth = localStorage.getItem(authStorageKey);
|
|
||||||
if (auth) {
|
|
||||||
try {
|
|
||||||
const obj = JSON.parse(auth);
|
|
||||||
if (obj.expiredAt && Date.now() < obj.expiredAt) {
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
} catch (err) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.reject();
|
|
||||||
},
|
|
||||||
checkError: (error) => {
|
|
||||||
const status = error.status;
|
|
||||||
if (status === 401 || status === 403) {
|
|
||||||
localStorage.removeItem(authStorageKey);
|
|
||||||
return Promise.reject();
|
|
||||||
}
|
|
||||||
|
|
||||||
// other error code (404, 500, etc): no need to log out
|
|
||||||
return Promise.resolve();
|
|
||||||
},
|
|
||||||
getIdentity: () => {
|
|
||||||
const { username } = JSON.parse(
|
|
||||||
localStorage.getItem(authStorageKey) ?? '{}'
|
|
||||||
);
|
|
||||||
if (!username) {
|
|
||||||
return Promise.reject();
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.resolve({
|
|
||||||
id: username,
|
|
||||||
fullName: username,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
getPermissions: () => Promise.resolve(''),
|
|
||||||
};
|
|
||||||
|
Loading…
Reference in New Issue