Skip to content

Commit

Permalink
feat: Add recovery password
Browse files Browse the repository at this point in the history
  • Loading branch information
Idir authored and Idir committed Jun 29, 2020
1 parent 45dcc03 commit 19036d3
Show file tree
Hide file tree
Showing 12 changed files with 963 additions and 516 deletions.
338 changes: 192 additions & 146 deletions src/controllers/login.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,177 +4,223 @@ const userProvider = require("../providers/user.provider");
const emailService = require("../services/email.service");
const tokenProvider = require("../providers/token.provider");
const refreshTokenProvider = require("../providers/refresh-token.provider");
const forgetPasswordTokenProvider = require("../providers/forget-password-token.provider");
const newrelic = require("newrelic");
const { v1: uuidv1 } = require("uuid");
const {v1: uuidv1} = require("uuid");

exports.recovery = (req, res) => {
const { username } = req.body;
userProvider
.findUserByUsername(username)
.then(user => {
if (!user) {
return res.status(404).send();
}
return res.status(204).send();
})
.catch(() => {
res.status(500).send();
});
exports.reset = (req, res) => {
const {username, token, new_password} = req.body;
userProvider.findUserByUsername(username)
.then(user => {
forgetPasswordTokenProvider.findOne(user.id, token)
.then(resetToken => {
if (!resetToken) return res.status(404).send({err: "Token not found"});
userProvider.updatePassword(user.id, new_password)
.then(() => res.status(204).send())
.catch(() => res.status(500).send());
})
.catch(err => {
res.status(500).send({err: err.message});
});
})
.catch(err => {
res.status(500).send({err: err.message});
});
};

exports.confirmation = (req, res) => {
const token = req.params.token;
tokenProvider.findOne(token)
.then((token) => {
if (!token) return res.status(404).send({ message: "We were unable to find a valid token. Your token my have expired." });
const userId = token.userId;
userProvider.update(userId, { isVerified: true }).then(() => {
res.status(204).send();
}).catch(err => {
res.status(500).send({ message: err.message });
});
});
exports.forget = (req, res) => {
const {username} = req.body;
userProvider
.findUserByUsername(username)
.then(user => {
if (!user) {
return res.status(404).send();
}
forgetPasswordTokenProvider.create(user.id)
.then(forgetToken => {
emailService
.forgetPassword(username, forgetToken.token, process.env.TINAPTIC_WEB_URL)
.then(() => {
return res.status(204).send();
})
.catch(err => {
res.send({
error: "email_not_sent",
e: err.message
});
});
});
})
.catch((err) => {
console.log(err);

res.status(500).send({
error: "email_not_sent",
e: err.message
});
});
};

exports.create = (req, res) => {
const userBody = req.body;
const { username, password, name, lastName, language } = userBody;
const data = {
username,
password,
name,
lastName,
language,
};

userProvider.findUserByUsername(username)
.then(exist => {
if (exist) {
res.send({ error: "email_already_exist" });
} else {
userProvider.create(data)
.then(user => {
tokenProvider.create(user).then(dataToken => {
emailService.sendConfirmation(user, dataToken, process.env.TINAPTIC_WEB_URL).then(() => {
res.send();
}).catch((err) => {
res.send({
error: "email_not_sent",
e: err.message
});
});
exports.confirmation = (req, res) => {
const token = req.params.token;
tokenProvider.findOne(token)
.then((token) => {
if (!token) return res.status(404).send({message: "We were unable to find a valid token. Your token my have expired."});
const userId = token.userId;
userProvider.update(userId, {isVerified: true}).then(() => {
res.status(204).send();
}).catch(err => {
res.status(500)
.send({ message: err.message });
res.status(500).send({message: err.message});
});
})
.catch(err => {
res.status(500).send({
message:
});
};

exports.create = (req, res) => {
const userBody = req.body;
const {username, password, name, lastName, language} = userBody;
const data = {
username,
password,
name,
lastName,
language,
};

userProvider.findUserByUsername(username)
.then(exist => {
if (exist) {
res.send({error: "email_already_exist"});
} else {
userProvider.create(data)
.then(user => {
tokenProvider.create(user).then(dataToken => {
emailService.sendConfirmation(user, dataToken, process.env.TINAPTIC_WEB_URL).then(() => {
res.send();
}).catch((err) => {
res.send({
error: "email_not_sent",
e: err.message
});
});
}).catch(err => {
res.status(500)
.send({message: err.message});
});
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the user.",
});
});
}
}).catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the user.",
});
});
}
}).catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the user.",
});
});
});
};

