Hangar/frontend/plugins/auth.ts

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-01-22 11:11:24 +08:00
import { Context } from '@nuxt/types';
import { Inject } from '@nuxt/types/app';
import { User } from 'hangar-api';
2021-02-05 04:30:47 +08:00
const createAuth = ({ app: { $cookies }, $axios, store, $api, redirect }: Context) => {
2021-01-22 11:11:24 +08:00
class Auth {
login(redirect: string): void {
$cookies.set('returnRoute', redirect, {
path: '/',
maxAge: 120,
secure: process.env.NODE_ENV === 'production',
2021-01-22 11:11:24 +08:00
});
2021-01-23 03:20:03 +08:00
location.replace(`/login?returnUrl=http://localhost:3000${redirect}`);
2021-01-22 11:11:24 +08:00
}
2021-02-03 07:47:15 +08:00
processLogin(token: string): Promise<void> {
2021-01-22 11:11:24 +08:00
store.commit('auth/SET_AUTHED', true);
2021-02-03 07:47:15 +08:00
return this.updateUser(token);
2021-01-22 11:11:24 +08:00
}
2021-02-05 04:30:47 +08:00
async logout(shouldRedirect = true): Promise<void> {
store.commit('auth/SET_USER', null);
store.commit('auth/SET_TOKEN', null);
store.commit('auth/SET_AUTHED', false);
2021-02-05 04:30:47 +08:00
await $axios.get('/invalidate');
$cookies.remove('HangarAuth_REFRESH', {
path: '/',
});
2021-02-05 04:30:47 +08:00
if (shouldRedirect) {
// TODO redirect home because they may have been on authed page and a reload would just show an error
redirect('/');
2021-01-31 10:00:11 +08:00
}
}
2021-02-03 07:47:15 +08:00
updateUser(token: string): Promise<void> {
2021-01-31 10:00:11 +08:00
return $api
2021-02-03 07:47:15 +08:00
.requestInternalWithToken<User>('users/@me', token)
2021-01-31 10:00:11 +08:00
.then((user) => {
store.commit('auth/SET_USER', user);
})
2021-02-03 07:47:15 +08:00
.catch((err) => {
console.log(err);
this.logout(process.client);
2021-02-03 07:47:15 +08:00
});
2021-01-22 11:11:24 +08:00
}
}
return new Auth();
};
type authType = ReturnType<typeof createAuth>;
declare module 'vue/types/vue' {
interface Vue {
$auth: authType;
}
}
declare module '@nuxt/types' {
interface NuxtAppOptions {
$auth: authType;
}
interface Context {
$auth: authType;
}
}
declare module 'vuex/types/index' {
2021-01-31 10:00:11 +08:00
// eslint-disable-next-line no-unused-vars,@typescript-eslint/no-unused-vars
2021-01-22 11:11:24 +08:00
interface Store<S> {
$auth: authType;
}
}
export default (ctx: Context, inject: Inject) => {
inject('auth', createAuth(ctx));
};