Skip to content

Commit f29b2c4

Browse files
author
sourabh
committed
[work]-on uploading images & signup user
1 parent fd5f1a3 commit f29b2c4

File tree

9 files changed

+207
-8
lines changed

9 files changed

+207
-8
lines changed

.env

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
11
PORT = 4000
2+
DB_URL = mongodb://localhost:27017/tshrtshopapp
3+
24
JWT_SECRET = thisismyjwtpersonalsecret
3-
JWT_EXPIRY = 7d
5+
JWT_EXPIRY = 3d
6+
COOKIE_TIME = 3d
7+
8+
CLOUDINARY_NAME = djqf9vhkq
9+
CLOUDINARY_API_KEY = 333799583579346
10+
CLOUDINARY_API_SECRET = NQvSauVhU6fjJ5Wrd_GDqMHTVu4
11+

app.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,23 @@ app.use(morgan("tiny"));
1818

1919
//COOKIES AND FILE-UPLOAD MIDDLEWARE
2020
app.use(cookieParser());
21-
app.use(fileUpload());
21+
app.use(
22+
fileUpload({
23+
useTempFiles: true,
24+
tempFileDir: "/tmp/",
25+
})
26+
);
2227

2328
//REGULAR MIDDLEWARE
2429
app.use(express.json());
25-
app.use(express.urlencoded({extended:true}))
30+
app.use(express.urlencoded({ extended: true }));
2631

2732
// BRINGS ROUTES
2833
const home = require("./routes/home");
34+
const user = require("./routes/user");
2935

3036
// USING MIDDLEWARE
3137
app.use("/api/v1", home);
38+
app.use("/api/v1", user);
3239

3340
module.exports = app;

config/db.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const mongoose = require("mongoose");
2+
const { DB_URL } = process.env;
3+
4+
const connectWithDb = () => {
5+
mongoose
6+
.connect(DB_URL, {
7+
useNewUrlParser: true,
8+
useUnifiedTopology: true,
9+
})
10+
.then(console.log("DB CONNECTED SUCCESSFULLY"))
11+
.catch((error) => {
12+
console.log(`DB CONNECTION FAILED`);
13+
console.log(error);
14+
process.exit(1);
15+
});
16+
};
17+
18+
module.exports = connectWithDb;

controllers/user.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const User = require("../models/user");
2+
const BigPromise = require("../middlewares/bigPromise");
3+
const CustomError = require("../utils/customError");
4+
const cookieToken = require("../utils/cookieToken");
5+
const fileUpload = require("express-fileupload");
6+
const cloudinary = require("cloudinary");
7+
8+
exports.signup = BigPromise(async (req, res, next) => {
9+
// UPLOAD IMAGE
10+
let result;
11+
if (req.files) {
12+
let file = req.files.photo;
13+
result = await cloudinary.v2.uploader.upload(file, {
14+
folder: "users",
15+
width: 150,
16+
crop: "scale",
17+
});
18+
}
19+
20+
// INVITE FIELD
21+
const { name, email, password } = req.body;
22+
23+
// EXITS,OR NOT
24+
if (!email || !name || !password) {
25+
return next(new CustomError("Name,email,password are required!", 400));
26+
}
27+
28+
// NEW ENTRY ON DB
29+
const user = await User.create({
30+
name,
31+
email,
32+
password,
33+
photo: {
34+
id: result.public_id,
35+
secure_url: result.secure_url,
36+
},
37+
});
38+
39+
cookieToken(user, res);
40+
});

index.js

+17-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
require("dotenv").config();
2-
const app = require("./app")
2+
const app = require("./app");
3+
const connectWithDb = require("./config/db");
4+
const cloudinary = require("cloudinary");
5+
6+
// CONNECT TO DATABASE
7+
connectWithDb();
8+
9+
// CLOUDINARY CONFIG
10+
cloudinary.config({
11+
clound_name: process.env.CLOUDINARY_NAME,
12+
api_key: process.env.CLOUDINARY_API_KEY,
13+
api_key: process.env.CLOUDINARY_API_SECRET,
14+
});
315

416
app.listen(process.env.PORT, () => {
5-
console.log(`Example app listening on port http://localhost:${process.env.PORT}/api/v1`)
6-
})
17+
console.log(
18+
`Example app listening on port http://localhost:${process.env.PORT}/api/v1`
19+
);
20+
});

models/user.js

+17-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const mongoose = require("mongoose");
22
const validator = require("validator");
33
const bcrypt = require("bcryptjs");
44
const jwt = require("jsonwebtoken");
5+
const crypto = require("crypto");
56

