Skip to content

Commit

Permalink
Mini Wallet: Manage your day-to-day finance inside Telegram
Browse files Browse the repository at this point in the history
  • Loading branch information
NusryNizam committed Oct 10, 2023
1 parent 889e50d commit 5c00c38
Show file tree
Hide file tree
Showing 82 changed files with 4,009 additions and 0 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions server/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
npm-debug.log
.env
25 changes: 25 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local
.env

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
13 changes: 13 additions & 0 deletions server/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
FROM node:18
WORKDIR /usr/src/app
COPY package*.json ./

RUN npm install
# If you are building your code for production
RUN npm ci --omit=dev

# Bundle app source
COPY . .
EXPOSE 8080

CMD [ "node", "app.js" ]
21 changes: 21 additions & 0 deletions server/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Nusry Nizam

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
51 changes: 51 additions & 0 deletions server/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const express = require('express')
const cors = require('cors')
const cookieParser = require('cookie-parser')
const morgan = require('morgan')
const helmet = require('helmet')
require('./config/database')

const authRoutes = require('./routes/authRoutes')
const mainRoutes = require('./routes/mainRoutes')
const { auth } = require('./middleware/authMiddleware')


const app = express()

app.use(morgan('dev'))
app.use(helmet())

app.use(cookieParser())
app.use(cors({
credentials: true,
origin: process.env.ORIGIN_URL || 'http://localhost:5173',
}))
app.use(express.json())
// app.use(auth)


// app.get('/', (req, res) => {
// res.send('Home')
// })

app.get('/protected', auth, (req, res, next) => {
// console.log('protected route')
res.send({"authorized": true})
})

app.get('/logout', (req, res, next) => {
// res.cookie('jwt', '', { httpOnly: true, sameSite: 'None', secure: true })
res.send({"message": "Successfully logged out"})
})

app.use(authRoutes)
app.use(mainRoutes)

app.use((err, req, res, next) => {
// console.log(err)
res.status(500).send({error: 'Unknown Error!!!'})
})

app.listen(process.env.PORT || 8080, () => {
console.log('Listening on port ' + process.env.PORT);
})
38 changes: 38 additions & 0 deletions server/config/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const mongoose = require('mongoose')

require('dotenv').config()

const dbURI = process.env.DB_STRING

mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true
})

mongoose.connection.on('connected', () => {
console.log('Database connected..')
})

// const { MongoClient, ServerApiVersion } = require('mongodb');
// const uri = process.env.DB_STRING;
// // Create a MongoClient with a MongoClientOptions object to set the Stable API version
// const client = new MongoClient(uri, {
// serverApi: {
// version: ServerApiVersion.v1,
// strict: true,
// deprecationErrors: true,
// }
// });
// async function run() {
// try {
// // Connect the client to the server (optional starting in v4.7)
// await client.connect();
// // Send a ping to confirm a successful connection
// await client.db("admin").command({ ping: 1 });
// console.log("Pinged your deployment. You successfully connected to MongoDB!");
// } finally {
// // Ensures that the client will close when you finish/error
// await client.close();
// }
// }
// run().catch(console.dir);
91 changes: 91 additions & 0 deletions server/controllers/authControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
const User = require("../models/User.model");
const jwt = require("jsonwebtoken");

const handleErrors = (err) => {
// console.log(err.message, err.code);
let errors = { response: "" };

//Signup errors
if (err.code === 11000) {
if (err.keyValue.email) {
// errors.email = "email not available"
errors.error = "email not available";
return errors;
}
if (err.keyValue.email) {
// errors.email = "Email not accepted"
errors.error = "Email not accepted";
return errors;
}
}

if (err.message.includes("user validation failed")) {
Object.values(err.errors).forEach(({ properties }) => {
// errors[properties.path] = properties.message
errors.error = properties.message;
});
return errors;
}

// Login Errors
if (err.message.includes("Incorrect")) {
errors.error = "Email or password doesn't match";
// errors.password = "Email or password doesn't match"
return errors;
}
};

const maxAge = 7 * 24 * 60 * 60; // 7 days
const createToken = (id) => {
const token = jwt.sign({ id }, process.env.PRIVATE_KEY, {
expiresIn: maxAge,
});
return token;
};

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

try {
let user = await User.login(email, password);
// console.log('User Logged in', user._id)
const token = createToken(user._id);
// res.cookie("jwt", token, {
// maxAge: maxAge * 1000,
// httpOnly: true,
// sameSite: "None",
// secure: true,
// });
res.status(200).json({ user: user._id, token: token });
} catch (err) {
res.status(401).json(handleErrors(err));
}
};

const signup = async (req, res) => {
const { email, password } = req.body;
// console.log(req.body)
try {
const user = await User.create({
email,
password,
});
if (user) {
// console.log(user);
const token = createToken(user._id);
// res.cookie('jwt', token, {
// maxAge: maxAge * 1000,
// httpOnly: true,
// sameSite: 'None',
// secure: true
// })
res.status(201).json({ user: user._id, token: token });
}
} catch (err) {
res.status(401).json(handleErrors(err));
}
};

module.exports.login = login;
module.exports.signup = signup;
123 changes: 123 additions & 0 deletions server/controllers/mainControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
const Entry = require("../models/Entry.model");
const validator = require("validator");

const getEntries = async (req, res, next) => {
try {
let user = req.user;
console.log(user);

const products = await Entry.find({ user: user }).populate("user").exec();
res.status(200).send(products);
} catch (err) {
console.error(err);
res.status(500).send("Internal Server Error");
}
};

const addEntry = (req, res, next) => {
let { user, name, category, amount, date } = req.body;
// console.log(req.body);
let newEntry = new Entry({
user,
name,
category,
amount,
date,
});

newEntry.save((err) => {
if (err) {
res.status(500).send(err.message);
return;
}

res.status(200).send({ message: "Entry successfully added" });
return;
});
};

const deleteEntries = (req, res, nex) => {
Entry.deleteMany(
{
_id: {
$in: req.body,
},
},
function (err, result) {
if (err) {
res.status(500).send({ error: err.message });
} else {
res.status(200).send(result);
}
}
);
};

const getEntriesByMonth = async (req, res) => {
const { year, month } = req.params;

if (
!validator.isInt(year, { min: 1900, max: 3000 }) ||
!validator.isInt(month, { min: 1, max: 12 })
) {
return res.status(400).json({ error: "Invalid year or month." });
}

const startDate = new Date(year, month - 1, 1); // month is 0-based index in JavaScript Date object
const endDate = new Date(year, month, 0);

console.log(req.params);

try {
const entries = await Entry.aggregate([
{
$match: {
date: {
$gte: startDate,
$lte: endDate,
},
},
},
{
$group: {
_id: "$category",
total: { $sum: "$amount" },
},
},
]);

const result = {
month: month,
year: year,
entries: entries,
};

if (entries.length === 0) {
return res.status(200).send({
month: month,
year: year,
entries: [
{
_id: "income",
total: 0,
},
{
_id: "expense",
total: 0,
},
],
});
}

return res.status(200).send(result);
} catch (error) {
res.status(500).send({ message: "Error" });
}
};

module.exports = {
getEntries,
addEntry,
deleteEntries,
getEntriesByMonth,
};

0 comments on commit 5c00c38

Please sign in to comment.