Skip to content

Commit debdf38

Browse files
committed
add prettier to user-service
1 parent 16e15f7 commit debdf38

File tree

12 files changed

+1042
-772
lines changed

12 files changed

+1042
-772
lines changed

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
},
99
"workspaces": [
1010
"question-service",
11-
"peerprep-fe"
11+
"peerprep-fe",
12+
"user-service"
1213
],
1314
"dependencies": {
1415
"nuqs": "^1.19.3"

user-service/.prettierignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules
2+
dist
3+
build

user-service/.prettierrc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"semi": true,
3+
"singleQuote": true,
4+
"trailingComma": "all",
5+
"printWidth": 80
6+
}

user-service/controller/auth-controller.js

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,49 @@
1-
import bcrypt from "bcrypt";
2-
import jwt from "jsonwebtoken";
3-
import { findUserByEmail as _findUserByEmail } from "../model/repository.js";
4-
import { formatUserResponse } from "./user-controller.js";
1+
import bcrypt from 'bcrypt';
2+
import jwt from 'jsonwebtoken';
3+
import { findUserByEmail as _findUserByEmail } from '../model/repository.js';
4+
import { formatUserResponse } from './user-controller.js';
55

66
export async function handleLogin(req, res) {
77
const { email, password } = req.body;
88
if (email && password) {
99
try {
1010
const user = await _findUserByEmail(email);
1111
if (!user) {
12-
return res.status(401).json({ message: "Wrong email and/or password" });
12+
return res.status(401).json({ message: 'Wrong email and/or password' });
1313
}
1414

1515
const match = await bcrypt.compare(password, user.password);
1616
if (!match) {
17-
return res.status(401).json({ message: "Wrong email and/or password" });
17+
return res.status(401).json({ message: 'Wrong email and/or password' });
1818
}
1919

20-
const accessToken = jwt.sign({
21-
id: user.id,
22-
}, process.env.JWT_SECRET, {
23-
expiresIn: "1d",
20+
const accessToken = jwt.sign(
21+
{
22+
id: user.id,
23+
},
24+
process.env.JWT_SECRET,
25+
{
26+
expiresIn: '1d',
27+
},
28+
);
29+
return res.status(200).json({
30+
message: 'User logged in',
31+
data: { accessToken, ...formatUserResponse(user) },
2432
});
25-
return res.status(200).json({ message: "User logged in", data: { accessToken, ...formatUserResponse(user) } });
2633
} catch (err) {
2734
return res.status(500).json({ message: err.message });
2835
}
2936
} else {
30-
return res.status(400).json({ message: "Missing email and/or password" });
37+
return res.status(400).json({ message: 'Missing email and/or password' });
3138
}
3239
}
3340

3441
export async function handleVerifyToken(req, res) {
3542
try {
3643
const verifiedUser = req.user;
37-
return res.status(200).json({ message: "Token verified", data: verifiedUser });
44+
return res
45+
.status(200)
46+
.json({ message: 'Token verified', data: verifiedUser });
3847
} catch (err) {
3948
return res.status(500).json({ message: err.message });
4049
}

user-service/controller/user-controller.js

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import bcrypt from "bcrypt";
2-
import { isValidObjectId } from "mongoose";
1+
import bcrypt from 'bcrypt';
2+
import { isValidObjectId } from 'mongoose';
33
import {
44
createUser as _createUser,
55
deleteUserById as _deleteUserById,
@@ -10,15 +10,17 @@ import {
1010
findUserByUsernameOrEmail as _findUserByUsernameOrEmail,
1111
updateUserById as _updateUserById,
1212
updateUserPrivilegeById as _updateUserPrivilegeById,
13-
} from "../model/repository.js";
13+
} from '../model/repository.js';
1414

1515
export async function createUser(req, res) {
1616
try {
1717
const { username, email, password } = req.body;
1818
if (username && email && password) {
1919
const existingUser = await _findUserByUsernameOrEmail(username, email);
2020
if (existingUser) {
21-
return res.status(409).json({ message: "username or email already exists" });
21+
return res
22+
.status(409)
23+
.json({ message: 'username or email already exists' });
2224
}
2325

2426
const salt = bcrypt.genSaltSync(10);
@@ -29,11 +31,15 @@ export async function createUser(req, res) {
2931
data: formatUserResponse(createdUser),
3032
});
3133
} else {
32-
return res.status(400).json({ message: "username and/or email and/or password are missing" });
34+
return res
35+
.status(400)
36+
.json({ message: 'username and/or email and/or password are missing' });
3337
}
3438
} catch (err) {
3539
console.error(err);
36-
return res.status(500).json({ message: "Unknown error when creating new user!" });
40+
return res
41+
.status(500)
42+
.json({ message: 'Unknown error when creating new user!' });
3743
}
3844
}
3945

@@ -48,22 +54,30 @@ export async function getUser(req, res) {
4854
if (!user) {
4955
return res.status(404).json({ message: `User ${userId} not found` });
5056
} else {
51-
return res.status(200).json({ message: `Found user`, data: formatUserResponse(user) });
57+
return res
58+
.status(200)
59+
.json({ message: `Found user`, data: formatUserResponse(user) });
5260
}
5361
} catch (err) {
5462
console.error(err);
55-
return res.status(500).json({ message: "Unknown error when getting user!" });
63+
return res
64+
.status(500)
65+
.json({ message: 'Unknown error when getting user!' });
5666
}
5767
}
5868

5969
export async function getAllUsers(req, res) {
6070
try {
6171
const users = await _findAllUsers();
6272

63-
return res.status(200).json({ message: `Found users`, data: users.map(formatUserResponse) });
73+
return res
74+
.status(200)
75+
.json({ message: `Found users`, data: users.map(formatUserResponse) });
6476
} catch (err) {
6577
console.error(err);
66-
return res.status(500).json({ message: "Unknown error when getting all users!" });
78+
return res
79+
.status(500)
80+
.json({ message: 'Unknown error when getting all users!' });
6781
}
6882
}
6983

@@ -82,11 +96,11 @@ export async function updateUser(req, res) {
8296
if (username || email) {
8397
let existingUser = await _findUserByUsername(username);
8498
if (existingUser && existingUser.id !== userId) {
85-
return res.status(409).json({ message: "username already exists" });
99+
return res.status(409).json({ message: 'username already exists' });
86100
}
87101
existingUser = await _findUserByEmail(email);
88102
if (existingUser && existingUser.id !== userId) {
89-
return res.status(409).json({ message: "email already exists" });
103+
return res.status(409).json({ message: 'email already exists' });
90104
}
91105
}
92106

@@ -95,25 +109,36 @@ export async function updateUser(req, res) {
95109
const salt = bcrypt.genSaltSync(10);
96110
hashedPassword = bcrypt.hashSync(password, salt);
97111
}
98-
const updatedUser = await _updateUserById(userId, username, email, hashedPassword);
112+
const updatedUser = await _updateUserById(
113+
userId,
114+
username,
115+
email,
116+
hashedPassword,
117+
);
99118
return res.status(200).json({
100119
message: `Updated data for user ${userId}`,
101120
data: formatUserResponse(updatedUser),
102121
});
103122
} else {
104-
return res.status(400).json({ message: "No field to update: username and email and password are all missing!" });
123+
return res.status(400).json({
124+
message:
125+
'No field to update: username and email and password are all missing!',
126+
});
105127
}
106128
} catch (err) {
107129
console.error(err);
108-
return res.status(500).json({ message: "Unknown error when updating user!" });
130+
return res
131+
.status(500)
132+
.json({ message: 'Unknown error when updating user!' });
109133
}
110134
}
111135

