Skip to content

Commit a6bd65c

Browse files
committed
final:fixed
1 parent 41a69a2 commit a6bd65c

File tree

5 files changed

+11
-42
lines changed

5 files changed

+11
-42
lines changed

.env

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,7 @@
11

2-
# Environment variables declared in this file are automatically made available to Prisma.
3-
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
4-
5-
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
6-
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
7-
8-
# The following `prisma+postgres` URL is similar to the URL produced by running a local Prisma Postgres
9-
# server with the `prisma dev` CLI command, when not choosing any non-default ports or settings. The API key, unlike the
10-
# one found in a remote Prisma Postgres URL, does not contain any sensitive information.
11-
122
# add you own url and secret key
133
# DATABASE_URL="postgresql://username:password@host:port/database"
144
# JWT_SECRET="your-secret-key"
155

16-
# DATABASE_URL="postgresql://postgres.uycuryvjjhznvsfumxre:[email protected]:5432/postgres"
17-
# JWT_SECRET="roshanishacker"
186
DATABASE_URL="postgresql://postgres.uycuryvjjhznvsfumxre:[email protected]:5432/postgres"
197
JWT_SECRET="roshanishacker"

Dockerfile

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ FROM node:20-alpine
1818
WORKDIR /app
1919
RUN npm install -g pnpm
2020

21-
# Set production environment
2221
ENV NODE_ENV=production
2322

2423
COPY package.json pnpm-lock.yaml ./
@@ -28,7 +27,6 @@ COPY --from=builder /app/dist ./dist
2827
COPY --from=builder /app/node_modules ./node_modules
2928
COPY prisma ./prisma
3029

31-
# Generate Prisma client for production
3230
RUN pnpm exec prisma generate
3331

3432
EXPOSE 4000

src/controllers/authController.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { RegisterInput, LoginInput } from "../dto/auth.dto";
55
class AuthController {
66
private service = new AuthService();
77

8-
// Register user
98
register = async (req: Request, res: Response) => {
109
try {
1110
const body = req.body as RegisterInput;
@@ -26,18 +25,16 @@ class AuthController {
2625
}
2726
};
2827

29-
// Login user
3028
login = async (req: Request, res: Response) => {
3129
try {
3230
const body = req.body as LoginInput;
3331
const result = await this.service.login(body.email, body.password);
3432

35-
// Set JWT token as HTTP-only cookie
3633
res.cookie("token", result.token, {
3734
httpOnly: true,
3835
secure: process.env.NODE_ENV === "production",
3936
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
40-
maxAge: 24 * 60 * 60 * 1000, // 1 day
37+
maxAge: 24 * 60 * 60 * 1000,
4138
domain: process.env.COOKIE_DOMAIN || undefined,
4239
path: "/",
4340
});
@@ -57,7 +54,6 @@ class AuthController {
5754
}
5855
};
5956

60-
// Logout user
6157
logout = async (req: Request, res: Response) => {
6258
res.clearCookie("token", {
6359
httpOnly: true,

src/server.ts

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,31 @@ import router from "./routes/router";
55
import cookieParser from "cookie-parser";
66
import cors from "cors";
77

8-
// Load environment variables
98
dotenv.config();
109
const PORT = Number(process.env.PORT) || 4000;
1110
const app = express();
1211
app.use(express.json());
1312

1413
app.use(cookieParser());
1514

16-
// CORS options
1715
const corsOptions = {
1816
origin:
1917
process.env.NODE_ENV === "production"
2018
? [
2119
"https://blog-content-management-demo.vercel.app",
2220
"https://blogcontentmanagement.netlify.app",
23-
...(process.env.FRONTEND_URL ? [process.env.FRONTEND_URL] : []), // Add custom frontend URL if provided
21+
...(process.env.FRONTEND_URL ? [process.env.FRONTEND_URL] : []),
2422
]
25-
: true, // Allow all origins in development
26-
credentials: true, // allow cookies to be sent
27-
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], // Explicitly allow methods
28-
allowedHeaders: ["Content-Type", "Authorization", "Cookie"], // Allow headers including cookies
29-
optionsSuccessStatus: 200, // For legacy browser support
23+
: true,
24+
credentials: true,
25+
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
26+
allowedHeaders: ["Content-Type", "Authorization", "Cookie"],
27+
optionsSuccessStatus: 200,
3028
};
3129

3230
app.use(cors(corsOptions));
3331
app.use(morgan("combined"));
3432

35-
// Health check endpoint
3633
app.get("/health", (req, res) => {
3734
res.status(200).json({
3835
status: "OK",
@@ -45,8 +42,8 @@ app.get("/health", (req, res) => {
4542
app.use("/api", router);
4643

4744
app.listen(PORT, "0.0.0.0", () => {
48-
console.log(`🚀 App is running and listening on port: ${PORT}`);
49-
console.log(`🌍 Environment: ${process.env.NODE_ENV || "development"}`);
50-
console.log(`🍪 Cookie domain: ${process.env.COOKIE_DOMAIN || "not set"}`);
51-
console.log(`🔗 Frontend URL: ${process.env.FRONTEND_URL || "not set"}`);
45+
console.log(`App is running and listening on port: ${PORT}`);
46+
console.log(`Environment: ${process.env.NODE_ENV || "development"}`);
47+
console.log(`Cookie domain: ${process.env.COOKIE_DOMAIN || "not set"}`);
48+
console.log(`Frontend URL: ${process.env.FRONTEND_URL || "not set"}`);
5249
});

src/services/authServices.ts

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,19 @@ import { generateToken } from "../utils/generateTokenJWT";
44
import { Response } from "express";
55

66
export class AuthService {
7-
// Register a new user
87
async register(
98
email: string,
109
password: string,
1110
name?: string,
1211
role?: "USER" | "ADMIN",
1312
) {
14-
// Check if user already exists
1513
const existingUser = await prisma.user.findUnique({ where: { email } });
1614
if (existingUser) {
1715
throw new Error("A user with this email already exists");
1816
}
1917

20-
//Hash the password
2118
const hashedPassword = await bcrypt.hash(password, 12);
2219

23-
//Create new user
2420
const user = await prisma.user.create({
2521
data: {
2622
email,
@@ -30,7 +26,6 @@ export class AuthService {
3026
},
3127
});
3228

33-
// Generate JWT token
3429
const token = generateToken({
3530
id: user.id,
3631
email: user.email,
@@ -41,17 +36,13 @@ export class AuthService {
4136
return { user, token };
4237
}
4338

44-
// Login existing user
4539
async login(email: string, password: string) {
46-
// Find user by email
4740
const user = await prisma.user.findUnique({ where: { email } });
4841
if (!user) throw new Error("User not found");
4942

50-
// Compare password
5143
const isMatch = await bcrypt.compare(password, user.password);
5244
if (!isMatch) throw new Error("Invalid credentials");
5345

54-
// Generate token
5546
const token = generateToken({
5647
id: user.id,
5748
email: user.email,
@@ -62,7 +53,6 @@ export class AuthService {
6253
return { user, token };
6354
}
6455

65-
// Logout user (clear JWT cookie)
6656
async logout(res: Response) {
6757
try {
6858
res.clearCookie("token", {

0 commit comments

Comments
 (0)