Files
directus/app/src/auth.ts
Rijk van Zanten dbf35a1736 Add ability to share items with people outside the platform (#10663)
* Add directus_shares

* Don't check for usage limit on refresh

* Add all endpoints to the shares controller

* Move route `/auth/shared` to `/shared/auth`

* Add password protection

* Add `share` action in permissions

* Add `shares/:pk/info`

* Start on shared-view

* Add basic styling for full shared view

* Fixed migrations

* Add inline style for shared view

* Allow title override

* Finish /info endpoint for shares

* Add basic UUID validation to share/info endpont

* Add UUID validation to other routes

* Add not found state

* Cleanup /extract/finish share login endpoint

* Cleanup auth

* Added `share_start` and `share_end`

* Add share sidebar details.

* Allow share permissions configuration

* Hide the `new_share` button for unauthorized users

* Fix uses_left displayed value

* Show expired / upcoming shares

* Improved expired/upcoming styling

* Fixed share login query

* Fix check-ip and get-permissions middlewares behaviour when role is null

* Simplify cache key

* Fix typescript linting issues

* Handle app auth flow for shared page

* Fixed /users/me response

* Show when user is authenticated

* Try showing item drawer in shared page

* Improved shared card styling

* Add shares permissions and change share card styling

* Pull in schema/permissions on share

* Create getPermissionForShare file

* Change getPermissionsForShare signature

* Render form + item on share after auth

* Finalize public front end

* Handle fake o2m field in applyQuery

* [WIP]

* New translations en-US.yaml (Bulgarian) (#10585)

* smaller label height (#10587)

* Update to the latest Material Icons (#10573)

The icons are based on https://fonts.google.com/icons

* New translations en-US.yaml (Arabic) (#10593)

* New translations en-US.yaml (Arabic) (#10594)

* New translations en-US.yaml (Portuguese, Brazilian) (#10604)

* New translations en-US.yaml (French) (#10605)

* New translations en-US.yaml (Italian) (#10613)

* fix M2A list not updating (#10617)

* Fix filters

* Add admin filter on m2o role selection

* Add admin filter on m2o role selection

* Add o2m permissions traversing

* Finish relational tree permissions generation

* Handle implicit a2o relation

* Update implicit relation regex

* Fix regex

* Fix implicitRelation unnesting for new regex

* Fix implicitRelation length check

* Rename m2a to a2o internally

* Add auto-gen permissions for a2o

* [WIP] Improve share UX

* Add ctx menu options

* Add share dialog

* Add email notifications

* Tweak endpoint

* Tweak file interface disabled state

* Add nicer invalid state to password input

* Dont return info for expired/upcoming shares

* Tweak disabled state for relational interfaces

* Fix share button for non admin roles

* Show/hide edit/delete based on permissions to shares

* Fix imports of mutationtype

* Resolve (my own) suggestions

* Fix migration for ms sql

* Resolve last suggestion

Co-authored-by: Oreilles <oreilles.github@nitoref.io>
Co-authored-by: Oreilles <33065839+oreilles@users.noreply.github.com>
Co-authored-by: Ben Haynes <ben@rngr.org>
Co-authored-by: Thien Nguyen <72242664+tatthien@users.noreply.github.com>
Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com>
2021-12-23 18:51:59 -05:00

189 lines
5.1 KiB
TypeScript

import api from '@/api';
import { dehydrate, hydrate } from '@/hydrate';
import { router } from '@/router';
import { useAppStore } from '@/stores';
import { RouteLocationRaw } from 'vue-router';
import { idleTracker } from './idle';
import { DEFAULT_AUTH_PROVIDER } from '@/constants';
type LoginCredentials = {
identifier?: string;
email?: string;
password?: string;
otp?: string;
share?: string;
};
type LoginParams = {
credentials: LoginCredentials;
provider?: string;
share?: boolean;
};
function getAuthEndpoint(provider?: string, share?: boolean) {
if (share) return '/shares/auth';
if (provider === DEFAULT_AUTH_PROVIDER) return '/auth/login';
return `/auth/login/${provider}`;
}
export async function login({ credentials, provider, share }: LoginParams): Promise<void> {
const appStore = useAppStore();
const response = await api.post<any>(getAuthEndpoint(provider, share), {
...credentials,
mode: 'cookie',
});
const accessToken = response.data.data.access_token;
// Add the header to the API handler for every request
api.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
// Refresh the token 10 seconds before the access token expires. This means the user will stay
// logged in without any noticeable hiccups or delays
// setTimeout breaks with numbers bigger than 32bits. This ensures that we don't try refreshing
// for tokens that last > 24 days. Ref #4054
if (response.data.data.expires <= 2100000000) {
refreshTimeout = setTimeout(() => refresh(), response.data.data.expires - 10000);
}
appStore.accessTokenExpiry = Date.now() + response.data.data.expires;
appStore.authenticated = true;
await hydrate();
}
let refreshTimeout: any;
let idle = false;
let isRefreshing = false;
let firstRefresh = true;
// Prevent the auto-refresh when the app isn't in use
idleTracker.on('idle', () => {
clearTimeout(refreshTimeout);
idle = true;
});
idleTracker.on('hide', () => {
clearTimeout(refreshTimeout);
idle = true;
});
// Restart the autorefresh process when the app is used (again)
idleTracker.on('active', () => {
if (idle === true) {
refresh();
idle = false;
}
});
idleTracker.on('show', () => {
if (idle === true) {
refresh();
idle = false;
}
});
export async function refresh({ navigate }: LogoutOptions = { navigate: true }): Promise<string | undefined> {
// Allow refresh during initial page load
if (firstRefresh) firstRefresh = false;
// Skip if not logged in
else if (!api.defaults.headers.common['Authorization']) return;
// Prevent concurrent refreshes
if (isRefreshing) return;
const appStore = useAppStore();
// Skip refresh if access token is still fresh
if (appStore.accessTokenExpiry && Date.now() < appStore.accessTokenExpiry - 10000) {
// Set a fresh timeout as it is cleared by idleTracker's idle or hide event
clearTimeout(refreshTimeout);
refreshTimeout = setTimeout(() => refresh(), appStore.accessTokenExpiry - 10000 - Date.now());
return;
}
isRefreshing = true;
try {
const response = await api.post<any>('/auth/refresh', undefined, {
transformRequest(data, headers) {
// This seems wrongly typed in Axios itself..
delete (headers?.common as unknown as Record<string, string>)?.['Authorization'];
return data;
},
});
const accessToken = response.data.data.access_token;
// Add the header to the API handler for every request
api.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
// Refresh the token 10 seconds before the access token expires. This means the user will stay
// logged in without any notable hiccups or delays
clearTimeout(refreshTimeout);
// setTimeout breaks with numbers bigger than 32bits. This ensures that we don't try refreshing
// for tokens that last > 24 days. Ref #4054
if (response.data.data.expires <= 2100000000) {
refreshTimeout = setTimeout(() => refresh(), response.data.data.expires - 10000);
}
appStore.accessTokenExpiry = Date.now() + response.data.data.expires;
appStore.authenticated = true;
return accessToken;
} catch (error: any) {
await logout({ navigate, reason: LogoutReason.SESSION_EXPIRED });
} finally {
isRefreshing = false;
}
}
export enum LogoutReason {
SIGN_OUT = 'SIGN_OUT',
SESSION_EXPIRED = 'SESSION_EXPIRED',
}
export type LogoutOptions = {
navigate?: boolean;
reason?: LogoutReason;
};
/**
* Everything that should happen when someone logs out, or is logged out through an external factor
*/
export async function logout(optionsRaw: LogoutOptions = {}): Promise<void> {
const appStore = useAppStore();
const defaultOptions: Required<LogoutOptions> = {
navigate: true,
reason: LogoutReason.SIGN_OUT,
};
delete api.defaults.headers.common['Authorization'];
clearTimeout(refreshTimeout);
const options = { ...defaultOptions, ...optionsRaw };
// Only if the user manually signed out should we kill the session by hitting the logout endpoint
if (options.reason === LogoutReason.SIGN_OUT) {
await api.post(`/auth/logout`);
}
appStore.authenticated = false;
await dehydrate();
if (options.navigate === true) {
const location: RouteLocationRaw = {
path: `/login`,
query: { reason: options.reason },
};
router.push(location);
}
}