authController.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. const fs = require('fs');
  2. const path = require('path');
  3. const passport = require('passport');
  4. const JWT = require('jsonwebtoken');
  5. const axios = require('axios');
  6. const config = require('../config');
  7. const transporter = require('../mail/mail');
  8. const { resetMailText, verifyMailText } = require('../mail/text');
  9. const {
  10. createUser,
  11. changePassword,
  12. generateApiKey,
  13. getUser,
  14. verifyUser,
  15. requestPasswordReset,
  16. resetPassword,
  17. } = require('../db/user');
  18. /* Read email template */
  19. const resetEmailTemplatePath = path.join(__dirname, '../mail/template-reset.html');
  20. const verifyEmailTemplatePath = path.join(__dirname, '../mail/template-verify.html');
  21. const resetEmailTemplate = fs
  22. .readFileSync(resetEmailTemplatePath, { encoding: 'utf-8' })
  23. .replace(/{{domain}}/gm, config.DEFAULT_DOMAIN);
  24. const verifyEmailTemplate = fs
  25. .readFileSync(verifyEmailTemplatePath, { encoding: 'utf-8' })
  26. .replace(/{{domain}}/gm, config.DEFAULT_DOMAIN);
  27. /* Function to generate JWT */
  28. const signToken = user =>
  29. JWT.sign(
  30. {
  31. iss: 'ApiAuth',
  32. sub: user.email,
  33. domain: user.domain || '',
  34. iat: new Date().getTime(),
  35. exp: new Date().setDate(new Date().getDate() + 7),
  36. },
  37. config.JWT_SECRET
  38. );
  39. /* Passport.js authentication controller */
  40. const authenticate = (type, error, isStrict = true) =>
  41. function auth(req, res, next) {
  42. if (req.user) return next();
  43. return passport.authenticate(type, (err, user) => {
  44. if (err) return res.status(400);
  45. if (!user && isStrict) return res.status(401).json({ error });
  46. if (user.banned) {
  47. return res.status(400).json({ error: 'Your are banned from using this website.' });
  48. }
  49. req.user = user;
  50. return next();
  51. })(req, res, next);
  52. };
  53. exports.authLocal = authenticate('local', 'Login email and/or password are wrong.');
  54. exports.authJwt = authenticate('jwt', 'Unauthorized.');
  55. exports.authJwtLoose = authenticate('jwt', 'Unauthorized.', false);
  56. exports.authApikey = authenticate('localapikey', 'API key is not correct.', false);
  57. /* reCaptcha controller */
  58. exports.recaptcha = async (req, res, next) => {
  59. if (!req.user) {
  60. const isReCaptchaValid = await axios({
  61. method: 'post',
  62. url: 'https://www.google.com/recaptcha/api/siteverify',
  63. headers: {
  64. 'Content-type': 'application/x-www-form-urlencoded',
  65. },
  66. params: {
  67. secret: config.RECAPTCHA_SECRET_KEY,
  68. response: req.body.reCaptchaToken,
  69. remoteip: req.realIp,
  70. },
  71. });
  72. if (!isReCaptchaValid.data.success) {
  73. return res.status(401).json({ error: 'reCAPTCHA is not valid. Try again.' });
  74. }
  75. }
  76. return next();
  77. };
  78. exports.signup = async (req, res) => {
  79. const { email, password } = req.body;
  80. if (password.length > 64) {
  81. return res.status(400).json({ error: 'Maximum password length is 64.' });
  82. }
  83. if (email.length > 64) {
  84. return res.status(400).json({ error: 'Maximum email length is 64.' });
  85. }
  86. const user = await getUser({ email });
  87. if (user && user.verified) return res.status(403).json({ error: 'Email is already in use.' });
  88. const newUser = await createUser({ email, password });
  89. const mail = await transporter.sendMail({
  90. from: config.MAIL_USER,
  91. to: newUser.email,
  92. subject: 'Verify your account',
  93. text: verifyMailText.replace('{{verification}}', newUser.verificationToken),
  94. html: verifyEmailTemplate.replace('{{verification}}', newUser.verificationToken),
  95. });
  96. if (mail.accepted.length) {
  97. return res.status(201).json({ email, message: 'Verification email has been sent.' });
  98. }
  99. return res.status(400).json({ error: "Couldn't send verification email. Try again." });
  100. };
  101. exports.login = ({ user }, res) => {
  102. const token = signToken(user);
  103. return res.status(200).json({ token });
  104. };
  105. exports.renew = ({ user }, res) => {
  106. const token = signToken(user);
  107. return res.status(200).json({ token });
  108. };
  109. exports.verify = async (req, res, next) => {
  110. const { verificationToken = '' } = req.params;
  111. const user = await verifyUser({ verificationToken });
  112. if (user) {
  113. const token = signToken(user);
  114. req.user = { token };
  115. }
  116. return next();
  117. };
  118. exports.changePassword = async ({ body: { password }, user }, res) => {
  119. if (password.length < 8) {
  120. return res.status(400).json({ error: 'Password must be at least 8 chars long.' });
  121. }
  122. if (password.length > 64) {
  123. return res.status(400).json({ error: 'Maximum password length is 64.' });
  124. }
  125. const changedUser = await changePassword({ email: user.email, password });
  126. if (changedUser) {
  127. return res.status(200).json({ message: 'Your password has been changed successfully.' });
  128. }
  129. return res.status(400).json({ error: "Couldn't change the password. Try again later" });
  130. };
  131. exports.generateApiKey = async ({ user }, res) => {
  132. const { apikey } = await generateApiKey({ email: user.email });
  133. if (apikey) {
  134. return res.status(201).json({ apikey });
  135. }
  136. return res.status(400).json({ error: 'Sorry, an error occured. Please try again later.' });
  137. };
  138. exports.userSettings = ({ user }, res) =>
  139. res.status(200).json({ apikey: user.apikey || '', customDomain: user.domain || '' });
  140. exports.requestPasswordReset = async ({ body: { email } }, res) => {
  141. const user = await requestPasswordReset({ email });
  142. if (!user) {
  143. return res.status(400).json({ error: "Couldn't reset password." });
  144. }
  145. const mail = await transporter.sendMail({
  146. from: config.MAIL_USER,
  147. to: user.email,
  148. subject: 'Reset your password',
  149. text: resetMailText
  150. .replace(/{{resetpassword}}/gm, user.resetPasswordToken)
  151. .replace(/{{domain}}/gm, config.DEFAULT_DOMAIN),
  152. html: resetEmailTemplate
  153. .replace(/{{resetpassword}}/gm, user.resetPasswordToken)
  154. .replace(/{{domain}}/gm, config.DEFAULT_DOMAIN),
  155. });
  156. if (mail.accepted.length) {
  157. return res.status(200).json({ email, message: 'Reset password email has been sent.' });
  158. }
  159. return res.status(400).json({ error: "Couldn't reset password." });
  160. };
  161. exports.resetPassword = async (req, res, next) => {
  162. const { resetPasswordToken = '' } = req.params;
  163. const user = await resetPassword({ resetPasswordToken });
  164. if (user) {
  165. const token = signToken(user);
  166. req.user = { token };
  167. }
  168. return next();
  169. };