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

Auth backend #141

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
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
7 changes: 0 additions & 7 deletions app/(api)/_actions/auth/deleteAuthToken.ts

This file was deleted.

42 changes: 3 additions & 39 deletions app/(api)/_actions/auth/login.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,7 @@
'use server';

import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import { Login } from '@datalib/auth/login';
import { HttpError, NotAuthenticatedError } from '@utils/response/Errors';
import FormToJSON from '@utils/form/FormToJSON';
import Login from '@datalib/auth/login';

import type AuthToken from '@typeDefs/authToken';
import User from '@typeDefs/user';

export default async function LoginAction(
prevState: any,
formData: FormData
): Promise<{
ok: boolean;
body?: AuthToken | null;
error?: string | null;
}> {
try {
const body = FormToJSON(formData) as User;
const data = await Login(body);

if (!data.ok || !data.body) {
throw new NotAuthenticatedError(data.error as string);
}

const payload = jwt.decode(data.body) as AuthToken;

cookies().set({
name: 'auth_token',
value: data.body,
expires: payload.exp * 1000,
secure: true,
httpOnly: true,
});

return { ok: true, body: payload || null, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
}
export default async function LoginAction(email: string, password: string) {
return Login(email, password);
}
7 changes: 7 additions & 0 deletions app/(api)/_actions/auth/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use server';

import Logout from '@datalib/auth/logout';

export default async function LogoutAction() {
return Logout();
}
43 changes: 3 additions & 40 deletions app/(api)/_actions/auth/register.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,7 @@
'use server';

import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import { Register } from '@datalib/auth/register';
import { HttpError, NotAuthenticatedError } from '@utils/response/Errors';
import FormToJSON from '@utils/form/FormToJSON';
import Register from '@datalib/auth/register';

import type AuthToken from '@typeDefs/authToken';
import type User from '@typeDefs/user';

export default async function RegisterAction(
prevState: any,
formData: FormData
): Promise<{
ok: boolean;
body?: AuthToken | null;
error?: string | null;
}> {
try {
const body = FormToJSON(formData) as User;

const data = await Register(body);

if (!data.ok || !data.body) {
throw new NotAuthenticatedError(data.error as string);
}

const payload = jwt.decode(data.body) as AuthToken;

cookies().set({
name: 'auth_token',
value: data.body,
expires: payload.exp * 1000,
secure: true,
httpOnly: true,
});

return { ok: true, body: payload, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
}
export default async function RegisterAction(body: object) {
return Register(body);
}
15 changes: 0 additions & 15 deletions app/(api)/_actions/auth/verifyToken.ts

This file was deleted.

8 changes: 8 additions & 0 deletions app/(api)/_actions/users/createUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use server';

import { CreateUser } from '@datalib/users/createUser';

export async function createUser(body: object) {
const response = await CreateUser(body);
return response;
}
26 changes: 0 additions & 26 deletions app/(api)/_datalib/auth/authToken.ts

This file was deleted.

48 changes: 21 additions & 27 deletions app/(api)/_datalib/auth/login.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
'use server';
import bcrypt from 'bcryptjs';
import { AuthError } from 'next-auth';

import { HttpError, NotAuthenticatedError } from '@utils/response/Errors';
import { GetManyUsers } from '@datalib/users/getUser';
import { CreateAuthToken } from './authToken';
import { signIn } from '@/auth';

export async function Login(body: { email: string; password: string }) {
export default async function Login(email: string, password: string) {
try {
const { email, password } = body;
await signIn('credentials', {
email,
password,
redirect: false,
});

// Find Judge
const data = await GetManyUsers({ email });
if (!data.ok || data.body.length === 0) {
throw new NotAuthenticatedError('Judge not found');
return { ok: true, body: 'Successfully logged in', error: null };
} catch (error) {
if (error instanceof AuthError && error?.cause?.err?.message) {
return {
ok: false,
body: null,
error: error.cause.err.message,
};
}

const judge = data.body[0];

const isPasswordValid = await bcrypt.compare(
password as string,
judge.password
);

if (!isPasswordValid) {
throw new NotAuthenticatedError('Email or Password do not match');
}

const token = await CreateAuthToken(judge);
return { ok: true, body: token, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
return {
ok: false,
body: null,
error: 'Authentication error.',
};
}
}
27 changes: 27 additions & 0 deletions app/(api)/_datalib/auth/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { AuthError } from 'next-auth';

import { signOut } from '@/auth';

export default async function Logout() {
try {
await signOut({
redirect: false,
});

return { ok: true, body: 'Successfully logged out', error: null };
} catch (error) {
if (error instanceof AuthError && error?.cause?.err?.message) {
return {
ok: false,
body: null,
error: error.cause.err.message,
};
}

return {
ok: false,
body: null,
error: 'Authentication error.',
};
}
}
41 changes: 16 additions & 25 deletions app/(api)/_datalib/auth/register.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,29 @@
'use server';
import bcrypt from 'bcryptjs';

import Login from '@datalib/auth/login';
import { CreateUser } from '@datalib/users/createUser';
import { DuplicateError, HttpError } from '@utils/response/Errors';
import { GetManyUsers } from '@datalib/users/getUser';
import { CreateAuthToken } from './authToken';
import User from '@typeDefs/user';
import HttpError from '@utils/response/HttpError';

export async function Register(body: User) {
export default async function Register(body: any) {
try {
const { email, password, ...rest } = body;
const hashedPassword = await bcrypt.hash(password as string, 10);
const password = body.password;
const userRes = await CreateUser(body);

// Find user
const userData = await GetManyUsers({ email });
if (!userData.ok || userData.body.length !== 0) {
throw new DuplicateError('User already exists');
if (!userRes.ok) {
throw new HttpError(userRes.error ?? 'Error creating user');
}

// Create user
const data = await CreateUser({
email,
password: hashedPassword,
...rest,
});
const response = await Login(body.email, password);

if (!data.ok) {
throw new HttpError('Failed to create user');
if (!response.ok) {
throw new HttpError(userRes.error ?? 'Authentication error');
}

const token = await CreateAuthToken(data.body);
return { ok: true, body: token, error: null };
return { ok: true, body: userRes.body, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, error: error.message };
return {
ok: false,
body: null,
error: error.message,
};
}
}
12 changes: 10 additions & 2 deletions app/(api)/_datalib/auth/resetPassword.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import bcrypt from 'bcryptjs';
import { GetManyUsers } from '@datalib/users/getUser';
import { UpdateUser } from '@datalib/users/updateUser';
import { HttpError } from '@utils/response/Errors';
import { signOut } from 'auth';

export async function ResetPassword(body: { email: string; password: string }) {
try {
Expand All @@ -23,9 +24,16 @@ export async function ResetPassword(body: { email: string; password: string }) {
},
});

return { ok: true, body: updateData, error: null };
await signOut();

return { ok: true, body: updateData, error: null, status: 200 };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
return {
ok: false,
body: null,
error: error.message,
status: error.status,
};
}
}
2 changes: 1 addition & 1 deletion app/(api)/_datalib/submissions/createSubmission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const CreateSubmission = async (body: {
_id: new ObjectId(creationStatus.insertedId),
});

return { ok: true, body: submission, error: null, status: 201 };
return { ok: true, body: submission, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
Expand Down
2 changes: 1 addition & 1 deletion app/(api)/_datalib/userToEvents/linkUserToEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const LinkUserToEvent = async (body: {
_id: new ObjectId(creationStatus.insertedId),
});

return { ok: true, body: userToEvent, error: null, status: 201 };
return { ok: true, body: userToEvent, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
Expand Down
23 changes: 21 additions & 2 deletions app/(api)/_datalib/users/createUser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { ObjectId } from 'mongodb';
import { hash } from 'bcryptjs';

import { getDatabase } from '@utils/mongodb/mongoClient.mjs';
import isBodyEmpty from '@utils/request/isBodyEmpty';
import parseAndReplace from '@utils/request/parseAndReplace';
Expand All @@ -17,6 +19,8 @@ export const CreateUser = async (body: object) => {

const parsedBody = await parseAndReplace(body);

parsedBody.password = await hash(parsedBody.password, 10);

const db = await getDatabase();

// duplicate
Expand All @@ -26,14 +30,29 @@ export const CreateUser = async (body: object) => {
if (existingUser) {
throw new DuplicateError('Duplicate: user already exists.');
}

// admin
if (parsedBody.role === 'admin') {
const existingAdmin = await db.collection('users').find({
role: 'admin',
});
if (existingAdmin) {
throw new DuplicateError('Duplicate: admin already exists');
}
}

const creationStatus = await db.collection('users').insertOne(parsedBody);
const user = await db.collection('users').findOne({
_id: new ObjectId(creationStatus.insertedId),
});

return { ok: true, body: user, error: null, status: 201 };
return { ok: true, body: user, error: null };
} catch (e) {
const error = e as HttpError;
return { ok: false, body: null, error: error.message };
return {
ok: false,
body: null,
error: error.message,
};
}
};
Loading
Loading