Skip to content
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
23 changes: 23 additions & 0 deletions .github/workflows/test.yml-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
14 changes: 14 additions & 0 deletions prisma.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: process.env["DATABASE_URL"],
},
});
38 changes: 38 additions & 0 deletions prisma/migrations/20260206215804_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
-- CreateTable
CREATE TABLE "users_auth" (
"id" SERIAL NOT NULL,
"name" VARCHAR(255) NOT NULL,
"email" VARCHAR(255) NOT NULL,
"password" VARCHAR(255) NOT NULL,
"activationToken" VARCHAR(255),
"createdAt" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(6) NOT NULL,

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

-- CreateTable
CREATE TABLE "tokens_auth" (
"id" SERIAL NOT NULL,
"refreshToken" VARCHAR(255) NOT NULL,
"createdAt" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(6) NOT NULL,
"userId" INTEGER NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX "users_auth_email_key" ON "users_auth"("email");

-- CreateIndex
CREATE UNIQUE INDEX "users_auth_activationToken_key" ON "users_auth"("activationToken");

-- CreateIndex
CREATE UNIQUE INDEX "tokens_auth_refreshToken_key" ON "tokens_auth"("refreshToken");

-- CreateIndex
CREATE UNIQUE INDEX "tokens_auth_userId_key" ON "tokens_auth"("userId");

-- AddForeignKey
ALTER TABLE "tokens_auth" ADD CONSTRAINT "tokens_auth_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users_auth"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- A unique constraint covering the columns `[resetToken]` on the table `users_auth` will be added. If there are existing duplicate values, this will fail.

*/
-- AlterTable
ALTER TABLE "users_auth" ADD COLUMN "resetToken" VARCHAR(255);

-- CreateIndex
CREATE UNIQUE INDEX "users_auth_resetToken_key" ON "users_auth"("resetToken");
11 changes: 11 additions & 0 deletions prisma/migrations/20260210160621_add_pending_email/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- A unique constraint covering the columns `[pendingEmail]` on the table `users_auth` will be added. If there are existing duplicate values, this will fail.

*/
-- AlterTable
ALTER TABLE "users_auth" ADD COLUMN "pendingEmail" VARCHAR(255);

-- CreateIndex
CREATE UNIQUE INDEX "users_auth_pendingEmail_key" ON "users_auth"("pendingEmail");
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
Warnings:

- You are about to drop the column `resetToken` on the `users_auth` table. All the data in the column will be lost.
- A unique constraint covering the columns `[passwordResetToken]` on the table `users_auth` will be added. If there are existing duplicate values, this will fail.
- A unique constraint covering the columns `[pendingEmailToken]` on the table `users_auth` will be added. If there are existing duplicate values, this will fail.

*/
-- DropIndex
DROP INDEX "users_auth_resetToken_key";

-- AlterTable
ALTER TABLE "users_auth" DROP COLUMN "resetToken",
ADD COLUMN "passwordResetToken" VARCHAR(255),
ADD COLUMN "pendingEmailToken" VARCHAR(255);

-- CreateIndex
CREATE UNIQUE INDEX "users_auth_passwordResetToken_key" ON "users_auth"("passwordResetToken");

-- CreateIndex
CREATE UNIQUE INDEX "users_auth_pendingEmailToken_key" ON "users_auth"("pendingEmailToken");
19 changes: 19 additions & 0 deletions prisma/migrations/20260326152454_add_social_accounts/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-- AlterTable
ALTER TABLE "users_auth" ALTER COLUMN "password" DROP NOT NULL;

-- CreateTable
CREATE TABLE "social_accounts_auth" (
"id" SERIAL NOT NULL,
"provider" VARCHAR(50) NOT NULL,
"providerId" VARCHAR(255) NOT NULL,
"userId" INTEGER NOT NULL,
"createdAt" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
CREATE UNIQUE INDEX "social_accounts_auth_provider_providerId_key" ON "social_accounts_auth"("provider", "providerId");

-- AddForeignKey
ALTER TABLE "social_accounts_auth" ADD CONSTRAINT "social_accounts_auth_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users_auth"("id") ON DELETE CASCADE ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- AlterTable
ALTER TABLE "users_auth" ADD COLUMN "activationExpiresAt" TIMESTAMPTZ(6),
ADD COLUMN "passwordResetExpiresAt" TIMESTAMPTZ(6),
ADD COLUMN "pendingEmailExpiresAt" TIMESTAMPTZ(6);
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
50 changes: 50 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
}

model User {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
email String @unique @db.VarChar(255)
password String? @db.VarChar(255)
activationToken String? @unique @db.VarChar(255)
activationExpiresAt DateTime? @db.Timestamptz(6)
createdAt DateTime @default(now()) @db.Timestamptz(6)
updatedAt DateTime @updatedAt @db.Timestamptz(6)
passwordResetToken String? @unique @db.VarChar(255)
passwordResetExpiresAt DateTime? @db.Timestamptz(6)
pendingEmail String? @unique @db.VarChar(255)
pendingEmailToken String? @unique @db.VarChar(255)
pendingEmailExpiresAt DateTime? @db.Timestamptz(6)
tokens Token[]
socialAccounts SocialAccount[]

@@map("users_auth")
}

model SocialAccount {
id Int @id @default(autoincrement())
provider String @db.VarChar(50)
providerId String @db.VarChar(255)
userId Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @db.Timestamptz(6)

@@unique([provider, providerId])
@@map("social_accounts_auth")
}

model Token {
id Int @id @default(autoincrement())
refreshToken String @unique @db.VarChar(255)
createdAt DateTime @default(now()) @db.Timestamptz(6)
updatedAt DateTime @updatedAt @db.Timestamptz(6)
userId Int @unique
user User @relation(fields: [userId], references: [id])

@@map("tokens_auth")
}
179 changes: 179 additions & 0 deletions src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { v4 as uuidv4 } from 'uuid';
import { userService } from '../services/user.service.js';
import { authService } from '../services/auth.service.js';
import { ApiError } from '../utils/api.error.js';
import { logger } from '../utils/logger.js';
import passport from '../utils/passport.js';

const register = async (req, res) => {
const { name, email, password } = req.body;

await authService.register(name, email, password);

res.send({ message: 'Registration successful' });
};

const activate = async (req, res) => {
const { activationToken } = req.params;

const activatedUser = await authService.activate(activationToken);

res.send(userService.normalize(activatedUser));
};

const sendAuthentication = async (res, user) => {
const {
user: normalizedUser,
accessToken,
refreshToken,
} = await authService.authenticate(user);

res.cookie('refreshToken', refreshToken, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: true,
sameSite: 'lax',
});
res.send({ user: normalizedUser, accessToken });
};

const login = async (req, res) => {
const { email, password } = req.body;

const user = await authService.login(email, password);

await sendAuthentication(res, user);
};

const refresh = async (req, res) => {
const { refreshToken } = req.cookies;

const user = await authService.refresh(refreshToken);

await sendAuthentication(res, user);
};

const logout = async (req, res) => {
const { refreshToken } = req.cookies;

await authService.logout(refreshToken);

res.clearCookie('refreshToken');

res.send({ message: 'Logged out successfully' });
};

const requestPasswordReset = async (req, res) => {
const { email } = req.body;

await authService.requestPasswordReset(email);

res.clearCookie('refreshToken');
res.send({ message: 'Password reset email sent' });
};

const confirmPasswordReset = async (req, res) => {
const { passwordResetToken } = req.params;
const { password } = req.body;

await authService.confirmPasswordReset(passwordResetToken, password);

res.clearCookie('refreshToken');
res.send({ message: 'Password reset successful' });
};

const confirmEmailChange = async (req, res) => {
const { pendingEmailToken } = req.params;

await authService.confirmEmailChange(pendingEmailToken);

res.clearCookie('refreshToken');
res.send({ message: 'Email updated successfully' });
};

const socialCallback = (provider) => (req, res, next) => {
passport.authenticate(
provider,
{ session: false },
async (err, user, info) => {
if (err) {
return next(err);
}

const isLink = req.session?.socialAuthIntent === 'link';

if (req.session?.socialAuthIntent) {
delete req.session.socialAuthIntent;
}

if (!user) {
const errorMsg = encodeURIComponent(
info?.message || 'Authentication failed',
);
const redirectPath = isLink ? '/profile' : '/login';

return res.redirect(
`${process.env.CLIENT_HOST}${redirectPath}?error=${errorMsg}`,
);
}

if (isLink) {
return res.redirect(
`${process.env.CLIENT_HOST}/profile?linked=${provider}`,
);
}

const code = uuidv4();

req.session.authCode = code;
req.session.authUserId = user.id;

req.session.save((saveErr) => {
if (saveErr) {
return next(saveErr);
}

res.redirect(`${process.env.CLIENT_HOST}/auth/callback?code=${code}`);
});
},
)(req, res, next);
};

const exchangeCode = async (req, res) => {
const { code } = req.body;

if (!code || !req.session?.authCode || req.session.authCode !== code) {
throw ApiError.badRequest('Invalid or expired authorization code');
}

const userId = req.session.authUserId;

req.session.destroy((err) => {
if (err) {
logger.error('Failed to destroy session after code exchange', {
message: err.message,
});
}
});

const user = await userService.getById(userId);

if (!user) {
throw ApiError.badRequest('User not found');
}

await sendAuthentication(res, user);
};

export const authController = {
register,
activate,
login,
refresh,
logout,
requestPasswordReset,
confirmPasswordReset,
confirmEmailChange,
socialCallback,
exchangeCode,
};
Loading
Loading