exports.findOne = (req, res) => {
const username = req.query.username;
const password = req.query.password;
userProvider.findUserByUsername(username).then(user => {
if (!user) {
res.status(404).send({ error: "email_doesnt_exist" });
} else {
if (bcrypt.compareSync(password, user.password)) {
if (!user.isVerified || user.isBlocked) return res.status(403).send({ error: "Your account has not been verified." });
const token = jwt.sign(
user.toJSON(),
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_TOKEN_EXPIRATION_TIME });
const refreshToken = uuidv1();
refreshTokenProvider.findByUser(user.id).then((data) => {
if (data) {
data.refreshToken = uuidv1();
data.save();
} else {
refreshTokenProvider.create(user.id, refreshToken);
}
const username = req.query.username;
const password = req.query.password;
userProvider.findUserByUsername(username).then(user => {
if (!user) {
res.status(404).send({error: "email_doesnt_exist"});
} else {
if (bcrypt.compareSync(password, user.password)) {
if (!user.isVerified || user.isBlocked) return res.status(403).send({error: "Your account has not been verified."});
const token = jwt.sign(
user.toJSON(),
process.env.JWT_SECRET,
{expiresIn: process.env.JWT_TOKEN_EXPIRATION_TIME});
const refreshToken = uuidv1();
refreshTokenProvider.findByUser(user.id).then((data) => {
if (data) {
data.refreshToken = uuidv1();
data.save();
} else {
refreshTokenProvider.create(user.id, refreshToken);
}
});
const tokens = {
token,
refreshToken
};
res.send({tokens});
} else {
res.status(401).send({error: "Invalid email or password"});
}
}
})
.catch(err => {
newrelic.noticeError(err);
res
.status(500)
.send({
error: "Error retrieving User",
e: err.message
});
});
const tokens = { token, refreshToken };
res.send({ tokens });
} else {
res.status(401).send({ error: "Invalid email or password" });
}
}
})
.catch(err => {
newrelic.noticeError(err);
res
.status(500)
.send({ error: "Error retrieving User", e: err.message });
});
};

exports.findAll = (req, res) => {
if (req.user.role !== "ROOT") {
res.status(403).send({ message: "Forbidden" });
return;
}
if (req.user.role !== "ROOT") {
res.status(403).send({message: "Forbidden"});
return;
}

userProvider.findAll()
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving users.",
});
});
userProvider.findAll()
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving users.",
});
});
};

exports.update = (req, res) => {
const deleteUserId = req.params.id;
const { user } = req.body;
userProvider.update(deleteUserId, user).then(data => {
if (!data) {
res.status(404).send({
message: `Cannot update User with id=${deleteUserId}. Maybe User was not found!`,
});
} else {
res.send({
message: "User was updated successfully!",
});
}
}).catch(() => {
res.status(500).send({
message: "Could not delete User with id=" + deleteUserId,
const deleteUserId = req.params.id;
const {user} = req.body;
userProvider.update(deleteUserId, user).then(data => {
if (!data) {
res.status(404).send({
message: `Cannot update User with id=${deleteUserId}. Maybe User was not found!`,
});
} else {
res.send({
message: "User was updated successfully!",
});
}
}).catch(() => {
res.status(500).send({
message: "Could not delete User with id=" + deleteUserId,
});
});
});
};

exports.delete = (req, res) => {
const id = req.params.id;
userProvider.delete(id)
.then(data => {
if (!data) {
res.status(404).send({
message: `Cannot delete Answer with id=${id}. Maybe Answer was not found!`,
});
} else {
res.status(204).send({
message: "Answer was deleted successfully!",
const id = req.params.id;
userProvider.delete(id)
.then(data => {
if (!data) {
res.status(404).send({
message: `Cannot delete Answer with id=${id}. Maybe Answer was not found!`,
});
} else {
res.status(204).send({
message: "Answer was deleted successfully!",
});
}
})
.catch(() => {
res.status(500).send({
message: "Could not delete Answer with id=" + id,
});
});
}
})
.catch(() => {
res.status(500).send({
message: "Could not delete Answer with id=" + id,
});
});
};
8 changes: 7 additions & 1 deletion src/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@
"body": "{{playerName}} ha completado la terea '{{examTitle}}' con una nota de {{score}} sobre {{numberQuestions}}."
},
"confirm": {
"subject": "Gracias por re",
"subject": "Gracias por registrarse",
"title": "Gracias por registrarte en Tinaptic.com! ¿Ahora qué?",
"body": "Confirma tu dirección de correo electrónico para comenzar a administrar tus exámenes en Tinaptic.",
"button": "Confirmar"
},
"forget": {
"subject": "Restablecer contraseña",
"title": "Has solicitado el cambio de contraseña en Tinaptic.com",
"body": "Haz click en el link para poder cambiar tu conntraseña.",
"button": "Cambiar"
},
"account_verification": "Verificación de la cuenta."
}
1 change: 1 addition & 0 deletions src/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ db.folder = require('./folder.model.js')(mongoose);
db.event = require('./event.model.js')(mongoose);
db.token = require('./token.model.js')(mongoose);
db.refreshToken = require('./refresh-token.model.js')(mongoose);
db.resetPasswordToken = require('./reset-password-token.model')(mongoose);

module.exports = db;
Loading

0 comments on commit 19036d3

Please sign in to comment.