chore: cleanup un-used exports

This commit is contained in:
Nicolas Meienberger 2023-05-17 21:07:33 +02:00
parent 1e2eb5d65c
commit 072a868ab6
15 changed files with 19 additions and 89 deletions

View file

@ -1,13 +1,7 @@
import * as Router from '../../server/routers/_app';
export type RouterOutput = Router.RouterOutput;
export type { FormField, AppInfo } from '@/server/services/apps/apps.helpers';
export type { AppCategory } from '@/server/services/apps/apps.types';
export type App = Omit<Router.RouterOutput['app']['getApp'], 'info'>;
export type AppWithInfo = Router.RouterOutput['app']['getApp'];
export interface IUser {
name: string;
email: string;
}

View file

@ -121,8 +121,11 @@
"empty-action": "Go to app store"
},
"app-store": {
"title": "App Store",
"search-placeholder": "Search apps",
"category-placeholder": "Select a category"
"category-placeholder": "Select a category",
"no-results": "No app found",
"no-results-subtitle": "Try to refine your search"
},
"app-details": {
"install-success": "App installed successfully",

View file

@ -28,9 +28,9 @@ export const AppStorePage: NextPage = () => {
const tableData = React.useMemo(() => sortTable({ data: data?.apps || [], col: sort, direction: sortDirection, category, search }), [data?.apps, sort, sortDirection, category, search]);
return (
<Layout title="App Store" actions={actions}>
<Layout title={t('title')} actions={actions}>
{(tableData.length > 0 || isLoading) && <AppStoreContainer loading={isLoading} apps={tableData} />}
{tableData.length === 0 && !error && <EmptyPage title="No app found" subtitle="Try to refine your search" />}
{tableData.length === 0 && !error && <EmptyPage title={t('no-results')} subtitle={t('no-results-subtitle')} />}
{error && <ErrorPage error={error.message} />}
</Layout>
);

View file

@ -115,7 +115,7 @@ export const SettingsForm = (props: IProps) => {
<span className="text-muted">{t('apps-repo-hint')}</span>
</div>
<div className="mb-3">
<Input {...register('storagePath')} label={t('storage-path')} error={errors.storagePath?.message} placeholder="Storage path" />
<Input {...register('storagePath')} label={t('storage-path')} error={errors.storagePath?.message} placeholder={t('storage-path')} />
<span className="text-muted">{t('storage-path-hint')}</span>
</div>
<Button loading={loading} type="submit" className="btn-success">

View file

@ -1,35 +0,0 @@
import jwt from 'jsonwebtoken';
import TipiCache from '../../core/TipiCache';
import { getConfig } from '../../core/TipiConfig';
import { getServerAuthSession } from '../get-server-auth-session';
jest.mock('redis');
describe('getServerAuthSession', () => {
it('should return null if no token is provided', async () => {
// @ts-expect-error - wrong res
const result = await getServerAuthSession({ req: { headers: { authorization: null } }, res: {} });
expect(result).toBeNull();
});
it('should return null if an invalid token is provided', async () => {
// @ts-expect-error - wrong res
const result = await getServerAuthSession({ req: { headers: { authorization: 'Bearer invalid_token' } }, res: {} });
expect(result).toBeNull();
});
it('should return null if there is no session id in the cache', async () => {
const validToken = jwt.sign('12', getConfig().jwtSecret);
// @ts-expect-error - wrong res
const result = await getServerAuthSession({ req: { headers: { authorization: `Bearer ${validToken}` } }, res: {} });
expect(result).toBeNull();
});
it('should return the user id and session id if a valid token is provided', async () => {
const validToken = jwt.sign({ id: 12, session: 'session_id' }, getConfig().jwtSecret);
TipiCache.set('session_id', '12');
// @ts-expect-error - wrong res
const result = await getServerAuthSession({ req: { headers: { authorization: `Bearer ${validToken}` } }, res: {} });
expect(result).toEqual({ userId: 12, id: 'session_id' });
});
});

View file

@ -1,33 +0,0 @@
import { type GetServerSidePropsContext } from 'next';
import jwt from 'jsonwebtoken';
import { v4 } from 'uuid';
import { getConfig } from '../core/TipiConfig';
import TipiCache from '../core/TipiCache';
import { Logger } from '../core/Logger';
export const generateSessionId = (prefix: string) => {
return `${prefix}-${v4()}`;
};
export const getServerAuthSession = async (ctx: { req: GetServerSidePropsContext['req']; res: GetServerSidePropsContext['res'] }) => {
const { req } = ctx;
const token = req.headers.authorization?.split(' ')[1];
if (token) {
try {
const decodedToken = jwt.verify(token, getConfig().jwtSecret) as { id: number; session: string };
const userId = await TipiCache.get(decodedToken.session);
if (userId === decodedToken.id.toString()) {
return {
userId: decodedToken.id,
id: decodedToken.session,
};
}
} catch (err) {
Logger.info(err);
}
}
return null;
};

View file

@ -0,0 +1,5 @@
import { v4 } from 'uuid';
export const generateSessionId = (prefix: string) => {
return `${prefix}-${v4()}`;
};

View file

@ -22,7 +22,7 @@ type CreateContextOptions = {
* @param {CreateContextOptions} opts - options
* @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts
*/
export const createContextInner = async (opts: CreateContextOptions) => ({
const createContextInner = async (opts: CreateContextOptions) => ({
...opts,
});

View file

@ -1,3 +1,2 @@
export { EventDispatcherInstance as EventDispatcher } from './EventDispatcher';
export type { EventType } from './EventDispatcher';
export { EVENT_TYPES } from './EventDispatcher';

View file

@ -49,7 +49,7 @@ const configSchema = z.object({
export const settingsSchema = configSchema.partial().pick({ dnsIp: true, internalIp: true, appsRepoUrl: true, domain: true, storagePath: true });
export type TipiSettingsType = z.infer<typeof settingsSchema>;
type TipiSettingsType = z.infer<typeof settingsSchema>;
const formatErrors = (errors: { fieldErrors: Record<string, string[]> }) =>
Object.entries(errors.fieldErrors)

View file

@ -30,5 +30,3 @@ export const FIELD_TYPES = {
RANDOM: 'random',
BOOLEAN: 'boolean',
} as const;
export type FieldType = (typeof FIELD_TYPES)[keyof typeof FIELD_TYPES];

View file

@ -2,7 +2,7 @@ import fs from 'fs-extra';
import * as argon2 from 'argon2';
import { faker } from '@faker-js/faker';
import { TotpAuthenticator } from '@/server/utils/totp';
import { generateSessionId } from '@/server/common/get-server-auth-session';
import { generateSessionId } from '@/server/common/session.helpers';
import { fromAny, fromPartial } from '@total-typescript/shoehorn';
import { mockInsert, mockSelect } from '@/server/tests/drizzle-helpers';
import { createDatabase, clearDatabase, closeDatabase, TestDatabase } from '@/server/tests/test-utils';
@ -74,7 +74,7 @@ describe('Login', () => {
});
describe('Test: verifyTotp', () => {
it('should return a valid jsonwebtoken if the totp is correct', async () => {
it('should correctly log in user after totp is verified', async () => {
// arrange
const req = { session: { userId: undefined } };
const email = faker.internet.email();

View file

@ -1,12 +1,12 @@
import * as argon2 from 'argon2';
import validator from 'validator';
import { TotpAuthenticator } from '@/server/utils/totp';
import { generateSessionId } from '@/server/common/get-server-auth-session';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { AuthQueries } from '@/server/queries/auth/auth.queries';
import { Context } from '@/server/context';
import { TranslatedError } from '@/server/utils/errors';
import { Locales, getLocaleFromString } from '@/shared/internationalization/locales';
import { generateSessionId } from '@/server/common/session.helpers';
import { getConfig } from '../../core/TipiConfig';
import TipiCache from '../../core/TipiCache';
import { fileExists, unlinkFile } from '../../common/fs.helpers';

View file

@ -13,9 +13,8 @@ const authQueries = new AuthQueries(db);
* Convert ZodError to a record
*
* @param {typeToFlattenedError<string>} errors - errors
* @returns {Record<string, string>} record
*/
export function zodErrorsToRecord(errors: typeToFlattenedError<string>) {
function zodErrorsToRecord(errors: typeToFlattenedError<string>) {
const record: Record<string, string> = {};
Object.entries(errors.fieldErrors).forEach(([key, value]) => {
const error = value?.[0];

View file

@ -1,4 +1,4 @@
export const APP_LOCALES = {
const APP_LOCALES = {
'en-US': 'English',
'fr-FR': 'Français',
'ja-JP': '日本語',