112136
export async function updateUserPrivilege(req, res) {
113137
try {
114138
const { isAdmin } = req.body;
115139

116-
if (isAdmin !== undefined) { // isAdmin can have boolean value true or false
140+
if (isAdmin !== undefined) {
141+
// isAdmin can have boolean value true or false
117142
const userId = req.params.id;
118143
if (!isValidObjectId(userId)) {
119144
return res.status(404).json({ message: `User ${userId} not found` });
@@ -123,17 +148,22 @@ export async function updateUserPrivilege(req, res) {
123148
return res.status(404).json({ message: `User ${userId} not found` });
124149
}
125150

126-
const updatedUser = await _updateUserPrivilegeById(userId, isAdmin === true);
151+
const updatedUser = await _updateUserPrivilegeById(
152+
userId,
153+
isAdmin === true,
154+
);
127155
return res.status(200).json({
128156
message: `Updated privilege for user ${userId}`,
129157
data: formatUserResponse(updatedUser),
130158
});
131159
} else {
132-
return res.status(400).json({ message: "isAdmin is missing!" });
160+
return res.status(400).json({ message: 'isAdmin is missing!' });
133161
}
134162
} catch (err) {
135163
console.error(err);
136-
return res.status(500).json({ message: "Unknown error when updating user privilege!" });
164+
return res
165+
.status(500)
166+
.json({ message: 'Unknown error when updating user privilege!' });
137167
}
138168
}
139169

@@ -149,10 +179,14 @@ export async function deleteUser(req, res) {
149179
}
150180

151181
await _deleteUserById(userId);
152-
return res.status(200).json({ message: `Deleted user ${userId} successfully` });
182+
return res
183+
.status(200)
184+
.json({ message: `Deleted user ${userId} successfully` });
153185
} catch (err) {
154186
console.error(err);
155-
return res.status(500).json({ message: "Unknown error when deleting user!" });
187+
return res
188+
.status(500)
189+
.json({ message: 'Unknown error when deleting user!' });
156190
}
157191
}
158192

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,31 @@
1-
import jwt from "jsonwebtoken";
2-
import { findUserById as _findUserById } from "../model/repository.js";
1+
import jwt from 'jsonwebtoken';
2+
import { findUserById as _findUserById } from '../model/repository.js';
33

