Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const UserSchema = new Schema({
- posts: [{
- type: Schema.Types.ObjectId,
- ref: 'posts'
- }],
- firstName: {
- type: String,
- required: true
- },
- lastName: {
- type: String,
- required: true
- },
- ...
- });
- module.exports = User = mongoose.model('users', UserSchema);
- const PostSchema = new Schema({
- user: {
- type: Schema.Types.ObjectId,
- ref: 'users'
- },
- text: {
- type: String,
- required: true
- },
- name: {
- type: String
- },
- ...
- });
- module.exports = Post = mongoose.model('posts', PostSchema);
- const User = require('../../models/User');
- router.post('/login', (req, res) => {
- const { errors, isValid } = validateLoginInput(req.body);
- // Check Validation
- if (! isValid) {
- return res.status(400).json(errors);
- }
- const email = req.body.email;
- const password = req.body.password;
- // Find user by email
- User.findOne({ email })
- .populate('posts')
- .then(user => {
- if (! user) {
- errors.email = 'User not found';
- return res.status(400).json(errors);
- }
- // Check password
- bcrypt.compare(password, user.password).then(isMatch => {
- if (isMatch) {
- // User Matched
- // Create JWT Payload
- const payload = {
- id: user.id,
- firstName: user.firstName,
- lastName: user.lastName,
- name: user.firstName + ' ' + user.lastName,
- avatar: user.avatar,
- posts: user.posts
- };
- jwt.sign(
- payload,
- keys.secretOrKey,
- { expiresIn: 3600 }, (err, token) => {
- res.json({
- success: true,
- token: 'Bearer ' + token,
- payload
- });
- });
- } else {
- errors.password = 'Password is incorrect';
- return res.status(400).json(errors);
- }
- });
- });
- });
- router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
- const { errors, isValid } = validatePostInput(req.body);
- if (! isValid) {
- // Return errors with 400 status
- return res.status(400).json(errors)
- }
- const newPost = new Post({
- text: req.body.text,
- name: req.body.name,
- avatar: req.body.avatar,
- user: req.user.id
- });
- newPost.save().then(post => res.json(post));
- });
Add Comment
Please, Sign In to add comment