unknown преди 2 години
родител
ревизия
2e619c6e22

+ 39 - 41
controllers/user.js

@@ -9,40 +9,6 @@ const client = require('../helpers/twilio');
 const phoneToken = require('generate-sms-verification-code');
 const SECRET_KEY = process.env.JWT_SECRET;
 
-const saveAvatarForStatic = async (req, res, next) => {
-	try {
-		const userId = req.user.id;
-		const DIR_IMAGES = process.env.DIR_IMAGES;
-		const pathToFile = req.file.path;
-		const newNameAvatar = req.file.originalname;
-
-		const img = await Jimp.read(pathToFile);
-		await img
-			.autocrop()
-			.cover(
-				250,
-				250,
-				Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE
-			)
-			.writeAsync(pathToFile);
-
-		await createFolderIsExist(path.join(DIR_IMAGES, userId));
-		await fs.rename(pathToFile, path.join(DIR_IMAGES, userId, newNameAvatar));
-		const newUrlAvatar = path.normalize(path.join(userId, newNameAvatar));
-		const newUrl = `http://localhost:3000/${userId}/${newNameAvatar}`;
-		await UserModel.updateAvatar(userId, newUrlAvatar);
-		return res.status(200).json({
-			status: 'success',
-			code: 200,
-			data: {
-				avatarUrl: newUrl,
-			},
-		});
-	} catch (e) {
-		next(e);
-	}
-};
-
 const createNewUser = async (req, res, next) => {
 	try {
 		const code = phoneToken(4, { type: 'number' });
@@ -83,8 +49,8 @@ const logIn = async (req, res, next) => {
 		const id = user._id;
 		const payload = { id };
 		const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '24h' });
-		let registration = false;
-		if (!user.name || !user.lastName || !user.avatarUrl) registration = true;
+		let registered = true;
+		if (!user.name || !user.lastName || !user.avatarUrl) registered = false;
 		await UserModel.updateToken(id, token);
 		await UserModel.updateCode(id, '');
 		return res.status(200).json({
@@ -92,7 +58,7 @@ const logIn = async (req, res, next) => {
 			code: 200,
 			data: {
 				token,
-				registration,
+				registered,
 			},
 		});
 	} catch (e) {
@@ -143,11 +109,43 @@ const getCurrent = async (req, res, next) => {
 
 const updateCredentials = async (req, res, next) => {
 	try {
-		const id = req.user.id;
-		const user = await UserModel.updateCredentials(id, req.body);
+		const { id, token } = req.user;
+		await UserModel.updateCredentials(id, req.body);
 		return res.status(200).json({
 			data: {
-				...user,
+				token,
+			},
+		});
+	} catch (e) {
+		next(e);
+	}
+};
+
+const updateAvatar = async (req, res, next) => {
+	try {
+		const userId = req.user.id;
+		const token = req.user.token;
+		const DIR_IMAGES = process.env.DIR_IMAGES;
+		const pathToFile = req.file.path;
+		const newNameAvatar = req.file.originalname;
+		const img = await Jimp.read(pathToFile);
+		await img
+			.autocrop()
+			.cover(
+				250,
+				250,
+				Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE
+			)
+			.writeAsync(pathToFile);
+		await createFolderIsExist(path.join(DIR_IMAGES, userId));
+		await fs.rename(pathToFile, path.join(DIR_IMAGES, userId, newNameAvatar));
+		const avatarUrl = path.normalize(path.join(userId, newNameAvatar));
+		await UserModel.updateAvatar(userId, avatarUrl);
+		return res.status(200).json({
+			status: 'success',
+			code: 200,
+			data: {
+				token,
 			},
 		});
 	} catch (e) {
@@ -156,10 +154,10 @@ const updateCredentials = async (req, res, next) => {
 };
 
 module.exports = {
-	saveAvatarForStatic,
 	createNewUser,
 	logIn,
 	logOut,
 	getCurrent,
 	updateCredentials,
+	updateAvatar,
 };

+ 11 - 11
helpers/apiLimiter.js

@@ -1,16 +1,16 @@
-const rateLimit = require("express-rate-limit");
+const rateLimit = require('express-rate-limit');
 
 const apiLimiter = rateLimit({
-  windowMs: 15 * 60 * 1000,
-  max: 200,
-  handler: (req, res, next) => {
-    return res.status(400).json({
-      status: "error",
-      code: 400,
-      data: "Bad request",
-      message: "Too many requests, please try again later.",
-    });
-  },
+	windowMs: 15 * 60 * 1000,
+	max: 2000,
+	handler: (req, res, next) => {
+		return res.status(400).json({
+			status: 'error',
+			code: 400,
+			data: 'Bad request',
+			message: 'Too many requests, please try again later.',
+		});
+	},
 });
 
 module.exports = apiLimiter;

images/6202872a6f9ce92fa4bd0e1e/6-1.png → images/62038d25b235de73d8876e22/6-1.png


BIN
images/62038e77b235de73d8876e23/6-1.png


BIN
images/620390a010645820b462512c/6-3.png


images/6202872a6f9ce92fa4bd0e1e/6-2.png → images/6203933cb578256c8ca8d7dc/6-2.png


BIN
images/620394bfb578256c8ca8d7de/6-1.png


+ 1 - 4
model/schemas/user.js

@@ -1,6 +1,5 @@
 const mongoose = require('mongoose');
 const { Schema, model } = mongoose;
-const gravatar = require('gravatar');
 mongoose.Types.ObjectId.isValid();
 
 const userSchema = new Schema(
@@ -28,9 +27,7 @@ const userSchema = new Schema(
 		},
 		avatarUrl: {
 			type: String,
-			default: function () {
-				return gravatar.url(this.email, { s: '250' }, true);
-			},
+			default: null,
 		},
 		token: {
 			type: String,

+ 3 - 3
routes/user.js

@@ -16,8 +16,8 @@ router
 	)
 	.get('/users/current', guard, controllers.getCurrent)
 	.patch(
-		'/users/avatar',
-		[guard, upload.single('avatar'), validation.validateUploadAvatar],
-		controllers.saveAvatarForStatic
+		'/users/avatars',
+		[guard, upload.single('avatar'), validation.validateUploadFile],
+		controllers.updateAvatar
 	);
 module.exports = router;

+ 3 - 3
validation/user.js

@@ -11,7 +11,7 @@ const schemaUpdateUser = Joi.object({
 	name: Joi.string().min(3).max(30).optional().trim().optional(),
 	lastName: Joi.string().min(3).max(30).optional().trim().optional(),
 	number: Joi.string().min(8).max(14).optional(),
-});
+}).min(1);
 
 const schemaLogIn = Joi.object({
 	number: Joi.string().min(8).max(14).required(),
@@ -28,13 +28,13 @@ module.exports.logIn = (req, _res, next) => {
 	return validate(schemaLogIn, req.body, next);
 };
 
-module.exports.validateUploadAvatar = (req, res, next) => {
+module.exports.validateUploadFile = (req, res, next) => {
 	if (!req.file)
 		return res.status(400).json({
 			status: 'error',
 			code: 400,
 			data: 'Bad request',
-			message: 'Field of avatar with file not found',
+			message: 'File not found',
 		});
 	next();
 };