|
|
@@ -3,6 +3,7 @@ import {mongoose} from 'mongoose';
|
|
|
import bcrypt from "bcrypt";
|
|
|
import jwt from "jsonwebtoken";
|
|
|
import {SECRET_KEY} from "../passport.js";
|
|
|
+import {isValidEmail} from "../utils.js";
|
|
|
|
|
|
const router = express.Router();
|
|
|
|
|
|
@@ -10,7 +11,7 @@ const router = express.Router();
|
|
|
const saltRounds = 10;
|
|
|
|
|
|
const userSchema = new mongoose.Schema({
|
|
|
- username: {
|
|
|
+ email: {
|
|
|
type: String,
|
|
|
required: true
|
|
|
},
|
|
|
@@ -29,16 +30,18 @@ function generateToken(user) {
|
|
|
}
|
|
|
|
|
|
router.post('/login', function (req, res) {
|
|
|
- const username = req.body.username;
|
|
|
+ const email = req.body.email;
|
|
|
const password = req.body.password;
|
|
|
- console.log(password);
|
|
|
- console.log(password);
|
|
|
|
|
|
- if (!password || !username) {
|
|
|
+ if (!password || !email) {
|
|
|
return res.status(400).json({ message: 'parameters invalid' });
|
|
|
}
|
|
|
|
|
|
- User.findOne({ username: username })
|
|
|
+ if (!isValidEmail(email)) {
|
|
|
+ return res.status(400).json({ message: 'email is invalid' });
|
|
|
+ }
|
|
|
+
|
|
|
+ User.findOne({ email: email })
|
|
|
.then(user => {
|
|
|
if (!user) {
|
|
|
return res.status(422).json({ message: 'no user found' });
|
|
|
@@ -60,16 +63,20 @@ router.post('/login', function (req, res) {
|
|
|
|
|
|
|
|
|
router.post('/register', async function (req, res) {
|
|
|
- const username = req.body.username;
|
|
|
+ const email = req.body.email;
|
|
|
const password = req.body.password;
|
|
|
|
|
|
- if (!password || !username) {
|
|
|
+ if (!password || !email) {
|
|
|
return res.status(400).json({ message: 'parameters invalid' });
|
|
|
}
|
|
|
|
|
|
+ if (!isValidEmail(email)) {
|
|
|
+ return res.status(400).json({ message: 'email is invalid' });
|
|
|
+ }
|
|
|
+
|
|
|
try {
|
|
|
// Check if user already exists
|
|
|
- const existingUser = await User.findOne({ username: username });
|
|
|
+ const existingUser = await User.findOne({ email: email });
|
|
|
if (existingUser) {
|
|
|
return res.status(403).json({ message: 'user already exists' });
|
|
|
}
|
|
|
@@ -80,7 +87,7 @@ router.post('/register', async function (req, res) {
|
|
|
return res.status(500).json({ error: err.message });
|
|
|
} else if (hash) {
|
|
|
// Insert user into database and generate token
|
|
|
- const user = await User.collection.insertOne({ username: username, password: hash });
|
|
|
+ const user = await User.collection.insertOne({ email: email, password: hash });
|
|
|
return res.json({ token: generateToken(user) });
|
|
|
}
|
|
|
});
|