44
export function verifyAccessToken(req, res, next) {
5-
const authHeader = req.headers["authorization"];
5+
const authHeader = req.headers['authorization'];
66
if (!authHeader) {
7-
return res.status(401).json({ message: "Authentication failed" });
7+
return res.status(401).json({ message: 'Authentication failed' });
88
}
99

1010
// request auth header: `Authorization: Bearer + <access_token>`
11-
const token = authHeader.split(" ")[1];
11+
const token = authHeader.split(' ')[1];
1212
jwt.verify(token, process.env.JWT_SECRET, async (err, user) => {
1313
if (err) {
14-
return res.status(401).json({ message: "Authentication failed" });
14+
return res.status(401).json({ message: 'Authentication failed' });
1515
}
1616

1717
// load latest user info from DB
1818
const dbUser = await _findUserById(user.id);
1919
if (!dbUser) {
20-
return res.status(401).json({ message: "Authentication failed" });
20+
return res.status(401).json({ message: 'Authentication failed' });
2121
}
2222

23-
req.user = { id: dbUser.id, username: dbUser.username, email: dbUser.email, isAdmin: dbUser.isAdmin };
23+
req.user = {
24+
id: dbUser.id,
25+
username: dbUser.username,
26+
email: dbUser.email,
27+
isAdmin: dbUser.isAdmin,
28+
};
2429
next();
2530
});
2631
}
@@ -29,7 +34,9 @@ export function verifyIsAdmin(req, res, next) {
2934
if (req.user.isAdmin) {
3035
next();
3136
} else {
32-
return res.status(403).json({ message: "Not authorized to access this resource" });
37+
return res
38+
.status(403)
39+
.json({ message: 'Not authorized to access this resource' });
3340
}
3441
}
3542

@@ -44,5 +51,7 @@ export function verifyIsOwnerOrAdmin(req, res, next) {
4451
return next();
4552
}
4653

47-
return res.status(403).json({ message: "Not authorized to access this resource" });
54+
return res
55+
.status(403)
56+
.json({ message: 'Not authorized to access this resource' });
4857
}

user-service/model/repository.js

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import UserModel from "./user-model.js";
2-
import "dotenv/config";
3-
import { connect } from "mongoose";
1+
import UserModel from './user-model.js';
2+
import 'dotenv/config';
3+
import { connect } from 'mongoose';
44

55
export async function connectToDB() {
66
let mongoDBUri =
7-
process.env.ENV === "PROD"
7+
process.env.ENV === 'PROD'
88
? process.env.DB_CLOUD_URI
99
: process.env.DB_LOCAL_URI;
1010

@@ -29,10 +29,7 @@ export async function findUserByUsername(username) {
2929

3030
export async function findUserByUsernameOrEmail(username, email) {
3131
return UserModel.findOne({
32-
$or: [
33-
{ username },
34-
{ email },
35-
],
32+
$or: [{ username }, { email }],
3633
});
3734
}
3835

@@ -50,7 +47,7 @@ export async function updateUserById(userId, username, email, password) {
5047
password,
5148
},
5249
},
53-
{ new: true }, // return the updated user
50+
{ new: true }, // return the updated user
5451
);
5552
}
5653

@@ -62,7 +59,7 @@ export async function updateUserPrivilegeById(userId, isAdmin) {
6259
isAdmin,
6360
},
6461
},
65-
{ new: true }, // return the updated user
62+
{ new: true }, // return the updated user
6663
);
6764
}
6865

user-service/model/user-model.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import mongoose from "mongoose";
1+
import mongoose from 'mongoose';
22

33
const Schema = mongoose.Schema;
44

@@ -28,4 +28,4 @@ const UserModelSchema = new Schema({
2828
},
2929
});
3030

31-
export default mongoose.model("UserModel", UserModelSchema);
31+
export default mongoose.model('UserModel', UserModelSchema);

0 commit comments

Comments
 (0)