-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #40 from acelaya-forks/feature/user-session
Add services needed for sessions and end-user authentication
- Loading branch information
Showing
24 changed files
with
497 additions
and
74 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import type { Strategy } from 'remix-auth'; | ||
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'; | ||
|
||
export const CREDENTIALS_STRATEGY = 'credentials'; | ||
|
||
function getAuthStrategies(usersService: UsersService): Map<string, Strategy<any, any>> { | ||
const strategies = new Map<string, Strategy<any, any>>(); | ||
|
||
// Add strategy to login via credentials form | ||
strategies.set(CREDENTIALS_STRATEGY, new FormStrategy(async ({ form }): Promise<SessionData> => { | ||
const { username, password } = credentialsSchema.parse({ | ||
username: form.get('username'), | ||
password: form.get('password'), | ||
}); | ||
|
||
const user = await usersService.getUserByCredentials(username, password); | ||
return { userId: user.id }; | ||
})); | ||
|
||
// TODO Add other strategies, like oAuth for SSO | ||
|
||
return strategies; | ||
} | ||
|
||
export function createAuthenticator(usersService: UsersService, sessionStorage: SessionStorage): Authenticator { | ||
const authenticator = new Authenticator(sessionStorage); | ||
const strategies = getAuthStrategies(usersService); | ||
strategies.forEach((strategy, name) => authenticator.use(strategy, name)); | ||
|
||
return authenticator; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { z } from 'zod'; | ||
|
||
export const credentialsSchema = z.object({ | ||
username: z.string().min(1), | ||
password: z.string().min(1), | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import * as argon2 from 'argon2'; | ||
|
||
export const hashPassword = async (plainTextPassword: string) => argon2.hash(plainTextPassword); | ||
|
||
export const verifyPassword = async (plainTextPassword: string, hashedPassword: string) => | ||
argon2.verify(hashedPassword, plainTextPassword); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { createCookieSessionStorage } from '@remix-run/node'; | ||
import { env, isProd } from '../utils/env.server'; | ||
|
||
export type SessionData = { | ||
userId: number; | ||
[key: string]: unknown; | ||
}; | ||
|
||
export const createSessionStorage = () => createCookieSessionStorage<SessionData>({ | ||
cookie: { | ||
name: 'shlink_dashboard_session', | ||
httpOnly: true, | ||
maxAge: 30 * 60, // 30 minutes | ||
path: '/', | ||
sameSite: 'lax', | ||
secrets: env.SHLINK_DASHBOARD_SESSION_SECRETS ?? ['s3cr3t1'], | ||
secure: isProd(), | ||
}, | ||
}); | ||
|
||
export type SessionStorage = ReturnType<typeof createSessionStorage>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import type { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/node'; | ||
import { json } from '@remix-run/node'; | ||
import { useLoaderData } from '@remix-run/react'; | ||
import { useId } from 'react'; | ||
import { Button, Input } from 'reactstrap'; | ||
import { Authenticator } from 'remix-auth'; | ||
import { CREDENTIALS_STRATEGY } from '../auth/auth.server'; | ||
import type { SessionStorage } from '../auth/session.server'; | ||
import { serverContainer } from '../container/container.server'; | ||
|
||
export async function action( | ||
{ request }: ActionFunctionArgs, | ||
authenticator: Authenticator = serverContainer[Authenticator.name], | ||
) { | ||
const { searchParams } = new URL(request.url); | ||
return authenticator.authenticate(CREDENTIALS_STRATEGY, request, { | ||
successRedirect: searchParams.get('redirect-to') ?? '/', // TODO Make sure "redirect-to" is a relative URL | ||
failureRedirect: request.url, | ||
}); | ||
} | ||
|
||
export async function loader( | ||
{ request }: LoaderFunctionArgs, | ||
authenticator: Authenticator = serverContainer[Authenticator.name], | ||
{ getSession, commitSession }: SessionStorage = serverContainer.sessionStorage, | ||
) { | ||
// If the user is already authenticated redirect to home | ||
await authenticator.isAuthenticated(request, { successRedirect: '/' }); | ||
|
||
const session = await getSession(request.headers.get('cookie')); | ||
const error = session.get(authenticator.sessionErrorKey); | ||
return json({ error }, { | ||
headers: { | ||
'Set-Cookie': await commitSession(session), | ||
}, | ||
}); | ||
} | ||
|
||
export default function Login() { | ||
const usernameId = useId(); | ||
const passwordId = useId(); | ||
const { error } = useLoaderData<typeof loader>(); | ||
|
||
return ( | ||
<form | ||
method="post" | ||
className="d-flex flex-column gap-3 p-3 mt-5 mx-auto w-50 rounded-2 border-opacity-25 border-secondary" | ||
style={{ borderWidth: '1px', borderStyle: 'solid' }} | ||
> | ||
<div> | ||
<label htmlFor={usernameId}>Username:</label> | ||
<Input id={usernameId} name="username" required /> | ||
</div> | ||
<div> | ||
<label htmlFor={passwordId}>Password:</label> | ||
<Input id={passwordId} type="password" name="password" required /> | ||
</div> | ||
<Button color="primary" type="submit">Login</Button> | ||
{!!error && <div className="text-danger" data-testid="error-message">Username or password are incorrect</div>} | ||
</form> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import type { EntityManager } from 'typeorm'; | ||
import { verifyPassword } from '../auth/passwords.server'; | ||
import type { User } from '../entities/User'; | ||
import { UserEntity } from '../entities/User'; | ||
|
||
export class UsersService { | ||
constructor(private readonly em: EntityManager) {} | ||
|
||
async getUserByCredentials(username: string, password: string): Promise<User> { | ||
const user = await this.em.findOneBy(UserEntity, { username }); | ||
if (!user) { | ||
throw new Error(`User not found with username ${username}`); | ||
} | ||
|
||
const isPasswordCorrect = await verifyPassword(password, user.password); | ||
if (!isPasswordCorrect) { | ||
throw new Error(`Incorrect password for user ${username}`); | ||
} | ||
|
||
return user; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.