67
const userSchema = new mongoose.Schema({
78
name: {
@@ -18,7 +19,7 @@ const userSchema = new mongoose.Schema({
1819
password: {
1920
type: String,
2021
required: [true, "Please provide an password"],
21-
minlength: [6, "password should be atleast 8 char"],
22+
minlength: [6, "password should be atleast 6 char"],
2223
select: false,
2324
},
2425
role: {
@@ -58,11 +59,25 @@ userSchema.methods.isValidatedPassword = async function (userSendPassword) {
5859

5960
//CREATE AND RETURN JWT TOKEN
6061
userSchema.methods.getJwtToken = function () {
61-
jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
62+
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
6263
expiresIn: process.env.JWT_EXPIRY,
6364
});
6465
};
6566

67+
// GENERATE FORGOT PASSWORD TOKEN (STRING)
68+
userSchema.methods.getForgotPasswordToken = function () {
69+
// GENERATE A LONG AND RANDOM STRING
70+
const forgotToken = crypto.randomBytes(20).toString("hex");
71+
// GETTING A HASH - MAKE SURE TO GET HASH ON backend
72+
this.forgotPasswordToken = crypto
73+
.createHash("sha256")
74+
.update(forgotToken)
75+
.digest("hex");
76+
// TIME OF TOKEN
77+
this.forgotPasswordExpiry = Date.now() + 20 * 60 * 1000;
78+
return forgotToken;
79+
};
80+
6681

6782
module.exports = mongoose.model("User", userSchema);
6883

routes/user.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
const express = require("express");
2+
const router = express.Router();
3+
const {signup} = require("../controllers/user");
4+
5+
router.route('/signup').post(signup);
6+
7+
module.exports = router;

map_project.js tracking_project/map_project.js

+71
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
/*
2+
@NOTE: Create first "CustomError"(🗃️utils), "bigPromise"(🗃️middlewares) for Error Handling BEFOUR Start PROJECT;
3+
24
@ABOUT_ROUTES:
35
Ref: ✈️🔗https://expressjs.com/en/5x/api.html#router
46
@@ -73,6 +75,7 @@ IN this we'r discussing about methods for VALIDATING the password that were pass
7375
-It just return true & false value weather you login or not !!
7476
7577
-----------------NEW--------------------
78+
7679
@SECTION: USER MODEL & SIGNUP
7780
@TITLE: CREATING JWT TOKEN
7881
@LOCATION: 🗃️models/user.js
@@ -90,4 +93,72 @@ IN this we'r discussing about methods for VALIDATING the password that were pass
9093
-🎯Then provide secrete Come from .env
9194
-🎯Then pass expiry time
9295
96+
97+
🥊🥊-----------------------@NEW@----------------------------🥊🥊
98+
99+
100+
@SECTION: USER MODEL & SIGNUP
101+
@TITLE: FORGOT PASSWORT & CRYPTO HASHING
102+
@ABOUT:user schema
103+
@LOCATION: 🗃️models/user.js
104+
@OVERVIEW:
105+
Ref: 🔗✈️https://www.npmjs.com/package/nanoid
106+
Ref: 🔗✈️https://www.npmjs.com/package/randomstring
107+
Ref: 🔗✈️https://www.npmjs.com/package/uuid
108+
109+
!Ref: 🔗✈️https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
110+
!Ref: 🔗✈️https://en.wikipedia.org/wiki/Cryptographic_hash_function
111+
112+
-🎯ForgotPasswordToken It just Normal String Nothing more than that don't consider as a jsonwebtoken
113+
-🎯Need to Stored this String Into DATABASE itself & send to frontend somebuddy else
114+
-🎯use crypto package take Refference of 2nd last link
115+
-🎯we can perform simply No need to woryy on 'createHash,digest,update' & all stuff just go & simply stored like this.forgotPasswordExpiry = forgotToken it's OK !! No Problem
116+
-🎯But,OPTIONAlY Moving one step ahead BEFOUR one Read about last wikipedia Link
117+
-🎯About ref link
118+
it Generate STRING which "fix in size" + find message only via "Bruit Force" which take long years & info not that much valuable + So in order to Resolve "Cryptographic_hash_function" Need of it;
119+
120+
121+
-@PROCESS
122+
^ Generate a long and random String
123+
[nanoid,randomstring,uuid]
124+
^ But😗, we'r using CRYPTO not any one of them it just for knowledge
125+
^ we'don't have to install it come with node itself;
126+
^ take Refference of last two below link study perpose & with the help of that createHash update & digest
127+
128+
129+
----------------------------SECTION
130+
131+
@TITLE: USER ROUTES AND POSTMAN
132+
@LOCATION: 🗃️MODEL/user/
133+
134+
🔺-"/forgotPassword "- request an email How to reset Password +
135+
🔺-"/password/reset/:token" - The whole idea behind this Grabbed this UNIC string(via :token) just created at earlier Via CRYPTO
136+
& want to Grabbed this "URL" itself if "STRING" Matches with my DATABASE STRING So everything reset in backend itself; this is how it work;
137+
Note: ALSO Allow PASSWORD Body itself
138+
🔺- Need All user info "/"
139+
🔺- "/password/update" && "/user/update"
140+
141+
-----------------------------SECTION
142+
143+
@LOCATION: 🗃️CONTROLLER/user.js
144+
@TITLE:SIGNUP A USER & COOKIE
145+
146+
/*SEND Cookie Value
147+
-🎯Optionally You can send msg Hey, user is created Go & Login
148+
-🎯But,here once Registerd then want send HIM cookie token & GRABBED It That's convection
149+
-🎯Now able to access Methods Now that we done on Model/user "getJwtToken" it'll give me token
150+
-🎯want set some options & throw it on "Cookie"
151+
-🎯Why Json for mobile perspective that's why you see easily token on web But.
152+
153+
Cookie token we need use frequently So create 🗃️utils/cookieToken/
154+
155+
156+
157+
158+
159+
160+
161+
162+
163+
93164
*/

utils/cookieToken.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const cookieToken = (user, res) => {
2+
// GRABBED TOKEN
3+
const token = user.getJwtToken();
4+
5+
// PASS TOKEN INTO OPTIONS THEN COOKIE
6+
const options = {
7+
expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
8+
httpOnly: true,
9+
};
10+
11+
user.password = undefined;
12+
res.status(200).cookie("token", token, options).json({
13+
success: true,
14+
token,
15+
user,
16+
});
17+
};
18+
19+
module.exports = cookieToken;

0 commit comments

Comments
 (0)