Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
53174a5
folders done
hamdiolad Apr 21, 2024
ffcaee0
backend
hamdiolad Apr 21, 2024
8017a70
changed some codes
hamdiolad Apr 22, 2024
ba44833
backend code added
hamdiolad Apr 22, 2024
9aa4482
frontend folder created
hamdiolad Apr 22, 2024
9863e67
more code added
hamdiolad Apr 22, 2024
0de07d2
frontend done
hamdiolad Apr 23, 2024
ed61c26
debugging
hamdiolad Apr 23, 2024
7b37b1c
css added
hamdiolad Apr 23, 2024
2c82404
debugging
hamdiolad Apr 23, 2024
7984ff7
.
hamdiolad Apr 23, 2024
2058523
uppdated packagejson
hamdiolad Apr 23, 2024
ea768af
.
hamdiolad Apr 23, 2024
0a55925
packagejson
hamdiolad Apr 23, 2024
d796bd8
fixing dependecies
hamdiolad Apr 23, 2024
261825e
.
hamdiolad Apr 23, 2024
b02bd9a
mongodb
hamdiolad Apr 23, 2024
542e18f
errors
hamdiolad Apr 23, 2024
58200d1
env added
hamdiolad Apr 25, 2024
1b0385d
fixed env issues
hamdiolad Apr 25, 2024
6a9a56d
frontedn env
hamdiolad Apr 25, 2024
d607679
.
hamdiolad Apr 25, 2024
9f27a49
test
hamdiolad Apr 25, 2024
413bd8d
env
hamdiolad Apr 25, 2024
41f5873
mongo
hamdiolad Apr 25, 2024
a0cfa65
debug
hamdiolad Apr 25, 2024
b358596
mongodb atlas
hamdiolad Apr 25, 2024
1c4139f
error
hamdiolad Apr 25, 2024
d322c8e
fixed error on env
hamdiolad Apr 25, 2024
cc6153c
fixed
hamdiolad Apr 25, 2024
7109afb
added code to serve
hamdiolad Apr 25, 2024
4c22c1a
done i hope
hamdiolad Apr 25, 2024
9bda6cd
..
hamdiolad Apr 25, 2024
4705ccf
code added
hamdiolad Apr 25, 2024
d305fd9
test
hamdiolad Apr 25, 2024
3947c30
dotenv
hamdiolad Apr 26, 2024
a05c939
.....
hamdiolad Apr 26, 2024
16632c7
server.js
hamdiolad Apr 26, 2024
7d28ee1
debugging serverjs
hamdiolad Apr 26, 2024
8cbe929
mmmm
hamdiolad Apr 26, 2024
6a1f8f4
fixed error
hamdiolad Apr 26, 2024
f70bb7c
endpints edited
hamdiolad Apr 26, 2024
64594c5
done
hamdiolad Apr 26, 2024
ebb013b
.
hamdiolad Apr 26, 2024
0256a5a
..
hamdiolad Apr 26, 2024
1d57f8b
login
hamdiolad Apr 26, 2024
cfe618a
log out page
hamdiolad Apr 26, 2024
b91438f
log out page
hamdiolad Apr 26, 2024
4cba976
p
hamdiolad Apr 26, 2024
6760dde
loggot
hamdiolad Apr 26, 2024
096dbae
log
hamdiolad Apr 26, 2024
4eb5372
...
hamdiolad Apr 26, 2024
79e0b65
o
hamdiolad Apr 26, 2024
0784bae
fix
hamdiolad Apr 26, 2024
e9d64d5
log out done
hamdiolad Apr 26, 2024
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: 2 additions & 1 deletion backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
package-lock.json
package-lock.json
.env
21 changes: 21 additions & 0 deletions backend/authenticateUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import UserModel from "./models/userModel.js";

export const authenticateUser = async (req, res, next) => {
const accessToken = req.header("Authorization");

if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
)
try {
const user = await UserModel.findOne({ accessToken: accessToken });
if (user) {
req.user = user;
next();
} else {
res.status(401).json({ success: false, response: "please log in" });
}
} catch (e) {
res.status(500).json({ success: false, response: e.message });
}
};
37 changes: 37 additions & 0 deletions backend/models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import mongoose from "mongoose";
import crypto from "crypto";

const { Schema } = mongoose;

const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
minlength: 2, // corrected typo: minlenght -> minlength
},
password: {
type: String,
required: true,
minlength: 6,
},
email: {
type: String,
required: true,
unique: true,
},
accessToken: {
type: String,
default: () => crypto.randomBytes(128).toString("hex"),
required: false,
},
},
{
timestamps: true,
}
);

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

export default UserModel;
12 changes: 10 additions & 2 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,25 @@
"description": "Starter project to get up and running with express quickly",
"scripts": {
"start": "babel-node server.js",
"dev": "nodemon server.js --exec babel-node"
"dev": "nodemon server.js --exec babel-node",
"build": "babel src -d dist"
},
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"@babel/core": "^7.17.9",
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"bcrypt": "^5.0.0",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.17.3",
"mongoose": "^8.0.0",
"express-async-handler": "^1.2.0",
"express-list-endpoints": "^7.1.0",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.5.0",
"mongoose": "^8.3.2",
"nodemon": "^3.0.1"
}
}
244 changes: 244 additions & 0 deletions backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
import express from "express";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";

