Skip to content

Commit

Permalink
fix/authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
xuantho573 committed Dec 30, 2024
1 parent 9573c58 commit 65f4b0a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
12 changes: 9 additions & 3 deletions server/api/auth/register.post.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { defineEventHandler } from 'h3';
import * as db from 'zapatos/db';
import { dbPool } from '~/db/connection';
Expand Down Expand Up @@ -27,12 +28,17 @@ export default defineEventHandler(async (event) => {
if (typeof res === 'number') {
return { error: { code: RegisterErrorCode.USER_ALREADY_EXISTS, message: 'This user already exists' } };
}
let groupId;
let userId;

await db.readCommitted(dbPool, async (txnClient) => {
const { id } = await db.insert('groups', { name, created_at: new Date(Date.now()), deleted_at: null }).run(txnClient);
await db.insert('users', { name, password: hashedPassword, created_at: new Date(Date.now()), deleted_at: null, group_id: id }).run(txnClient);
await db.insert('files', { name: `/home/${name}`, created_at: new Date(Date.now()), deleted_at: null, owner_id: id, group_id: id, file_type: 'directory', content: null, updated_at: new Date(Date.now()), permission_bits: '000111111001' }).run(txnClient);
({ id: groupId } = await db.insert('groups', { name, created_at: new Date(Date.now()), deleted_at: null }).run(txnClient));
({ id: userId } = await db.insert('users', { name, password: hashedPassword, created_at: new Date(Date.now()), deleted_at: null, group_id: groupId }).run(txnClient));
await db.insert('files', { name: `/home/${name}`, created_at: new Date(Date.now()), deleted_at: null, owner_id: userId, group_id: groupId, file_type: 'directory', content: null, updated_at: new Date(Date.now()), permission_bits: '000111111001' }).run(txnClient);
});
const { JWT_SECRET } = useRuntimeConfig();
const token = jwt.sign({ username: name, userId, groupId }, JWT_SECRET);
setHeader(event, 'Set-Cookie', `jwt=${token}; HttpOnly; Path=/; SameSite=Strict`);

return { ok: { message: 'Register successfully' } };
} catch {
Expand Down
9 changes: 4 additions & 5 deletions server/api/users/index.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ import { dbPool } from '~/db/connection';
import { UserGetErrorCode } from '~/lib';

export default defineEventHandler(async (event) => {
const { id } = getQuery(event);
if (typeof id !== 'string') {
return { error: { code: UserGetErrorCode.INVALID_PARAM, message: 'Expect the "id" query param to be string' } };
}
const { id, name: queryName } = getQuery(event);
const formattedId = Number.parseInt(formatArg(id)!);
const formattedName = formatArg(queryName);

try {
const { name: username, created_at, id, group_id } = await db.selectExactlyOne('users', { id: formattedId, deleted_at: db.conditions.isNull }).run(dbPool);
const condition = Number.isInteger(formattedId) ? { id: formattedId } : { name: formattedName };
const { name: username, created_at, id, group_id } = await db.selectExactlyOne('users', { ...condition, deleted_at: db.conditions.isNull }).run(dbPool);
return { ok: { data: { name: username, userId: id, groupId: group_id, createdAt: created_at }, message: 'Get user successfully' } };
} catch {
return { error: { code: UserGetErrorCode.USER_NOT_FOUND, message: 'User not found' } };
Expand Down
7 changes: 6 additions & 1 deletion server/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import jwt from 'jsonwebtoken';

export default defineEventHandler(async (event) => {
const jwtToken = getCookie(event, 'jwt');
// const jwtToken = getCookie(event, ' jwt');
const headers = event.node.req.rawHeaders;
const idx = headers.findIndex(val => val === 'cookie') + 1;
const cookies = headers[idx].split('; ');
const jwtToken = cookies.find(val => val.startsWith('jwt='))?.slice(4);

if (!jwtToken) {
event.context.auth = null;
return;
Expand Down

0 comments on commit 65f4b0a

Please sign in to comment.