27 | {user ? (
28 | <>
29 |
Hello {user.first_name}
30 |
You are logged in
31 |
34 | >
35 | ) : (
36 | <>
37 |
Hello
38 |
You are not logged in
39 |
40 | Go to Login page to login
41 |
42 | >
43 | )}
44 |
45 | );
46 | }
47 |
--------------------------------------------------------------------------------
/examples/remix-basic/app/routes/auth.tsx:
--------------------------------------------------------------------------------
1 | import { redirect } from '@remix-run/node';
2 | import type { LoaderFunction } from '@remix-run/node';
3 | import { AuthDataValidator } from '@telegram-auth/server';
4 | import { urlStrToAuthDataMap } from '@telegram-auth/server/utils';
5 | import { getSession, commitSession } from '../sessions';
6 |
7 | export const loader: LoaderFunction = async ({ request }) => {
8 | const validator = new AuthDataValidator({ botToken: `${process.env.BOT_TOKEN}` });
9 |
10 | const session = await getSession(request.headers.get('Cookie'));
11 |
12 | const data = urlStrToAuthDataMap(request.url);
13 |
14 | try {
15 | const user = await validator.validate(data);
16 |
17 | session.set('user', user);
18 | } catch (error: any) {
19 | session.flash('error', error.message);
20 |
21 | // Redirect back to the login page with errors.
22 | return redirect('/login', {
23 | headers: {
24 | 'Set-Cookie': await commitSession(session),
25 | },
26 | });
27 | }
28 |
29 | // Login succeeded, send them to the home page.
30 | return redirect('/', {
31 | headers: {
32 | 'Set-Cookie': await commitSession(session),
33 | },
34 | });
35 | };
36 |
--------------------------------------------------------------------------------
/examples/remix-basic/app/routes/login.tsx:
--------------------------------------------------------------------------------
1 | import { json, redirect } from '@remix-run/node';
2 | import { useLoaderData, Link } from '@remix-run/react';
3 | import type { LoaderFunction, ActionFunction } from '@remix-run/node';
4 | import { LoginButton } from '@telegram-auth/react';
5 |
6 | import { getSession, commitSession, destroySession } from '../sessions';
7 |
8 | export const loader: LoaderFunction = async ({ request }) => {
9 | const session = await getSession(request.headers.get('Cookie'));
10 |
11 | if (session.has('user')) {
12 | return redirect('/');
13 | }
14 |
15 | const botUsername = process.env.BOT_USERNAME || '';
16 |
17 | const data = { error: session.get('error'), botUsername };
18 |
19 | return json(data, {
20 | headers: {
21 | 'Set-Cookie': await commitSession(session),
22 | },
23 | });
24 | };
25 |
26 | export const action: ActionFunction = async ({ request }) => {
27 | const session = await getSession(request.headers.get('Cookie'));
28 |
29 | return redirect('/', {
30 | headers: {
31 | 'Set-Cookie': await destroySession(session),
32 | },
33 | });
34 | };
35 |
36 | export default function Login() {
37 | const { botUsername, error } = useLoaderData