This project provides a RESTful API for managing bank account balances and transferring money between accounts. The API is built using Node.js, Express, and MongoDB with Mongoose.
- Clone the repository:
git clone https://github.com/yourusername/bank-account-management-api.git
- Navigate to the project directory:
cd /backend
- Install dependencies:
npm install
- Create a
.env
file in the root directory and add your environment variables:PORT=3000 SERVER_KEY1=your_jwt_secret_key MONGODB_URI=your_mongodb_connection_string
- Start the server:
npm start
Use the following base URL to access the API:
- URL:
/api/v1/user/signup
- Method:
POST
- Body:
{ "firstname": "John", "lastname": "Doe", "username": "john.doe@example.com", "password": "your_password" }
- Response:
{ "err": false, "message": "User created successfully" }
- URL:
/api/v1/user/signin
- Method:
POST
- Body:
{ "username": "john.doe@example.com", "password": "your_password" }
- Response:
{ "err": false, "msg": "LOGIN SUCCESSFUL", "token": "your_jwt_token" }
- URL:
/api/v1/user/balance
- Method:
GET
- Headers:
Authorization: Bearer your_jwt_token
- Response:
{ "err": false, "balance": 1000 }
- URL:
/api/v1/user/transfer
- Method:
POST
- Headers:
Authorization: Bearer your_jwt_token
- Body:
{ "amount": 100, "to": "recipient_user_id" }
- Response:
{ "message": "Transfer successful" }
//import jwt
const jwt = require("jsonwebtoken");
//middleware
const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(403).json({ err: true, msg: "No token provided" });
}
const token = authHeader.split(" ")[1];
console.log("Received token:", token);
//verify server keY
try {
const decoded = jwt.verify(token, process.env.YOUR_KEY_HERE);
req.user = decoded;
next(); //PASSING ROUTE NEXT ROUTE
} catch (err) {
console.error("JWT verification error:", err);
return res.status(403).json({ err: true, msg: "Invalid token" });
}
};
The authMiddleware
function is used to protect routes that require authentication. It verifies the JWT token and attaches the user information to the request object.
//user
const UserSchema = new mongoose.Schema({
firstname: String,
lastname: String,
username: { type: String, unique: true },
password: String,
});
//account
const Bankschema = new mongoose.Schema({
userID: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
Balance: { type: Number, required: true },
});