Skip to content

Commit

Permalink
upload da iamgem
Browse files Browse the repository at this point in the history
  • Loading branch information
matheusbattisti committed Mar 30, 2022
1 parent afcae5b commit 1b99ac1
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 10 deletions.
5 changes: 5 additions & 0 deletions 13_REACTGRAM/backend/app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
require("dotenv").config();

const express = require("express");
const path = require("path");

const port = process.env.PORT;

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Upload directory
app.use(express.static(path.join(__dirname, "uploads")));

// db connection
require("./config/db.js");

Expand Down
61 changes: 55 additions & 6 deletions 13_REACTGRAM/backend/controllers/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,18 @@ const register = async (req, res) => {
password: passwordHash,
});

if (newUser) {
res.status(201).json({
_id: newUser._id,
token: generateToken(newUser._id),
});
} else {
// If user was created sucessfully, return the token
if (!newUser) {
res.status(422).json({
errors: ["Houve um erro, por favor tente novamente mais tarde."],
});
return;
}

res.status(201).json({
_id: newUser._id,
token: generateToken(newUser._id),
});
};

// Get logged in user
Expand All @@ -60,13 +62,60 @@ const login = async (req, res) => {

const user = await User.findOne({ email });

// Check if user exists
if (!user) {
res.json({ errors: ["Usuário não encontrado!"] });
return;
}

// Check if password matches
if (!(await bcrypt.compare(password, user.password))) {
res.json({ errors: ["Senha inválida!"] });
return;
}

// Return user with token
res.status(200).json({
_id: user._id,
token: generateToken(user._id),
});
};

// Update user
const update = async (req, res) => {
const { name, email, password, bio } = req.body;
const profileImage = req.file.filename;

const reqUser = req.user;

const user = await User.findById(reqUser._id);

if (name) {
user.name = name;
}

if (password) {
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
user.password = passwordHash;
}

if (profileImage) {
user.profileImage = profileImage;
}

if (bio) {
user.bio = bio;
}

await user.save();

res.status(200).json(user);
};

module.exports = {
register,
getCurrentUser,
login,
update,
};
32 changes: 32 additions & 0 deletions 13_REACTGRAM/backend/middlewares/imageUpload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const multer = require("multer");
const path = require("path");

// Destination to store image
const imageStorage = multer.diskStorage({
destination: function (req, file, cb) {
let folder = "";

if (req.baseUrl.includes("users")) {
folder = "users";
} else if (req.baseUrl.includes("photos")) {
folder = "photos";
}
cb(null, `uploads/${folder}/`);
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
},
});

const imageUpload = multer({
storage: imageStorage,
fileFilter(req, file, cb) {
if (!file.originalname.match(/\.(png|jpg)$/)) {
// upload only png and jpg format
return cb(new Error("Por favor, envie apenas png ou jpg!"));
}
cb(undefined, true);
},
});

module.exports = { imageUpload };
21 changes: 19 additions & 2 deletions 13_REACTGRAM/backend/middlewares/userValidations.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { body } = require("express-validator");

const userValidation = () => {
const userCreateValidation = () => {
return [
body("name")
.isString()
Expand Down Expand Up @@ -40,4 +40,21 @@ const loginValidation = () => {
];
};

module.exports = { userValidation, loginValidation };
const userUpdateValidation = () => {
return [
body("name")
.optional()
.isLength({ min: 3 })
.withMessage("O nome precisa ter no mínimo 3 caracteres."),
body("password")
.optional()
.isLength({ min: 5 })
.withMessage("A senha precisa de no mínimo 5 caracteres."),
];
};

module.exports = {
userCreateValidation,
loginValidation,
userUpdateValidation,
};
15 changes: 13 additions & 2 deletions 13_REACTGRAM/backend/routes/UserRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,28 @@ const {
register,
getCurrentUser,
login,
update,
} = require("../controllers/UserController");

const validate = require("../middlewares/handleValidations");
const {
userValidation,
userCreateValidation,
loginValidation,
userUpdateValidation,
} = require("../middlewares/userValidations");
const authGuard = require("../middlewares/authGuard");
const { imageUpload } = require("../middlewares/imageUpload");

router.post("/", userValidation(), validate, register);
router.post("/register", userCreateValidation(), validate, register);
router.get("/profile", authGuard, getCurrentUser);
router.post("/login", loginValidation(), validate, login);
router.put(
"/",
authGuard,
userUpdateValidation(),
validate,
imageUpload.single("profileImage"),
update
);

module.exports = router;
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 1b99ac1

Please sign in to comment.