Skip to content

Commit

Permalink
reviuwing
Browse files Browse the repository at this point in the history
  • Loading branch information
nin0-dev committed Oct 25, 2024
1 parent b9a2fd3 commit 50cbb38
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/common/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export enum ErrorCode {
ConflictError,
PermissionError
}

export function sendError(
res: FastifyReply,
location: "ws" | "rest",
Expand Down Expand Up @@ -40,12 +41,12 @@ export function sendError(
}
default: {
res.code(400);
return {
code,
message
};
}
}
return {
code,
message
};
} else {
return {}; // tbd
}
Expand Down
7 changes: 7 additions & 0 deletions src/rest/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ async function plugin(fst: FastifyInstance, opts) {
ErrorCode.ValidationError,
"CAPTCHA is expired or invalid"
);

// Check for existing info
if (
await psqlClient.query("SELECT id FROM users WHERE username=$1 OR email=$2", [
Expand All @@ -104,6 +105,7 @@ async function plugin(fst: FastifyInstance, opts) {
ErrorCode.ConflictError,
"Username or email are already registered"
);

// Moderate username
if (shouldModerate(body.username).newText !== body.username) {
return sendError(
Expand All @@ -113,14 +115,17 @@ async function plugin(fst: FastifyInstance, opts) {
"Username contains restricted words"
);
}

// Hash password
const hashedPassword = await hash(body.password, salt);

// Add user to database
const newUserID = generateID();
await psqlClient.query(
"INSERT INTO users (id, username, email, password) VALUES ($1, $2, $3, $4)",
[newUserID, body.username, body.email, hashedPassword]
);

// Generate confirm email
const emailConfirmToken = encodeURIComponent(
randomBytes(60).toString("base64").replace("+", "")
Expand Down Expand Up @@ -156,6 +161,7 @@ async function plugin(fst: FastifyInstance, opts) {
},
async function handler(request, res) {
const token = (request.query as any).token;

// Check if token is valid
const query = await psqlClient.query(
"SELECT id FROM email_verifications WHERE token=$1",
Expand All @@ -164,6 +170,7 @@ async function plugin(fst: FastifyInstance, opts) {
if (query.rows.length === 0) {
return sendError(res, "rest", ErrorCode.DataError, "Invalid verify token");
}

// Delete token
await psqlClient.query("DELETE FROM email_verifications WHERE token=$1", [token]);
await psqlClient.query("UPDATE users SET activated=true WHERE id=$1", [
Expand Down

0 comments on commit 50cbb38

Please sign in to comment.