Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 1 addition & 48 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,18 @@ const asyncHandler = require('../middleware/async');
const sendEmail = require('../utils/sendEmail');
const User = require('../models/User');

// @desc Register user
// @route POST /api/v1/auth/register
// @access Public
exports.register = asyncHandler(async (req, res, next) => {
const { name, email, password, role } = req.body;

// Create user
const user = await User.create({
name,
email,
password,
role,
});

// grab token and send to email
const confirmEmailToken = user.generateEmailConfirmToken();

// Create reset url
const confirmEmailURL = `${req.protocol}://${req.get(
'host',
)}/api/v1/auth/confirmemail?token=${confirmEmailToken}`;
Expand All @@ -39,25 +33,20 @@ exports.register = asyncHandler(async (req, res, next) => {
sendTokenResponse(user, 200, res);
});

// @desc Login user
// @route POST /api/v1/auth/login
// @access Public

exports.login = asyncHandler(async (req, res, next) => {
const { email, password } = req.body;

// Validate emil & password
if (!email || !password) {
return next(new ErrorResponse('Please provide an email and password', 400));
}

// Check for user
const user = await User.findOne({ email }).select('+password');

if (!user) {
return next(new ErrorResponse('Invalid credentials', 401));
}

// Check if password matches
const isMatch = await user.matchPassword(password);

if (!isMatch) {
Expand All @@ -67,9 +56,6 @@ exports.login = asyncHandler(async (req, res, next) => {
sendTokenResponse(user, 200, res);
});

// @desc Log user out / clear cookie
// @route GET /api/v1/auth/logout
// @access Public
exports.logout = asyncHandler(async (req, res, next) => {
res.cookie('token', 'none', {
expires: new Date(Date.now() + 10 * 1000),
Expand All @@ -82,11 +68,7 @@ exports.logout = asyncHandler(async (req, res, next) => {
});
});

// @desc Get current logged in user
// @route GET /api/v1/auth/me
// @access Private
exports.getMe = asyncHandler(async (req, res, next) => {
// user is already available in req due to the protect middleware
const user = req.user;

res.status(200).json({
Expand All @@ -95,9 +77,6 @@ exports.getMe = asyncHandler(async (req, res, next) => {
});
});

// @desc Update user details
// @route PUT /api/v1/auth/updatedetails
// @access Private
exports.updateDetails = asyncHandler(async (req, res, next) => {
const fieldsToUpdate = {
name: req.body.name,
Expand All @@ -115,13 +94,9 @@ exports.updateDetails = asyncHandler(async (req, res, next) => {
});
});

// @desc Update password
// @route PUT /api/v1/auth/updatepassword
// @access Private
exports.updatePassword = asyncHandler(async (req, res, next) => {
const user = await User.findById(req.user.id).select('+password');

// Check current password
if (!(await user.matchPassword(req.body.currentPassword))) {
return next(new ErrorResponse('Password is incorrect', 401));
}
Expand All @@ -132,22 +107,17 @@ exports.updatePassword = asyncHandler(async (req, res, next) => {
sendTokenResponse(user, 200, res);
});

// @desc Forgot password
// @route POST /api/v1/auth/forgotpassword
// @access Public
exports.forgotPassword = asyncHandler(async (req, res, next) => {
const user = await User.findOne({ email: req.body.email });

if (!user) {
return next(new ErrorResponse('There is no user with that email', 404));
}

// Get reset token
const resetToken = user.getResetPasswordToken();

await user.save({ validateBeforeSave: false });

// Create reset url
const resetUrl = `${req.protocol}://${req.get(
'host',
)}/api/v1/auth/resetpassword/${resetToken}`;
Expand All @@ -173,11 +143,7 @@ exports.forgotPassword = asyncHandler(async (req, res, next) => {
}
});

// @desc Reset password
// @route PUT /api/v1/auth/resetpassword/:resettoken
// @access Public
exports.resetPassword = asyncHandler(async (req, res, next) => {
// Get hashed token
const resetPasswordToken = crypto
.createHash('sha256')
.update(req.params.resettoken)
Expand All @@ -192,7 +158,6 @@ exports.resetPassword = asyncHandler(async (req, res, next) => {
return next(new ErrorResponse('Invalid token', 400));
}

// Set new password
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
Expand All @@ -201,13 +166,7 @@ exports.resetPassword = asyncHandler(async (req, res, next) => {
sendTokenResponse(user, 200, res);
});

/**
* @desc Confirm Email
* @route GET /api/v1/auth/confirmemail
* @access Public
*/
exports.confirmEmail = asyncHandler(async (req, res, next) => {
// grab token from email
const { token } = req.query;

if (!token) {
Expand All @@ -220,7 +179,6 @@ exports.confirmEmail = asyncHandler(async (req, res, next) => {
.update(splitToken)
.digest('hex');

// get user by token
const user = await User.findOne({
confirmEmailToken,
isEmailConfirmed: false,
Expand All @@ -230,20 +188,15 @@ exports.confirmEmail = asyncHandler(async (req, res, next) => {
return next(new ErrorResponse('Invalid Token', 400));
}

// update confirmed to true
user.confirmEmailToken = undefined;
user.isEmailConfirmed = true;

// save
user.save({ validateBeforeSave: false });

// return token
sendTokenResponse(user, 200, res);
});

// Get token from model, create cookie and send response
const sendTokenResponse = (user, statusCode, res) => {
// Create token
const token = user.getSignedJwtToken();

const options = {
Expand Down
34 changes: 0 additions & 34 deletions controllers/bootcamps.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,10 @@ const asyncHandler = require('../middleware/async');
const geocoder = require('../utils/geocoder');
const Bootcamp = require('../models/Bootcamp');

// @desc Get all bootcamps
// @route GET /api/v1/bootcamps
// @access Public
exports.getBootcamps = asyncHandler(async (req, res, next) => {
res.status(200).json(res.advancedResults);
});

// @desc Get single bootcamp
// @route GET /api/v1/bootcamps/:id
// @access Public
exports.getBootcamp = asyncHandler(async (req, res, next) => {
const bootcamp = await Bootcamp.findById(req.params.id);

Expand All @@ -26,17 +20,11 @@ exports.getBootcamp = asyncHandler(async (req, res, next) => {
res.status(200).json({ success: true, data: bootcamp });
});

// @desc Create new bootcamp
// @route POST /api/v1/bootcamps
// @access Private
exports.createBootcamp = asyncHandler(async (req, res, next) => {
// Add user to req,body
req.body.user = req.user.id;

// Check for published bootcamp
const publishedBootcamp = await Bootcamp.findOne({ user: req.user.id });

// If the user is not an admin, they can only add one bootcamp
if (publishedBootcamp && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand All @@ -54,9 +42,6 @@ exports.createBootcamp = asyncHandler(async (req, res, next) => {
});
});

// @desc Update bootcamp
// @route PUT /api/v1/bootcamps/:id
// @access Private
exports.updateBootcamp = asyncHandler(async (req, res, next) => {
let bootcamp = await Bootcamp.findById(req.params.id);

Expand All @@ -66,7 +51,6 @@ exports.updateBootcamp = asyncHandler(async (req, res, next) => {
);
}

// Make sure user is bootcamp owner
if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand All @@ -84,9 +68,6 @@ exports.updateBootcamp = asyncHandler(async (req, res, next) => {
res.status(200).json({ success: true, data: bootcamp });
});

// @desc Delete bootcamp
// @route DELETE /api/v1/bootcamps/:id
// @access Private
exports.deleteBootcamp = asyncHandler(async (req, res, next) => {
const bootcamp = await Bootcamp.findById(req.params.id);

Expand All @@ -96,7 +77,6 @@ exports.deleteBootcamp = asyncHandler(async (req, res, next) => {
);
}

// Make sure user is bootcamp owner
if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand All @@ -111,20 +91,13 @@ exports.deleteBootcamp = asyncHandler(async (req, res, next) => {
res.status(200).json({ success: true, data: {} });
});

// @desc Get bootcamps within a radius
// @route GET /api/v1/bootcamps/radius/:zipcode/:distance
// @access Private
exports.getBootcampsInRadius = asyncHandler(async (req, res, next) => {
const { zipcode, distance } = req.params;

// Get lat/lng from geocoder
const loc = await geocoder.geocode(zipcode);
const lat = loc[0].latitude;
const lng = loc[0].longitude;

// Calc radius using radians
// Divide dist by radius of Earth
// Earth Radius = 3,963 mi / 6,378 km
const radius = distance / 3963;

const bootcamps = await Bootcamp.find({
Expand All @@ -138,9 +111,6 @@ exports.getBootcampsInRadius = asyncHandler(async (req, res, next) => {
});
});

// @desc Upload photo for bootcamp
// @route PUT /api/v1/bootcamps/:id/photo
// @access Private
exports.bootcampPhotoUpload = asyncHandler(async (req, res, next) => {
const bootcamp = await Bootcamp.findById(req.params.id);

Expand All @@ -150,7 +120,6 @@ exports.bootcampPhotoUpload = asyncHandler(async (req, res, next) => {
);
}

// Make sure user is bootcamp owner
if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand All @@ -166,12 +135,10 @@ exports.bootcampPhotoUpload = asyncHandler(async (req, res, next) => {

const file = req.files.file;

// Make sure the image is a photo
if (!file.mimetype.startsWith('image')) {
return next(new ErrorResponse(`Please upload an image file`, 400));
}

// Check filesize
if (file.size > process.env.MAX_FILE_UPLOAD) {
return next(
new ErrorResponse(
Expand All @@ -181,7 +148,6 @@ exports.bootcampPhotoUpload = asyncHandler(async (req, res, next) => {
);
}

// Create custom filename
file.name = `photo_${bootcamp._id}${path.parse(file.name).ext}`;

file.mv(`${process.env.FILE_UPLOAD_PATH}/${file.name}`, async err => {
Expand Down
19 changes: 0 additions & 19 deletions controllers/courses.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ const asyncHandler = require('../middleware/async');
const Course = require('../models/Course');
const Bootcamp = require('../models/Bootcamp');

// @desc Get courses
// @route GET /api/v1/courses
// @route GET /api/v1/bootcamps/:bootcampId/courses
// @access Public
exports.getCourses = asyncHandler(async (req, res, next) => {
if (req.params.bootcampId) {
const courses = await Course.find({ bootcamp: req.params.bootcampId });
Expand All @@ -21,9 +17,6 @@ exports.getCourses = asyncHandler(async (req, res, next) => {
}
});

// @desc Get single course
// @route GET /api/v1/courses/:id
// @access Public
exports.getCourse = asyncHandler(async (req, res, next) => {
const course = await Course.findById(req.params.id).populate({
path: 'bootcamp',
Expand All @@ -42,9 +35,6 @@ exports.getCourse = asyncHandler(async (req, res, next) => {
});
});

// @desc Add course
// @route POST /api/v1/bootcamps/:bootcampId/courses
// @access Private
exports.addCourse = asyncHandler(async (req, res, next) => {
req.body.bootcamp = req.params.bootcampId;
req.body.user = req.user.id;
Expand All @@ -60,7 +50,6 @@ exports.addCourse = asyncHandler(async (req, res, next) => {
);
}

// Make sure user is bootcamp owner
if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand All @@ -78,9 +67,6 @@ exports.addCourse = asyncHandler(async (req, res, next) => {
});
});

// @desc Update course
// @route PUT /api/v1/courses/:id
// @access Private
exports.updateCourse = asyncHandler(async (req, res, next) => {
let course = await Course.findById(req.params.id);

Expand All @@ -90,7 +76,6 @@ exports.updateCourse = asyncHandler(async (req, res, next) => {
);
}

// Make sure user is course owner
if (course.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand All @@ -113,9 +98,6 @@ exports.updateCourse = asyncHandler(async (req, res, next) => {
});
});

// @desc Delete course
// @route DELETE /api/v1/courses/:id
// @access Private
exports.deleteCourse = asyncHandler(async (req, res, next) => {
const course = await Course.findById(req.params.id);

Expand All @@ -125,7 +107,6 @@ exports.deleteCourse = asyncHandler(async (req, res, next) => {
);
}

// Make sure user is course owner
if (course.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
Expand Down
Loading