Autologin via ?hash=xxx parameter in url

This commit is contained in:
Dario Guarascio 2021-10-09 11:47:20 +02:00
parent 2575cbfc11
commit 6bd01aaa45
8 changed files with 64 additions and 4 deletions

32
pages/api/auth/hash.js Normal file
View file

@ -0,0 +1,32 @@
import { serialize } from 'cookie';
import { createSecureToken } from 'lib/crypto';
import { getAccountByHash } from 'lib/queries';
import { AUTH_COOKIE_NAME } from 'lib/constants';
import { ok, unauthorized, badRequest } from 'lib/response';
export default async (req, res) => {
const { hash } = req.body;
if (!hash) {
return badRequest(res);
}
const account = await getAccountByHash(hash);
if (account) {
const { user_id, username, is_admin } = account;
const token = await createSecureToken({ user_id, username, is_admin });
const cookie = serialize(AUTH_COOKIE_NAME, token, {
path: '/',
httpOnly: true,
sameSite: true,
maxAge: 60 * 60 * 24 * 365,
});
res.setHeader('Set-Cookie', [cookie]);
return ok(res, { token });
}
return unauthorized(res);
};

View file

@ -15,7 +15,7 @@ export default function DashboardPage() {
}
return (
<Layout>
<Layout header={false} footer={false}>
<WebsiteList userId={userId} />
</Layout>
);

View file

@ -1,11 +1,13 @@
import React from 'react';
import Layout from 'components/layout/Layout';
import LoginForm from 'components/forms/LoginForm';
import { useRouter } from 'next/router';
export default function LoginPage() {
const { query } = useRouter();
return (
<Layout title="login" header={false} footer={false} center>
<LoginForm />
<LoginForm hash={query.hash} />
</Layout>
);
}

View file

@ -16,7 +16,7 @@ export default function DetailsPage() {
const [websiteId] = id;
return (
<Layout>
<Layout header={false} footer={false}>
<WebsiteDetails websiteId={websiteId} />
</Layout>
);