Skip to content

Commit 85cb28f

Browse files
committed
login
1 parent 92e8904 commit 85cb28f

File tree

11 files changed

+729
-294
lines changed

11 files changed

+729
-294
lines changed

package-lock.json

Lines changed: 605 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
"type": "module",
77
"scripts": {
88
"start": "nodemon src/index.js",
9-
"update-deps": "npx npm-check-updates -u && npm install"
9+
"update-deps": "npx npm-check-updates -u && npm install",
10+
"lint": "eslint",
11+
"test": "echo \"Error: no test specified\" && exit 1"
1012
},
1113
"keywords": [
1214
"capstone-project",
@@ -16,16 +18,19 @@
1618
"license": "MIT",
1719
"homepage": "https://github.com/Capstone-C2SE02-TI/backend-node-mongodb#readme",
1820
"dependencies": {
21+
"and": "^0.0.3",
1922
"bcrypt": "^5.1.0",
23+
"build": "^0.1.4",
2024
"cookie-parser": "^1.4.6",
2125
"cors": "^2.8.5",
26+
"crypto": "^1.0.1",
2227
"dotenv": "^16.0.3",
2328
"express": "^4.18.2",
2429
"express-validator": "^6.15.0",
2530
"google-auth-library": "^8.7.0",
2631
"jsonwebtoken": "^9.0.0",
2732
"lodash": "^4.17.21",
28-
"mongoose": "^7.0.2",
33+
"mongoose": "^7.0.3",
2934
"mongoose-sequence": "^5.3.1",
3035
"morgan": "^1.10.0",
3136
"nodemailer": "^6.9.1",

src/controllers/Auth.js

Lines changed: 14 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -1,135 +1,32 @@
11
import dotenv from "dotenv";
22
dotenv.config();
33

4-
import {
5-
createNewUser,
6-
checkExistedUsername,
7-
checkExistedEmail,
8-
getPasswordByUsername,
9-
getUserByUsername,
10-
checkExistedWalletAddress
11-
} from "../services/crudDatabase/user.js";
12-
import {
13-
isAuthed,
14-
generateAccessToken
15-
} from "../services/authentication/index.js";
4+
import { createNewUser } from "../services/crudDatabase/user.js";
165
import {
176
cryptWalletAddress,
18-
cryptPassword,
19-
comparePassword
7+
decryptWalletAddress,
8+
encryptWalletAddress
209
} from "../helpers/index.js";
21-
import { validateSignUpBody, validateSignInBody } from "../validators/user.js";
2210

2311
const TI_AUTH_COOKIE = process.env.TI_AUTH_COOKIE;
2412

2513
function AuthController() {
2614
this.signup = async (req, res, next) => {
2715
const { walletAddress } = req.body;
2816

29-
cryptWalletAddress(walletAddress, async (error, hashAddress) => {
30-
const detailCreated = await createNewUser({
31-
walletAddress: hashAddress
32-
});
33-
detailCreated.created
34-
? res.status(200).json({
35-
message: detailCreated.message,
36-
error: null
37-
})
38-
: res.status(400).json({
39-
message: detailCreated.message,
40-
error: detailCreated.error,
41-
});
42-
});
43-
};
44-
45-
this.signin = async (req, res, next) => {
46-
const { username, password } = req.body;
47-
const { status, error } = await validateSignInBody(req, res, next);
48-
49-
if (status === "failed")
50-
return res.status(400).json({
51-
message: error,
52-
error: error,
53-
user: null
54-
});
55-
56-
if (!(await checkExistedUsername(username))) {
57-
return res.status(404).json({
58-
message: "username-notfound",
59-
error: "username-notfound",
60-
user: null
61-
});
62-
} else {
63-
const hashPassword = await getPasswordByUsername(username);
64-
comparePassword(
65-
password,
66-
hashPassword,
67-
async (error, isPasswordMatch) => {
68-
if (isPasswordMatch) {
69-
const user = await getUserByUsername(username);
70-
const cookie = req.cookies[TI_AUTH_COOKIE];
71-
72-
if (!cookie) {
73-
const accessToken = await generateAccessToken({
74-
username
75-
});
76-
77-
res.cookie(TI_AUTH_COOKIE, accessToken, {
78-
// Expire in 1 week
79-
maxAge: 604800000
80-
});
81-
82-
return res.status(200).json({
83-
message: "successfully",
84-
error: null,
85-
user: {
86-
role: "user",
87-
username: user.username,
88-
userId: user.userId,
89-
email: user.email
90-
}
91-
});
92-
} else {
93-
if (await isAuthed(req)) {
94-
return res.status(200).json({
95-
message: "successfully",
96-
error: null,
97-
user: {
98-
role: "user",
99-
username: user.username,
100-
userId: user.userId,
101-
email: user.email
102-
}
103-
});
104-
} else {
105-
return res.status(401).json({
106-
message: "failed-unauthorized",
107-
error: "failed-unauthorized",
108-
user: null
109-
});
110-
}
111-
}
112-
} else {
113-
return res.status(400).json({
114-
message: "incorrect-password",
115-
error: "incorrect-password",
116-
user: null
117-
});
118-
}
119-
}
120-
);
121-
}
122-
};
17+
const hashWallet = encryptWalletAddress(walletAddress);
12318

124-
this.signout = (req, res, next) => {
125-
try {
126-
req.user = null;
127-
req.session = null;
19+
const detailCreated = await createNewUser(hashWallet.encryptedData);
12820

129-
return res.status(200).json({ message: "successfully", error: null });
130-
} catch (error) {
131-
return res.status(400).json({ message: "failed", error: error });
132-
}
21+
detailCreated.created
22+
? res.status(200).json({
23+
message: detailCreated.message,
24+
error: null
25+
})
26+
: res.status(400).json({
27+
message: detailCreated.message,
28+
error: detailCreated.error
29+
});
13330
};
13431
}
13532

src/controllers/User.js

Lines changed: 9 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
import _ from "lodash";
22
import {
3-
getUserByEmail,
4-
updateUserPassword,
5-
getPasswordByEmail,
63
followWalletOfShark,
74
unfollowWalletOfShark,
85
getListOfSharkFollowed,
@@ -16,28 +13,25 @@ import {
1613
} from "../services/crudDatabase/admin.js";
1714
import {
1815
validateUpdateProfileBody,
19-
validateChangePasswordBody
2016
} from "../validators/user.js";
21-
import { cryptPassword, comparePassword } from "../helpers/index.js";
2217

2318
function UserController() {
2419
this.getUserProfile = async (req, res, next) => {
25-
let userId = req.query.userId;
20+
let walletAddress = req.query.walletAddress;
2621

27-
if (!userId) userId = null;
22+
if (!walletAddress) walletAddress = null;
2823
else {
29-
const userIdCheck = _.toString(userId);
30-
if (_.isNaN(userIdCheck)) userId = undefined;
31-
else userId = Number(userIdCheck);
24+
const walletAddressCheck = _.toString(walletAddress);
25+
if (_.isNaN(walletAddressCheck)) walletAddress = undefined;
3226
}
3327

34-
await getUserProfile(userId)
28+
await getUserProfile(walletAddress)
3529
.then((data) =>
3630
Object.entries(data).length === 0
3731
? res.status(400).json({
38-
message: "failed-userid-invalid",
39-
error: "userid-invalid",
40-
data: {}
32+
message: "failed-wallet-address-invalid",
33+
error: "wallet-address-invalid",
34+
data: data
4135
})
4236
: res.status(200).json({
4337
message: "successfully",
@@ -91,48 +85,8 @@ function UserController() {
9185
}
9286
};
9387

94-
this.changePassword = async (req, res, next) => {
95-
const { status, error } = await validateChangePasswordBody(req, res, next);
96-
97-
if (status === "failed")
98-
return res.status(400).json({ message: error, error: error });
99-
else {
100-
const { email, oldPassword, newPassword } = req.body;
101-
const user = await getUserByEmail(email);
102-
103-
if (user) {
104-
// Check correct old password
105-
const password = await getPasswordByEmail(email);
106-
comparePassword(oldPassword, password, (error, isPasswordMatch) => {
107-
if (isPasswordMatch) {
108-
cryptPassword(newPassword, async (error, hashPassword) =>
109-
(await updateUserPassword(user.userId, hashPassword)) === true
110-
? res.status(200).json({
111-
message: "successfully",
112-
error: null
113-
})
114-
: res.status(400).json({
115-
message: "failed",
116-
error: error
117-
})
118-
);
119-
} else {
120-
return res.status(400).json({
121-
message: "incorrect-oldpassword",
122-
error: "incorrect-oldpassword"
123-
});
124-
}
125-
});
126-
} else {
127-
return res
128-
.status(400)
129-
.json({ message: "user-notfound", error: "user-notfound" });
130-
}
131-
}
132-
};
133-
13488
this.upgradePremiumAccount = async (req, res, next) => {
135-
let userId = req.body.userId;
89+
let userId = req.body.userId;
13690

13791
if (!userId) userId = null;
13892
else {

src/helpers/index.js

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,35 @@
11
import _ from "lodash";
22
import bcrypt from "bcrypt";
3+
import crypto from "crypto";
4+
5+
const algorithm = "aes-256-cbc";
6+
7+
const key = crypto.randomBytes(32);
8+
9+
const iv = crypto.randomBytes(16);
310

411
export const randomConfirmationCode = () => {
512
const code = Math.floor(100000 + Math.random() * 900000);
613
return code.toString();
714
};
815

9-
export const cryptWalletAddress = (walletAddress, callback) => {
10-
bcrypt.genSalt(10, (error, salt) => {
11-
if (error) return callback(error);
16+
export const encryptWalletAddress = (walletAddress) => {
17+
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
18+
let encrypted = cipher.update(walletAddress);
19+
encrypted = Buffer.concat([encrypted, cipher.final()]);
20+
return { iv: iv.toString("hex"), encryptedData: encrypted.toString("hex") };
21+
};
1222

13-
bcrypt.hash(walletAddress, salt, (error, hashAddress) => {
14-
console.log(hashAddress);
15-
return callback(error, hashAddress);
16-
});
17-
});
23+
export const decryptWalletAddress = (encryptedData) => {
24+
const ivDecrypt = Buffer.from(iv.toString("hex"), "hex");
25+
const encryptedText = Buffer.from(encryptedData, "hex");
26+
27+
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), ivDecrypt);
28+
29+
let decrypted = decipher.update(encryptedText);
30+
decrypted = Buffer.concat([decrypted, decipher.final()]);
31+
32+
return decrypted;
1833
};
1934

2035
export const compareWalletAddress = (plainAddress, hashAddress, callback) => {
@@ -23,6 +38,16 @@ export const compareWalletAddress = (plainAddress, hashAddress, callback) => {
2338
});
2439
};
2540

41+
export const cryptWalletAddress = (password, callback) => {
42+
bcrypt.genSalt(10, (error, salt) => {
43+
if (error) return callback(error);
44+
45+
bcrypt.hash(password, salt, (error, hashPassword) => {
46+
return callback(error, hashPassword);
47+
});
48+
});
49+
};
50+
2651
export const cryptPassword = (password, callback) => {
2752
bcrypt.genSalt(10, (error, salt) => {
2853
if (error) return callback(error);

src/models/User.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import mongoose from "mongoose";
2-
import Inc from "mongoose-sequence";
3-
const AutoIncrement = Inc(mongoose);
42

53
const UserSchema = new mongoose.Schema(
64
{
@@ -42,5 +40,6 @@ const UserSchema = new mongoose.Schema(
4240
{ timestamps: true, versionKey: false }
4341
);
4442

43+
4544
const UserModel = mongoose.model("User", UserSchema);
4645
export default UserModel;

src/routes/auth.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,5 @@ const router = express.Router();
33
import AuthController from "../controllers/Auth.js";
44

55
router.post("/signup", AuthController.signup);
6-
router.post("/signin", AuthController.signin);
7-
router.post("/signout", AuthController.signout);
86

97
export default router;

src/routes/user.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { isAuth } from "../middlewares/authentication/index.js";
55

66
router.post("/profile/update", isAuth, UserController.updateUserProfile);
77
router.get("/profile", isAuth, UserController.getUserProfile);
8-
router.post("/change-password", isAuth, UserController.changePassword);
98
router.post(
109
"/upgrade-premium-account",
1110
isAuth,

0 commit comments

Comments
 (0)