Skip to content
Closed
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
10 changes: 10 additions & 0 deletions bin/configs.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,14 @@ export const templates = {
name: "express_oauth_google",
serverPort: "8080:8080",
},
express_auth: {
name: "express_auth",
isUrl: true,
needDB: true,
dbPort: "27017:27017",
dbName: "MongoDB",
serverPort: "8080:8080",
dbDockerImage: "mongo:latest",
dbDataPath: "/data/db",
},
};
6 changes: 6 additions & 0 deletions templates/express_auth/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
PORT=8080
DB_HOST=127.0.0.1
DB_PORT=27017
DB_NAME=auth_db
JWT_SECRET=your_secret_jwt_key_here
JWT_EXPIRES_IN=1d
15 changes: 15 additions & 0 deletions templates/express_auth/config/authConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const authConfig = {
PORT: process.env.PORT || 8080,
DB: {
HOST: process.env.DB_HOST || "127.0.0.1",
PORT: process.env.DB_PORT || 27017,
NAME: process.env.DB_NAME || "auth_db",
},
JWT: {
SECRET: process.env.JWT_SECRET || "default_secret",
EXPIRES_IN: process.env.JWT_EXPIRES_IN || "1d",
},
router: {
AUTH_PREFIX: "/api/auth",
},
};
14 changes: 14 additions & 0 deletions templates/express_auth/connection/connection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import mongoose from "mongoose";
import { authConfig } from "../config/authConfig.js";

const databaseUrl = `mongodb://${authConfig.DB.HOST}:${authConfig.DB.PORT}/${authConfig.DB.NAME}`;

export const connectDB = async () => {
try {
await mongoose.connect(databaseUrl);
console.log("MongoDB Connected Successfully.");
} catch (err) {
console.error(`MongoDB Connection Failed: ${err.message}`);
process.exit(1);
}
};
56 changes: 56 additions & 0 deletions templates/express_auth/controller/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import jwt from "jsonwebtoken";
import { User } from "../models/User.js";
import { authConfig } from "../config/authConfig.js";

const generateToken = (id) => {
return jwt.sign({ id }, authConfig.JWT.SECRET, {
expiresIn: authConfig.JWT.EXPIRES_IN,
});
};

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

try {
const userExists = await User.findOne({ email });
if (userExists) {
return res.status(400).json({ message: "User already exists" });
}

const user = await User.create({ name, email, password });

res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
token: generateToken(user._id),
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};

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

try {
const user = await User.findOne({ email });

if (user && (await user.comparePassword(password))) {
res.json({
_id: user._id,
name: user.name,
email: user.email,
token: generateToken(user._id),
});
} else {
res.status(401).json({ message: "Invalid email or password" });
}
} catch (error) {
res.status(500).json({ message: error.message });
}
};

export const getUserProfile = async (req, res) => {
res.json(req.user);
};
36 changes: 36 additions & 0 deletions templates/express_auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import express from "express";
import cors from "cors";

import { authConfig } from "./config/authConfig.js";
import { authRouter } from "./router/authRouter.js";

import { initLog } from "./logs/initLog.js";

import { connectDB } from "./connection/connection.js";

const app = express();

initLog();

app.use(cors());
app.use(express.json());

app.use(authConfig.router.AUTH_PREFIX, authRouter);

app.get("/", (req, res) => {
res.json({ message: "auth server is running" });
});

const startServer = async () => {
await connectDB();
app.listen(authConfig.PORT, () => {
console.info(
`Server is running on http://127.0.0.1:${authConfig.PORT}`,
);
console.warn(
`Test registration at http://127.0.0.1:${authConfig.PORT}${authConfig.router.AUTH_PREFIX}/register`,
);
});
};

startServer();
7 changes: 7 additions & 0 deletions templates/express_auth/logs/initLog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { existsSync, mkdirSync } from "fs";

export const initLog = () => {
if (!existsSync("./logs")) {
mkdirSync("./logs");
}
};
26 changes: 26 additions & 0 deletions templates/express_auth/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import jwt from "jsonwebtoken";
import { authConfig } from "../config/authConfig.js";
import { User } from "../models/User.js";

export const protect = async (req, res, next) => {
let token;

if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, authConfig.JWT.SECRET);

req.user = await User.findById(decoded.id).select("-password");
next();
} catch (error) {
res.status(401).json({ message: "Not authorized, token failed" });
}
}

if (!token) {
res.status(401).json({ message: "Not authorized, no token" });
}
};
35 changes: 35 additions & 0 deletions templates/express_auth/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
},
password: {
type: String,
required: true,
minlength: 6,
},
},
{ timestamps: true },
);

userSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});

userSchema.methods.comparePassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};

export const User = mongoose.model("User", userSchema);
24 changes: 24 additions & 0 deletions templates/express_auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "express_auth",
"version": "1.0.0",
"description": "Express.js server with Custom JWT Authentication and MongoDB.",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "quick_start_express",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.9.3"
},
"devDependencies": {
"nodemon": "^3.1.9"
},
"type": "module"
}
16 changes: 16 additions & 0 deletions templates/express_auth/router/authRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import express from "express";
import {
registerUser,
loginUser,
getUserProfile,
} from "../controller/authController.js";
import { protect } from "../middleware/authMiddleware.js";

const router = express.Router();

router.post("/register", registerUser);
router.post("/login", loginUser);

router.get("/profile", protect, getUserProfile);

export { router as authRouter };
16 changes: 8 additions & 8 deletions test/init.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ describe("normal init with default settings", () => {

expect(hasNodemon()).toBe(true);
expect(nodeModulesExist()).toBe(true);
}, 25000);
}, 60000);
});
});

Expand Down Expand Up @@ -185,7 +185,7 @@ describe("init --remove-deps", () => {

expect(hasNodemon()).toBe(true);
expect(nodeModulesExist()).toBe(false);
}, 25000);
}, 60000);
});
});

Expand Down Expand Up @@ -249,7 +249,7 @@ describe("init with custom template name without installing deps", () => {
},
);
verifyPackageName(validName);
}, 25000);
}, 60000);

test("valid template name: lowercase only", async () => {
const validName = "validname";
Expand All @@ -260,7 +260,7 @@ describe("init with custom template name without installing deps", () => {
},
);
verifyPackageName(validName);
}, 25000);
}, 60000);

test("valid template name: URL friendly characters", async () => {
const validName = "valid-name";
Expand All @@ -271,7 +271,7 @@ describe("init with custom template name without installing deps", () => {
},
);
verifyPackageName(validName);
}, 25000);
}, 60000);

// TODO: Add test for cases where `inquirer` prompts are used for this.
});
Expand Down Expand Up @@ -304,7 +304,7 @@ describe("init without nodemon option without installing deps.", () => {
"nodemon",
);
}
}, 25000);
}, 60000);
});
});

Expand Down Expand Up @@ -335,7 +335,7 @@ describe("init with docker-compose without cache service and db", () => {
expect(nodeModulesExist()).toBe(false);

verifyDockerFiles();
}, 25000);
}, 60000);
});
});

Expand Down Expand Up @@ -388,6 +388,6 @@ describe("init with docker-compose with cache service and db", () => {
expect(nodeModulesExist()).toBe(false);

verifyDockerFiles();
}, 25000);
}, 60000);
});
});
3 changes: 2 additions & 1 deletion test/list.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ Available Templates:
- express_mysql
- express_pg_prisma
- express_oauth_microsoft
- express_oauth_google\n`;
- express_oauth_google
- express_auth\n`;

describe("List Command", () => {
test("list", async () => {
Expand Down