Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ REDIS_PASSWORD=''
REDIS_PORT=6379
REDIS_USERNAME=''
JOBS_RETENTION_HOURS=24

OTP_EXPIRATION_MINUTES=15
1 change: 1 addition & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ env:
REDIS_PORT: '6379'
REDIS_USERNAME: 'default'
JOBS_RETENTION_HOURS: '24'
OTP_EXPIRATION_MINUTES: '15'

jobs:
build:
Expand Down
1 change: 1 addition & 0 deletions .woodpecker/.backend-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ x-common: &common
- REDIS_PORT=6379
- REDIS_USERNAME=default
- JOBS_RETENTION_HOURS=24
- OTP_EXPIRATION_MINUTES=15

pipeline:
setup:
Expand Down
11 changes: 3 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"concurrently": "^8.2.0",
"cors": "^2.8.5",
"cross-spawn": "^7.0.3",
"date-fns": "^2.30.0",
"dotenv": "^16.0.0",
"dotenv-cli": "^7.3.0",
"express": "^4.17.1",
Expand Down
21 changes: 21 additions & 0 deletions prisma/migrations/20231204190920_add_tokens_table/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- CreateEnum
CREATE TYPE "TypeToken" AS ENUM ('RESET_PASSWORD');

-- CreateTable
CREATE TABLE "Tokens" (
"id" TEXT NOT NULL,
"created_at" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"token" TEXT NOT NULL,
"type" "TypeToken" NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"user_id" TEXT,

CONSTRAINT "Tokens_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "Tokens_user_id_type_key" ON "Tokens"("user_id", "type");

-- AddForeignKey
ALTER TABLE "Tokens" ADD CONSTRAINT "Tokens_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
18 changes: 18 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ model User {
email String @unique
password String
name String?
token Tokens[]
}

model Session {
Expand All @@ -28,3 +29,20 @@ model Session {
accessToken String @unique
refreshToken String @unique
}

model Tokens {
id String @id @default(uuid())
createdAt DateTime @default(now()) @map("created_at") @db.Timestamp(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamp(6)
token String
type TypeToken
expiresAt DateTime @map("expires_at")
userId String? @map("user_id")
user User? @relation(fields: [userId], references: [id])

@@unique([userId, type])
}

enum TypeToken {
RESET_PASSWORD
}
8 changes: 8 additions & 0 deletions src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ const envVarsSchema = z
'JOBS RETENTION HOURS must be a number',
),
REDIS_USERNAME: z.string(),
OTP_EXPIRATION_MINUTES: z
.string()
.transform((val) => Number(val))
.refine(
(val) => !Number.isNaN(val),
'OTP EXPIRATION TIME must be a number',
),
})
.passthrough();

Expand Down Expand Up @@ -76,4 +83,5 @@ export const config: Config = {
redisPort: envVars.REDIS_PORT,
redisUsername: envVars.REDIS_USERNAME,
jobsRetentionHours: envVars.JOBS_RETENTION_HOURS,
otpExpirationMinutes: envVars.OTP_EXPIRATION_MINUTES,
};
10 changes: 10 additions & 0 deletions src/config/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export const errors = {
errorCode: 400_003,
description: 'Invalid token',
},
INVALID_CODE: {
httpCode: 400,
errorCode: 400_004,
description: 'Invalid code',
},
UNAUTHENTICATED: {
httpCode: 401,
errorCode: 401_000,
Expand All @@ -29,6 +34,11 @@ export const errors = {
errorCode: 401_001,
description: 'Token expired',
},
CODE_EXPIRED: {
httpCode: 403,
errorCode: 403_001,
description: 'Code has expired',
},
NOT_FOUND: {
httpCode: 404,
errorCode: 404_000,
Expand Down
26 changes: 25 additions & 1 deletion src/controllers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@ import {
Delete,
Get,
Path,
Post,
Put,
Request,
Route,
Security,
} from 'tsoa';
import { UserService } from 'services';
import { ReturnUser, UpdateUserParams, AuthenticatedRequest } from 'types';
import {
ReturnUser,
UpdateUserParams,
AuthenticatedRequest,
PasswordResetCodeRequest,
ResetPassword,
} from 'types';

@Route('v1/users')
export class UsersControllerV1 extends Controller {
Expand Down Expand Up @@ -58,4 +65,21 @@ export class UsersControllerV1 extends Controller {
await UserService.destroy(id);
this.setStatus(httpStatus.NO_CONTENT);
}

@Post('/requestResetPasswordCode')
public async requestResetPasswordCode(
@Body() requestBody: PasswordResetCodeRequest,
): Promise<void> {
await UserService.requestResetPasswordCode(requestBody.email);
this.setStatus(httpStatus.OK);
}

@Post('/resetPassword')
public async resetPassword(
@Body() requestBody: ResetPassword,
): Promise<void> {
const { email, code, newPassword } = requestBody;
await UserService.resetPassword(email, code, newPassword);
this.setStatus(httpStatus.OK);
}
}
57 changes: 36 additions & 21 deletions src/emails/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,48 @@ import pug from 'pug';

import { config } from 'config/config';

const createTransporter = () => {
const testTransporter = nodemailer.createTransport({
host: config.smtpHost,
port: config.smtpPort,
auth: {
user: config.smtpUser,
pass: config.smtpPassword,
},
});
return testTransporter;
};
const emailTransporter = nodemailer.createTransport({
host: config.smtpHost,
port: config.smtpPort,
auth: {
user: config.smtpUser,
pass: config.smtpPassword,
},
});

export async function sendSignUpEmail(
appName: string,
const sendEmail = async (
emailTo: string,
): Promise<void> {
const subject = ` Welcome to ${appName}!!`;
const html = pug.renderFile('src/emails/template.pug', {
appName,
username: emailTo,
});

const emailTransporter = createTransporter();
subject: string,
html: string,
): Promise<void> => {
await emailTransporter.sendMail({
from: config.emailFrom,
to: emailTo,
subject,
html,
});
};

export async function sendSignUpEmail(emailTo: string): Promise<void> {
const subject = `Welcome to ${config.appName}!!`;
const html = pug.renderFile('src/emails/signUpTemplate.pug', {
appName: config.appName,
username: emailTo,
});

await sendEmail(emailTo, subject, html);
}

export const sendResetPasswordCode = async (
emailTo: string,
code: string,
): Promise<void> => {
const subject = `${config.appName} password recovery code`;
const html = pug.renderFile('src/emails/resetPasswordCodeTemplate.pug', {
appName: config.appName,
username: emailTo,
code,
});

await sendEmail(emailTo, subject, html);
};
6 changes: 6 additions & 0 deletions src/emails/resetPasswordCodeTemplate.pug
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
html
head
title #{appName} password reset code
body
h1 Hello #{username},
p To recover your password use the next code #{code}.
File renamed without changes.
Loading