Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend code #33

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions backend/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const JWT_TOKEN = ""

module.export = JWT_TOKEN
54 changes: 54 additions & 0 deletions backend/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// backend/db.js
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/paytm");

// Create a Schema for Users
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
minLength: 3,
maxLength: 30,
},
password: {
type: String,
required: true,
minLength: 6,
},
firstName: {
type: String,
required: true,
trim: true,
maxLength: 50,
},
lastName: {
type: String,
required: true,
trim: true,
maxLength: 50,
},
});

const accountSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId, // Reference to User model
ref: "User",
required: true,
},
balance: {
type: Number,
required: true,
},
});

const Account = mongoose.model("Account", accountSchema);
const User = mongoose.model("User", userSchema);

module.exports = {
User,
Account,
};
10 changes: 10 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
// backend/index.js
const express = require("express");
const cors = require("cors");
const rootRouter = require("./routes/index");

const app = express();

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

app.use("/api/v1", rootRouter);

app.listen(3000);
26 changes: 26 additions & 0 deletions backend/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { JWT_SECRET } = require("./config");
const jwt = require("jsonwebtoken");

const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;

if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(403).json({});
}

const token = authHeader.split(" ")[1];

try {
const decoded = jwt.verify(token, JWT_SECRET);

req.userId = decoded.userId;

next();
} catch (err) {
return res.status(403).json({});
}
};

module.exports = {
authMiddleware,
};
126 changes: 126 additions & 0 deletions backend/package-lock.json

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

2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.1.0",
"zod": "^3.22.4"
}
Expand Down
63 changes: 63 additions & 0 deletions backend/routes/account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// backend/routes/account.js
const express = require("express");
const { authMiddleware } = require("../middleware");
const { Account } = require("../db");
const { default: mongoose } = require("mongoose");

const router = express.Router();

router.get("/balance", authMiddleware, async (req, res) => {
const account = await Account.findOne({
userId: req.userId,
});

res.json({
balance: account.balance,
});
});

router.post("/transfer", authMiddleware, async (req, res) => {
const session = await mongoose.startSession();

session.startTransaction();
const { amount, to } = req.body;

// Fetch the accounts within the transaction
const account = await Account.findOne({ userId: req.userId }).session(
session
);

if (!account || account.balance < amount) {
await session.abortTransaction();
return res.status(400).json({
message: "Insufficient balance",
});
}

const toAccount = await Account.findOne({ userId: to }).session(session);

if (!toAccount) {
await session.abortTransaction();
return res.status(400).json({
message: "Invalid account",
});
}

// Perform the transfer
await Account.updateOne(
{ userId: req.userId },
{ $inc: { balance: -amount } }
).session(session);
await Account.updateOne(
{ userId: to },
{ $inc: { balance: amount } }
).session(session);

// Commit the transaction
await session.commitTransaction();
res.json({
message: "Transfer successful",
});
});

module.exports = router;
11 changes: 11 additions & 0 deletions backend/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// backend/user/index.js
const express = require("express");
const userRouter = require("./user");
const accountRouter = require("./account");

const router = express.Router();

router.use("/user", userRouter);
router.use("/account", accountRouter);

module.exports = router;
Loading