Skip to content

Commit

Permalink
project init
Browse files Browse the repository at this point in the history
  • Loading branch information
ibbatta committed Dec 26, 2024
0 parents commit 73e0db0
Show file tree
Hide file tree
Showing 24 changed files with 576 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .github/AUTHOR.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Dev Maurizio Battaghini | [email protected]
• Developer
— — • Twitter: https://twitter.com/battago
— — • GitHub: https://github.com/ibbatta
21 changes: 21 additions & 0 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Contributing

I love your input and I want to make contributing to this project as easy and transparent as possible, whether it's:

- Reporting a bug
- Discussing the current state of the code
- Submitting a fix
- Proposing new features
- Becoming a maintainer

### How to contributing

- Fork it!
- Create your feature branch: `git checkout -b my-new-feature`
- Commit your changes: `git commit -am 'Add some feature'`
- Push to the branch: `git push origin my-new-feature`
- Submit a pull request

## I Develop with Github

I use github to host code, to track issues and feature requests, as well as accept pull requests.
12 changes: 12 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# These are supported funding model platforms

github: [ibbatta]
patreon: ibbatta
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: https://www.paypal.me/mauriziobattaghini
40 changes: 40 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
name: Bug report
about: Create a report to help us improve
title: ""
labels: ""
assignees: ""
---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:

1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**

- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]

**Smartphone (please complete the following information):**

- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]

**Additional context**
Add any other context about the problem here.
19 changes: 19 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
42 changes: 42 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
### react ###
.DS_*
*.log
logs
**/*.backup.*
**/*.back.*



### npm ###
node_modules
package-lock.json
.npm



### Node ###
.env
*.env
*.env.*
*.local
*.local.*
*.secret
*.secret.*
coverage
dist
tmp
temp
*.tmp
*.temp
*.swp
*.swo
*.bak
*.orig
*.rej
*.sublime-project
*.sublime-workspace
.vscode
.idea
*.iml
.DS_Store
Thumbs.db
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Maurizio Battaghini

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.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# BACKEND Boilerplate

> Super minimal boilerplate to start simple node + express backend with mongoose integration
---

| Node | Express | MongoDB |
| :----------------------: | :----------------------: | :----------------------: |
| <img src="" width="50"/> | <img src="" width="50"/> | <img src="" width="50"/> |

### Features

- @Routing: the project routing ready
- @Authentication: the project provide auth and login with middleware's protection

---

### TODO:

- [x] Routing
- [x] Authentication / Access
- [x] Db connection
- [ ] ...
5 changes: 5 additions & 0 deletions nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"watch": ["src"],
"ext": ".ts,.js,.json",
"exec": " ts-node ./src/index.ts"
}
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "poke-deck",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "nodemon",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/compression": "^1.7.5",
"@types/cookie-parser": "^1.4.8",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/mongoose": "^5.11.96",
"dotenv": "^16.4.7",
"nodemon": "^3.1.9",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.2"
},
"dependencies": {
"body-parser": "^1.20.3",
"compression": "^1.7.5",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"express": "^4.21.2",
"mongoose": "^8.9.2"
}
}
16 changes: 16 additions & 0 deletions src/$configs/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import "dotenv/config";

export const PORT_FALLBACK = 8080;
export const SECRET = process.env.SECRET || "secret-string";
export const COOKIE = process.env.COOKIE || "cookie-string";

export const DB_EVENTS = {
CONNECTED: "connected",
ERROR: "error",
DISCONNECTED: "disconnected",
};

export const PROCESS_EVENTS = {
SIGINT: "SIGINT",
SIGTERM: "SIGTERM",
};
11 changes: 11 additions & 0 deletions src/$configs/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { MongoUrlType } from "$configs/type";

export const GET_MONGO_URL = ({
username,
password,
cluster,
}: MongoUrlType): string => {
const userEncoded = encodeURIComponent(username);
const passEncoded = encodeURIComponent(password);
return `mongodb+srv://${userEncoded}:${passEncoded}@${cluster}.mongodb.net/retryWrites=true&w=majority`;
};
5 changes: 5 additions & 0 deletions src/$configs/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type MongoUrlType = {
username: string;
password: string;
cluster: string;
};
12 changes: 12 additions & 0 deletions src/$helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import crypto from "crypto";

import { SECRET } from "$configs/constants";

export const random = () => crypto.randomBytes(128).toString("base64");

export const authentication = (salt: string, password: string) => {
return crypto
.createHmac("sha256", [salt, password].join("/"))
.update(SECRET)
.digest("hex");
};
64 changes: 64 additions & 0 deletions src/controllers/authentication.ctrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Request, Response } from "express";

import { COOKIE } from "$configs/constants";
import { createUser, getUserByEmail } from "$queries/users";
import { authentication, random } from "$helpers/utils";

export const register = async (req: Request, res: Response): Promise<any> => {
try {
const { email, password, username } = req.body;

if (!email || !password || !username) return res.sendStatus(400);
if (await getUserByEmail(email)) return res.sendStatus(400);

const salt = random();
const user = await createUser({
email,
username,
authentication: {
salt,
password: authentication(salt, password),
},
});

return res.status(200).json(user).end();
} catch (error) {
console.error("ERROR:", error);
return res.sendStatus(400);
}
};

export const login = async (req: Request, res: Response): Promise<any> => {
try {
const { email, password } = req.body;

if (!email || !password) return res.sendStatus(400);

const user = await getUserByEmail(email).select(
"+authentication.salt +authentication.password"
);
if (!user) res.sendStatus(400);

const expectedHas = authentication(user.authentication.salt, password);
if (user.authentication.password !== expectedHas) {
return res.sendStatus(403);
}

const salt = random();
user.authentication.sessionToken = authentication(
salt,
user._id.toString()
);
await user.save();

res.cookie(COOKIE, user.authentication.sessionToken, {
domain: "localhost",
path: "/",
});

return res.status(200).json(user).end();
} catch (error) {
console.error("ERROR:", error);
return res.sendStatus(400);
}
};
52 changes: 52 additions & 0 deletions src/controllers/user.ctrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Request, Response } from "express";

import {
getUsers,
deleteUserById,
updateUserById,
getUserById,
} from "$queries/users";

export const getAllUsers = async (
req: Request,
res: Response
): Promise<any> => {
try {
const user = await getUsers();
res.status(200).json(user);
} catch (error) {
console.error("ERROR", error);
return res.sendStatus(400);
}
};

export const deleteUser = async (req: Request, res: Response): Promise<any> => {
try {
const { id } = req.params;
const deletedUser = await deleteUserById(id);

return res.json(deletedUser);
} catch (error) {
console.error("ERROR", error);
return res.sendStatus(400);
}
};

export const updateUser = async (req: Request, res: Response): Promise<any> => {
try {
const { id } = req.params;
const { username } = req.body;

if (!username) return res.sendStatus(400);

const user = await getUserById(id);
user.username = username;

await user.save();

return res.status(200).json(user).end();
} catch (error) {
console.error("ERROR", error);
return res.sendStatus(400);
}
};
Loading

0 comments on commit 73e0db0

Please sign in to comment.