Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/logout #51

Merged
merged 4 commits into from
May 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/auth/auth.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { Authenticator } from 'remix-auth';
import { FormStrategy } from 'remix-auth-form';
import type { UsersService } from '../users/UsersService.server';
import { credentialsSchema } from './credentials-schema.server';
import type { SessionData, SessionStorage } from './session.server';
import type { SessionStorage } from './session.server';
import type { SessionData } from './session-context';

export const CREDENTIALS_STRATEGY = 'credentials';

Expand Down
12 changes: 12 additions & 0 deletions app/auth/session-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createContext, useContext } from 'react';

export type SessionData = {
userId: number;
[key: string]: unknown;
};

const SessionContext = createContext<SessionData | null>(null);

export const { Provider: SessionProvider } = SessionContext;

export const useSession = () => useContext(SessionContext);
6 changes: 1 addition & 5 deletions app/auth/session.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { createCookieSessionStorage } from '@remix-run/node';
import { env, isProd } from '../utils/env.server';

export type SessionData = {
userId: number;
[key: string]: unknown;
};
import type { SessionData } from './session-context';

export const createSessionStorage = () => createCookieSessionStorage<SessionData>({
cookie: {
Expand Down
43 changes: 35 additions & 8 deletions app/common/MainHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,40 @@
import { faArrowRightFromBracket as faLogout, faChevronDown as arrowIcon } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Link } from '@remix-run/react';
import { useToggle } from '@shlinkio/shlink-frontend-kit';
import type { FC } from 'react';
import React from 'react';
import { Navbar, NavbarBrand } from 'reactstrap';
import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
import { useSession } from '../auth/session-context';
import { ShlinkLogo } from './ShlinkLogo';

export const MainHeader: FC = () => (
<Navbar color="primary" dark fixed="top" className="main-header" expand="md">
<NavbarBrand tag={Link} to="/">
<ShlinkLogo className="tw-inline-block tw-mr-1 tw-w-[26px]" color="white" /> Shlink
</NavbarBrand>
</Navbar>
);
export const MainHeader: FC = () => {
const session = useSession();
const [isOpen, toggleCollapse] = useToggle();

return (
<Navbar color="primary" dark fixed="top" className="main-header" expand="md">
<NavbarBrand tag={Link} to="/">
<ShlinkLogo className="tw-inline-block tw-mr-1 tw-w-[26px]" color="white" /> Shlink
</NavbarBrand>

{session !== null && (
<>
<NavbarToggler onClick={toggleCollapse}>
<FontAwesomeIcon icon={arrowIcon} />
</NavbarToggler>

<Collapse navbar isOpen={isOpen}>
<Nav navbar className="tw-ml-auto">
<NavItem>
<NavLink tag={Link} to="/logout">
<FontAwesomeIcon icon={faLogout} className="tw-w-[26px] tw-inline-block" /> Logout
</NavLink>
</NavItem>
</Nav>
</Collapse>
</>
)}
</Navbar>
);
};
2 changes: 1 addition & 1 deletion app/container/container.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ bottle.serviceFactory('em', () => appDataSource.manager);

bottle.serviceFactory('ServersRepository', createServersRepository, 'em');

bottle.service(TagsService.name, TagsService, 'em');
bottle.service(ServersService.name, ServersService, 'ServersRepository');
bottle.service(TagsService.name, TagsService, 'em', ServersService.name);
bottle.service(SettingsService.name, SettingsService, 'em');
bottle.service(UsersService.name, UsersService, 'em');

Expand Down
44 changes: 28 additions & 16 deletions app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,60 @@
import type { LoaderFunctionArgs } from '@remix-run/node';
import { Links, Meta, Outlet, Scripts } from '@remix-run/react';
import { Links, Meta, Outlet, Scripts, useLoaderData } from '@remix-run/react';

Check warning on line 2 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L2

Added line #L2 was not covered by tests
import { Authenticator } from 'remix-auth';
import type { SessionData } from './auth/session-context';
import { SessionProvider } from './auth/session-context';

Check warning on line 5 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L4-L5

Added lines #L4 - L5 were not covered by tests
import { MainHeader } from './common/MainHeader';
import { serverContainer } from './container/container.server';
import { appDataSource } from './db/data-source.server';
import './index.scss';

export async function loader(
{ request }: LoaderFunctionArgs,
authenticator: Authenticator = serverContainer[Authenticator.name],
authenticator: Authenticator<SessionData> = serverContainer[Authenticator.name],

Check warning on line 13 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L13

Added line #L13 was not covered by tests
) {
// FIXME This should be done during server start-up, not here

Check warning on line 15 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L15

Added line #L15 was not covered by tests
if (!appDataSource.isInitialized) {
console.log('Initializing database connection...');

Check warning on line 17 in app/root.tsx

View workflow job for this annotation

GitHub Actions / ci / lint (npm run lint)

Unexpected console statement
await appDataSource.initialize();
console.log('Database connection initialized');

Check warning on line 19 in app/root.tsx

View workflow job for this annotation

GitHub Actions / ci / lint (npm run lint)

Unexpected console statement
}

const { pathname } = new URL(request.url);
const isPublicRoute = ['/login'].includes(pathname);
if (!isPublicRoute) {
await authenticator.isAuthenticated(request, {
failureRedirect: `/login?redirect-to=${encodeURIComponent(pathname)}`,
});
}

return {};
const isPublicRoute = ['/login', '/logout'].includes(pathname);
const session = await (isPublicRoute
? authenticator.isAuthenticated(request) // For public routes, do not redirect
: authenticator.isAuthenticated(
request,
{ failureRedirect: `/login?redirect-to=${encodeURIComponent(pathname)}` },
));
return { session };

Check warning on line 30 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L23-L30

Added lines #L23 - L30 were not covered by tests
}

/* eslint-disable-next-line no-restricted-exports */
export default function App() {
const { session } = useLoaderData<typeof loader>();

Check warning on line 36 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L35-L36

Added lines #L35 - L36 were not covered by tests
return (
<html lang="en">
<head>
<title>Shlink dashboard</title>
<link rel="icon" href="data:image/x-icon;base64,AA" />

<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="theme-color" content="#4696e5" />

Check warning on line 44 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L41-L44

Added lines #L41 - L44 were not covered by tests
<Meta />

<link rel="icon" href="data:image/x-icon;base64,AA" />

Check warning on line 47 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L46-L47

Added lines #L46 - L47 were not covered by tests
<Links />
</head>
<body>
<MainHeader />
<div className="app">
<Outlet />
</div>
<Scripts />
<SessionProvider value={session}>
<MainHeader />
<div className="app">
<Outlet />
</div>
<Scripts />
</SessionProvider>

Check warning on line 57 in app/root.tsx

View check run for this annotation

Codecov / codecov/patch

app/root.tsx#L51-L57

Added lines #L51 - L57 were not covered by tests
</body>
</html>
);
Expand Down
10 changes: 10 additions & 0 deletions app/routes/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { ActionFunctionArgs } from '@remix-run/node';
import { Authenticator } from 'remix-auth';
import { serverContainer } from '../container/container.server';

export function loader(
{ request }: ActionFunctionArgs,
authenticator: Authenticator = serverContainer[Authenticator.name],
) {
return authenticator.logout(request, { redirectTo: '/login' });
}
2 changes: 1 addition & 1 deletion app/routes/server.$serverId.$.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { useEffect, useMemo, useState } from 'react';
import { Authenticator } from 'remix-auth';
import { ShlinkApiProxyClient } from '../api/ShlinkApiProxyClient.client';
import type { SessionData } from '../auth/session.server';
import type { SessionData } from '../auth/session-context';

Check warning on line 8 in app/routes/server.$serverId.$.tsx

View check run for this annotation

Codecov / codecov/patch

app/routes/server.$serverId.$.tsx#L8

Added line #L8 was not covered by tests
import { serverContainer } from '../container/container.server';
import { SettingsService } from '../settings/SettingsService.server';
import { TagsService } from '../tags/TagsService.server';
Expand Down
2 changes: 1 addition & 1 deletion app/routes/server.$serverId.shlink-api.$method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ShlinkApiClient } from '@shlinkio/shlink-js-sdk';
import { ErrorType } from '@shlinkio/shlink-js-sdk/api-contract';
import { Authenticator } from 'remix-auth';
import type { ApiClientBuilder } from '../api/apiClientBuilder.server';
import type { SessionData } from '../auth/session.server';
import type { SessionData } from '../auth/session-context';
import { serverContainer } from '../container/container.server';
import { ServersService } from '../servers/ServersService.server';
import { problemDetails } from '../utils/response.server';
Expand Down
2 changes: 1 addition & 1 deletion app/routes/server.$serverId.tags.colors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ActionFunctionArgs } from '@remix-run/node';
import { Authenticator } from 'remix-auth';
import type { SessionData } from '../auth/session.server';
import type { SessionData } from '../auth/session-context';
import { serverContainer } from '../container/container.server';
import { TagsService } from '../tags/TagsService.server';
import { empty } from '../utils/response.server';
Expand Down
6 changes: 3 additions & 3 deletions app/tags/TagsService.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { EntityManager } from 'typeorm';
import type { Server } from '../entities/Server';
import { ServerEntity } from '../entities/Server';
import { TagEntity } from '../entities/Tag';
import type { User } from '../entities/User';
import { UserEntity } from '../entities/User';
import type { ServersService } from '../servers/ServersService.server';

export type FindTagsParam = {
userId: number;
Expand All @@ -20,7 +20,7 @@ type ServerAndUserResult = {
};

export class TagsService {
constructor(private readonly em: EntityManager) {}
constructor(private readonly em: EntityManager, private readonly serversService: ServersService) {}

async tagColors(param: FindTagsParam): Promise<Record<string, string>> {
const { server, user } = await this.resolveServerAndUser(param);
Expand Down Expand Up @@ -71,7 +71,7 @@ export class TagsService {

private async resolveServerAndUser({ userId, serverPublicId }: FindTagsParam): Promise<ServerAndUserResult> {
const [server, user] = await Promise.all([
serverPublicId ? this.em.findOneBy(ServerEntity, { publicId: serverPublicId }) : null,
serverPublicId ? this.serversService.getByPublicIdAndUser(serverPublicId, userId) : null,
this.em.findOneBy(UserEntity, { id: userId }),
]);

Expand Down
17 changes: 8 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
"migration:create": "tsx node_modules/.bin/typeorm migration:create app/db/migrations/migration"
},
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.5.2",
"@fortawesome/free-brands-svg-icons": "^6.5.2",
"@fortawesome/free-regular-svg-icons": "^6.5.2",
"@fortawesome/free-solid-svg-icons": "^6.5.2",
"@fortawesome/react-fontawesome": "^0.2.1",
"@remix-run/express": "^2.9.2",
"@remix-run/node": "^2.9.2",
"@remix-run/react": "^2.9.2",
Expand Down
35 changes: 29 additions & 6 deletions test/common/MainHeader.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { MemoryRouter } from 'react-router';
import type { SessionData } from '../../app/auth/session-context';
import { SessionProvider } from '../../app/auth/session-context';
import { MainHeader } from '../../app/common/MainHeader';
import { checkAccessibility } from '../__helpers__/accessibility';

describe('<MainHeader />', () => {
const setUp = () => render(
<MemoryRouter>
<MainHeader />
</MemoryRouter>,
const setUp = (session?: SessionData) => render(
<SessionProvider value={session ?? null}>
<MemoryRouter>
<MainHeader />
</MemoryRouter>
</SessionProvider>,
);

it('passes a11y checks', () => checkAccessibility(setUp()));
it.each([
[undefined],
[fromPartial<SessionData>({})],
])('passes a11y checks', (session) => checkAccessibility(setUp(session)));

it.each([
[undefined],
[fromPartial<SessionData>({})],
])('shows logout and menu toggle only if session is set', (session) => {
setUp(session);

if (session) {
expect(screen.getByRole('button')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Logout' })).toBeInTheDocument();
} else {
expect(screen.queryByRole('button')).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Logout' })).not.toBeInTheDocument();
}
});
});
19 changes: 19 additions & 0 deletions test/routes/logout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { LoaderFunctionArgs } from '@remix-run/node';
import { fromPartial } from '@total-typescript/shoehorn';
import type { Authenticator } from 'remix-auth';
import { loader as logoutLoader } from '../../app/routes/logout';

describe('logout', () => {
const logout = vi.fn();
const authenticator = fromPartial<Authenticator>({ logout });
const setUp = () => (args: LoaderFunctionArgs) => logoutLoader(args, authenticator);

it('logs out in authenticator', () => {
const request = fromPartial<Request>({});
const action = setUp();

action(fromPartial({ request }));

expect(logout).toHaveBeenCalledWith(request, { redirectTo: '/login' });
});
});
2 changes: 1 addition & 1 deletion test/routes/server.$serverId.shlink-api.$method.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ErrorType } from '@shlinkio/shlink-js-sdk/api-contract';
import { fromPartial } from '@total-typescript/shoehorn';
import type { Authenticator } from 'remix-auth';
import { expect } from 'vitest';
import type { SessionData } from '../../app/auth/session.server';
import type { SessionData } from '../../app/auth/session-context';
import { action } from '../../app/routes/server.$serverId.shlink-api.$method';
import type { ServersService } from '../../app/servers/ServersService.server';

Expand Down
2 changes: 1 addition & 1 deletion test/routes/server.$serverId.tags.colors.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ActionFunctionArgs } from '@remix-run/node';
import { fromPartial } from '@total-typescript/shoehorn';
import type { Authenticator } from 'remix-auth';
import type { SessionData } from '../../app/auth/session.server';
import type { SessionData } from '../../app/auth/session-context';
import { action } from '../../app/routes/server.$serverId.tags.colors';
import type { TagsService } from '../../app/tags/TagsService.server';

Expand Down
Loading
Loading