Skip to content

Commit

Permalink
Trying to move my commits from Brian's account to my account
Browse files Browse the repository at this point in the history
  • Loading branch information
stevethekey committed Apr 29, 2023
2 parents 790130d + ed8d19a commit bf1c1cc
Show file tree
Hide file tree
Showing 31 changed files with 29,341 additions and 5,844 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ Create a .env file in then root and add the following
```
NODE_ENV = development
PORT = 5000
EMAIL_ADDRESS = your email address
EMAIL_PASSWORD = your email password (gmail app password)
MONGO_URI = your mongodb uri
JWT_SECRET = 'abc123'
PAYPAL_CLIENT_ID = your paypal client id
Expand Down
50 changes: 50 additions & 0 deletions backend/controllers/contactController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import nodemailer from 'nodemailer'

// @desc Send email
// @route POST /api/send-email
// @access Public
const sendMail = async (req, res) => {
// Get the subject and message the user entered from the request body
const subject = req.body['subject']['subject'];
const message = req.body['subject']['message'];

// Make sure all fields are filled in
if (!subject || !message) {
// If all fields are not filled in, show an error message
return res.status(400).json({ message: 'All fields are required' });
}

// Create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
// Email address defined in .env file
user: process.env.EMAIL_ADDRESS,
// Email app password defined in .env file
pass: process.env.EMAIL_PASSWORD,
}
});

// Set the email options
var mailOptions = {
from: process.env.EMAIL_ADDRESS,
to: process.env.EMAIL_ADDRESS,
// Set the subject to the subject the user entered on the form
subject: subject,
// Set the message to the message the user entered on the form
text: message
};

// Send the email
transporter.sendMail(mailOptions, function(error, info){
if (error) {
// Log error if failed
console.log(error);
} else {
// Log the email was sent
console.log('Email sent: ' + info.response);
}
});
}

export { sendMail };
122 changes: 62 additions & 60 deletions backend/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import asyncHandler from 'express-async-handler'
import generateToken from '../utils/generateToken.js'
import User from '../models/userModel.js'
import asyncHandler from 'express-async-handler';
import User from '../models/userModel.js';
import generateToken from '../utils/generateToken.js';

// @desc Auth user & get token
// @route POST /api/users/login
// @access Public
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body
const { email, password } = req.body;

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

if (user && (await user.matchPassword(password))) {
res.json({
Expand All @@ -17,162 +17,164 @@ const authUser = asyncHandler(async (req, res) => {
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user._id),
})
});
} else {
res.status(401)
throw new Error('Invalid email or password')
res.status(401);
throw new Error('Invalid email or password');
}
})
});

// @desc Register a new user
// @route POST /api/users
// @access Public
const registerUser = asyncHandler(async (req, res) => {
const { name, email, password } = req.body
const { name, email, password, isAdmin } = req.body;

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

if (userExists) {
res.status(400)
throw new Error('User already exists')
res.status(400);
throw new Error('User already exists');
}

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

if (user) {
console.log('user', user);
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user._id),
})
});
} else {
res.status(400)
throw new Error('Invalid user data')
res.status(400);
throw new Error('Invalid user data');
}
})
});

// @desc Get user profile
// @route GET /api/users/profile
// @access Private
const getUserProfile = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id)
const user = await User.findById(req.user._id);

if (user) {
res.json({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
})
});
} else {
res.status(404)
throw new Error('User not found')
res.status(404);
throw new Error('User not found');
}
})
});

// @desc Update user profile
// @route PUT /api/users/profile
// @access Private
const updateUserProfile = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id)
const user = await User.findById(req.user._id);

if (user) {
user.name = req.body.name || user.name
user.email = req.body.email || user.email
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
if (req.body.password) {
user.password = req.body.password
user.password = req.body.password;
}

const updatedUser = await user.save()
const updatedUser = await user.save();

res.json({
_id: updatedUser._id,
name: updatedUser.name,
email: updatedUser.email,
isAdmin: updatedUser.isAdmin,
token: generateToken(updatedUser._id),
})
});
} else {
res.status(404)
throw new Error('User not found')
res.status(404);
throw new Error('User not found');
}
})
});

// @desc Get all users
// @route GET /api/users
// @access Private/Admin
const getUsers = asyncHandler(async (req, res) => {
const users = await User.find({})
res.json(users)
})
const users = await User.find({});
res.json(users);
});

// @desc Delete user
// @route DELETE /api/users/:id
// @access Private/Admin
const deleteUser = asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id)
const user = await User.findById(req.params.id);

if (user) {
await user.remove()
res.json({ message: 'User removed' })
await user.remove();
res.json({ message: 'User removed' });
} else {
res.status(404)
throw new Error('User not found')
res.status(404);
throw new Error('User not found');
}
})
});

// @desc Get user by ID
// @route GET /api/users/:id
// @access Private/Admin
const getUserById = asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id).select('-password')
const user = await User.findById(req.params.id).select('-password');

if (user) {
res.json(user)
res.json(user);
} else {
res.status(404)
throw new Error('User not found')
res.status(404);
throw new Error('User not found');
}
})
});

// @desc Update user
// @route PUT /api/users/:id
// @access Private/Admin
const updateUser = asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id)
const user = await User.findById(req.params.id);

if (user) {
user.name = req.body.name || user.name
user.email = req.body.email || user.email
user.isAdmin = req.body.isAdmin
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
user.isAdmin = req.body.isAdmin;

const updatedUser = await user.save()
const updatedUser = await user.save();

res.json({
_id: updatedUser._id,
name: updatedUser.name,
email: updatedUser.email,
isAdmin: updatedUser.isAdmin,
})
});
} else {
res.status(404)
throw new Error('User not found')
res.status(404);
throw new Error('User not found');
}
})
});

export {
authUser,
registerUser,
getUserProfile,
updateUserProfile,
getUsers,
deleteUser,
getUserById,
getUserProfile,
getUsers,
registerUser,
updateUser,
}
updateUserProfile,
};
41 changes: 22 additions & 19 deletions backend/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,45 @@
import jwt from 'jsonwebtoken'
import asyncHandler from 'express-async-handler'
import User from '../models/userModel.js'
import asyncHandler from 'express-async-handler';
import jwt from 'jsonwebtoken';
import User from '../models/userModel.js';

const protect = asyncHandler(async (req, res, next) => {
let token
let token;

if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
try {
token = req.headers.authorization.split(' ')[1]
token = req.headers.authorization.split(' ')[1];

const decoded = jwt.verify(token, process.env.JWT_SECRET)
const decoded = jwt.verify(token, process.env.JWT_SECRET);

req.user = await User.findById(decoded.id).select('-password')
req.user = await User.findById(decoded.id).select('-password');

next()
next();
} catch (error) {
console.error(error)
res.status(401)
throw new Error('Not authorized, token failed')
console.error(error);
res.status(401);
throw new Error('Not authorized, token failed');
}
}

if (!token) {
res.status(401)
throw new Error('Not authorized, no token')
res.status(401);
console.error('Not authorized, no token');
throw new Error('Not authorized, no token');
}
})
});

const admin = (req, res, next) => {
if (req.user && req.user.isAdmin) {
next()
next();
} else {
res.status(401)
throw new Error('Not authorized as an admin')
res.status(401);
console.error('user', req.user);
console.error('Not authorized as an admin');
throw new Error('Not authorized as an admin');
}
}
};

export { protect, admin }
export { admin, protect };
8 changes: 8 additions & 0 deletions backend/routes/contactRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import express from 'express';
const router = express.Router();
import { sendMail } from '../controllers/contactController.js';

// Add a route for the new endpoint using the Express router.
router.route('/').post(sendMail);

export default router;
Loading

0 comments on commit bf1c1cc

Please sign in to comment.