Skip to content

Commit

Permalink
Add server side validation
Browse files Browse the repository at this point in the history
  • Loading branch information
gocreating committed Oct 31, 2016
1 parent 430bb93 commit 5274da3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
22 changes: 18 additions & 4 deletions src/server/controllers/user.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import fs from 'fs';
import path from 'path';
import mkdirp from 'mkdirp';
import assign from 'object-assign';
import configs from '../../../configs/project/server';
import Errors from '../../common/constants/Errors';
import { handleDbError } from '../decorators/handleError';
import handleError, { handleDbError } from '../decorators/handleError';
import User from '../models/User';
import filterAttribute from '../utils/filterAttribute';
import { loginUser } from '../../common/actions/userActions';
Expand Down Expand Up @@ -213,8 +216,19 @@ export default {
uploadAvatar(req, res) {
// use `req.file` to access the avatar file
// and use `req.body` to access other fileds
res.json({
downloadURL: `/users/${req.user._id}/${req.file.filename}`,
});
let { filename } = req.files.avatar[0];
let tmpPath = req.files.avatar[0].path;
let targetDir = path.join(
__dirname, '../../public', 'users', req.user._id.toString()
);
let targetPath = path.join(targetDir, filename);

mkdirp(targetDir, handleError(res)(() => {
fs.rename(tmpPath, targetPath, handleError(res)(() => {
res.json({
downloadURL: `/users/${req.user._id}/${filename}`,
});
}));
}));
},
};
5 changes: 4 additions & 1 deletion src/server/middlewares/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import User from '../models/User';
export default {
form: (formPath, onlyFields = []) => (req, res, next) => {
let { validate } = require(`../../common/components/forms/${formPath}`);
let errors = validate(req.body);
let errors = validate({
...req.body,
...req.files,
});

if (onlyFields.length > 0) {
let newErrors = {};
Expand Down
5 changes: 3 additions & 2 deletions src/server/routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,10 @@ export default ({ app }) => {
app.post('/api/users/me/avatar',
authRequired,
fileUpload.disk({
destination: 'users/{userId}',
destination: 'tmp/{userId}',
filename: 'avatar.jpg',
}).single('avatar'),
}).fields([{ name: 'avatar' }]),
validate.form('user/AvatarForm'),
userController.uploadAvatar);

// form
Expand Down

0 comments on commit 5274da3

Please sign in to comment.