import UserModel from "../models/userModel.js"; // Make sure to import your user model here

import asyncHandler from "express-async-handler";
import dotenv from "dotenv";
import { authenticateUser } from "../authenticateUser.js"; // If you have an authentication middleware, import it here

dotenv.config();

const router = express.Router();

const generateToken = (user) => {
// Function to generate JWT token
return jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "24h",
});
};

// Route for user registration
router.post(
"/register",
asyncHandler(async (req, res) => {
const { username, password, email } = req.body;
try {
// Check if all required fields are provided
if (!username || !password || !email) {
res.status(400);
throw new Error("Please provide all fields");
}
// Check if user with the same username or email already exists
const existingUser = await UserModel.findOne({
$or: [{ username }, { email }],
});
if (existingUser) {
res.status(400);
throw new Error(
`User with ${
existingUser.username === username ? "username" : "email"
} already exists`
);
}
// Hash the password
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);
// Create a new user
const newUser = new UserModel({
username,
email,
password: hashedPassword,
});
await newUser.save();
// Respond with success message and token
res.status(201).json({
success: true,
response: {
username: newUser.username,
email: newUser.email,
id: newUser._id,
accessToken: generateToken(newUser),
},
});
} catch (e) {
// Handle any errors
res.status(500).json({ success: false, response: e.message });
}
})
);

// Route for user login
router.post(
"/login",
asyncHandler(async (req, res) => {
const { username, password } = req.body;
try {
// Find user by username
const user = await UserModel.findOne({ username });
if (!user) {
return res
.status(401)
.json({ success: false, response: "User not found" });
}
// Compare passwords
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res
.status(401)
.json({ success: false, response: "Incorrect password" });
}
// Respond with success message and token
res.status(200).json({
success: true,
response: {
username: user.username,
email: user.email,
id: user._id,
accessToken: generateToken(user),
},
});
} catch (error) {
// Handle any errors
res.status(500).json({
success: false,
response: {
message: error.message,
},
});
}
})
);

// Sample route accessible only to logged-in users
router.get(
"/logged-in",
authenticateUser, // Authentication middleware to verify JWT token
asyncHandler(async (req, res) => {
res.status(200).json({
success: true,
response: {
message: "User is logged in",
},
});
})
);

export default router;

/*import express from "express";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";

import UserModel from "../models/userModel.js";

import asyncHandler from "express-async-handler";
import dotenv from "dotenv";
import { authenticateUser } from "../authenticateUser.js";

dotenv.config();

const router = express.Router();

const generateToken = (user) => {
return jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "24h",
});
};

router.post(
"/register",
asyncHandler(async (req, res) => {
const { username, password, email } = req.body;
try {
if (!username || !password || !email) {
res.status(400);
throw new Error("please add all fields");
}
const existingUser = await UserModel.findOne({
$or: [{ username }, { email }],
});
if (existingUser) {
res.status(400);
throw new Error(
`user with ${
existingUser.username === username ? "username" : "email"
} already exists`
);
}
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);
const newUser = new UserModel({
username,
email,
password: hashedPassword,
});
await newUser.save();
res.status(201).json({
success: true,
response: {
username: newUser.username,
email: newUser.email,
id: newUser._id,
accessToken: geneerateToken(newUser),
},
});
} catch (e) {
res.status(500).json({ success: false, response: e.message });
}
})
);

router.post(
"/login",
asyncHandler(async (req, res) => {
const { username, password } = req.body;
try {
const user = await UserModel.findOne({ username });
if (!user) {
return res
.status(401)
.json({ success: false, response: "user not found" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res
.status(401)
.json({ success: false, response: "incorrect password" });
}
res.status(200).json({
success: true,
response: {
username: user.username,
email: user.email,
id: user._id,
accessToken: geneerateToken(user),
},
});
} catch (error) {
res.status(500).json({
success: false,
response: {
message: error.message,
},
});
}
})
);

router.get(
"/logged-in",
authenticateUser,
asyncHandler(async (req, res) => {
res.status(200).json({
success: true,
response: {
message: "user is logged in",
},
});
})
);

export default router;
*/
45 changes: 31 additions & 14 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,44 @@
import express from "express";
import expressListEndpoints from "express-list-endpoints";
import cors from "cors";
import mongoose from "mongoose";
import dotenv from "dotenv";
import userRoutes from "./routes/userRoutes.js";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = Promise;
dotenv.config();

// Defines the port the app will run on. Defaults to 8080, but can be overridden
// when starting the server. Example command to overwrite PORT env variable value:
// PORT=9000 npm start
const port = process.env.PORT || 8080;
const app = express();
const port = process.env.PORT || 9090;

// Add middlewares to enable cors and json body parsing
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(userRoutes);

// Start defining your routes here
// Routes
app.get("/", (req, res) => {
res.send("Hello Technigo!");
const endpoints = expressListEndpoints(app);
res.json(endpoints);
console.log("List of Endpoints:");
console.log(endpoints);
});

// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
// Database connection

mongoose
.connect(process.env.MONGODB_URI, {
//useNewUrlParser: true,
//useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB Atlas");
// Start the server after successfully connecting to the database
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
})
.catch((error) => {
console.error("Error connecting to MongoDB Atlas:", error);
process.exit(1);
});
Loading