auth.handler.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. const { differenceInMinutes, addMinutes, subMinutes } = require("date-fns");
  2. const passport = require("passport");
  3. const { v4: uuid } = require("uuid");
  4. const bcrypt = require("bcryptjs");
  5. const nanoid = require("nanoid");
  6. const axios = require("axios");
  7. const { CustomError } = require("../utils");
  8. const query = require("../queries");
  9. const utils = require("../utils");
  10. const redis = require("../redis");
  11. const mail = require("../mail");
  12. const env = require("../env");
  13. function authenticate(type, error, isStrict) {
  14. return function auth(req, res, next) {
  15. if (req.user) return next();
  16. passport.authenticate(type, (err, user) => {
  17. if (err) return next(err);
  18. const accepts = req.accepts(["json", "html"]);
  19. if (!user && isStrict) {
  20. req.viewTemplate = "partials/auth/form";
  21. throw new CustomError(error, 401);
  22. }
  23. if (user && isStrict && !user.verified) {
  24. req.viewTemplate = "partials/auth/form";
  25. throw new CustomError("Your email address is not verified. " +
  26. "Sign up to get the verification link again.", 400);
  27. }
  28. if (user && user.banned) {
  29. req.viewTemplate = "partials/auth/form";
  30. throw new CustomError("You're banned from using this website.", 403);
  31. }
  32. if (user) {
  33. req.user = {
  34. ...user,
  35. admin: utils.isAdmin(user.email)
  36. };
  37. return next();
  38. }
  39. return next();
  40. })(req, res, next);
  41. }
  42. }
  43. const local = authenticate("local", "Login credentials are wrong.", true);
  44. const jwt = authenticate("jwt", "Unauthorized.", true);
  45. const jwtLoose = authenticate("jwt", "Unauthorized.", false);
  46. const apikey = authenticate("localapikey", "API key is not correct.", false);
  47. /**
  48. * @type {import("express").Handler}
  49. */
  50. async function cooldown(req, res, next) {
  51. if (env.DISALLOW_ANONYMOUS_LINKS) return next();
  52. const cooldownConfig = env.NON_USER_COOLDOWN;
  53. if (req.user || !cooldownConfig) return next();
  54. const ip = await query.ip.find({
  55. ip: req.realIP.toLowerCase(),
  56. created_at: [">", subMinutes(new Date(), cooldownConfig).toISOString()]
  57. });
  58. if (ip) {
  59. const timeToWait =
  60. cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
  61. throw new CustomError(
  62. `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
  63. 400
  64. );
  65. }
  66. next();
  67. }
  68. /**
  69. * @type {import("express").Handler}
  70. */
  71. function admin(req, res, next) {
  72. // FIXME: attaching to req is risky, find another way
  73. if (req.user.admin) return next();
  74. throw new CustomError("Unauthorized", 401);
  75. }
  76. /**
  77. * @type {import("express").Handler}
  78. */
  79. async function signup(req, res) {
  80. const salt = await bcrypt.genSalt(12);
  81. const password = await bcrypt.hash(req.body.password, salt);
  82. const user = await query.user.add(
  83. { email: req.body.email, password },
  84. req.user
  85. );
  86. await mail.verification(user);
  87. if (req.isHTML) {
  88. res.render("partials/auth/verify");
  89. return;
  90. }
  91. return res.status(201).send({ message: "A verification email has been sent." });
  92. }
  93. /**
  94. * @type {import("express").Handler}
  95. */
  96. function login(req, res) {
  97. const token = utils.signToken(req.user);
  98. if (req.isHTML) {
  99. res.cookie("token", token, {
  100. maxAge: 1000 * 60 * 60 * 24 * 7, // expire after seven days
  101. httpOnly: true,
  102. secure: env.isProd
  103. });
  104. res.render("partials/auth/welcome");
  105. return;
  106. }
  107. return res.status(200).send({ token });
  108. }
  109. /**
  110. * @type {import("express").Handler}
  111. */
  112. async function verify(req, res, next) {
  113. if (!req.params.verificationToken) return next();
  114. const [user] = await query.user.update(
  115. {
  116. verification_token: req.params.verificationToken,
  117. verification_expires: [">", new Date().toISOString()]
  118. },
  119. {
  120. verified: true,
  121. verification_token: null,
  122. verification_expires: null
  123. }
  124. );
  125. if (user) {
  126. const token = utils.signToken(user);
  127. req.token = token;
  128. }
  129. return next();
  130. }
  131. /**
  132. * @type {import("express").Handler}
  133. */
  134. async function changePassword(req, res) {
  135. const salt = await bcrypt.genSalt(12);
  136. const password = await bcrypt.hash(req.body.password, salt);
  137. const [user] = await query.user.update({ id: req.user.id }, { password });
  138. if (!user) {
  139. throw new CustomError("Couldn't change the password. Try again later.");
  140. }
  141. return res
  142. .status(200)
  143. .send({ message: "Your password has been changed successfully." });
  144. }
  145. /**
  146. * @type {import("express").Handler}
  147. */
  148. async function generateApiKey(req, res) {
  149. const apikey = nanoid(40);
  150. redis.remove.user(req.user);
  151. const [user] = await query.user.update({ id: req.user.id }, { apikey });
  152. if (!user) {
  153. throw new CustomError("Couldn't generate API key. Please try again later.");
  154. }
  155. return res.status(201).send({ apikey });
  156. }
  157. /**
  158. * @type {import("express").Handler}
  159. */
  160. async function resetPasswordRequest(req, res) {
  161. const [user] = await query.user.update(
  162. { email: req.body.email },
  163. {
  164. reset_password_token: uuid(),
  165. reset_password_expires: addMinutes(new Date(), 30).toISOString()
  166. }
  167. );
  168. if (user) {
  169. await mail.resetPasswordToken(user);
  170. }
  171. return res.status(200).send({
  172. message: "If email address exists, a reset password email has been sent."
  173. });
  174. }
  175. /**
  176. * @type {import("express").Handler}
  177. */
  178. async function resetPassword(req, res, next) {
  179. const { resetPasswordToken } = req.params;
  180. if (resetPasswordToken) {
  181. const [user] = await query.user.update(
  182. {
  183. reset_password_token: resetPasswordToken,
  184. reset_password_expires: [">", new Date().toISOString()]
  185. },
  186. { reset_password_expires: null, reset_password_token: null }
  187. );
  188. if (user) {
  189. const token = utils.signToken(user);
  190. req.token = token;
  191. }
  192. }
  193. return next();
  194. }
  195. /**
  196. * @type {import("express").Handler}
  197. */
  198. function signupAccess(req, res, next) {
  199. if (!env.DISALLOW_REGISTRATION) return next();
  200. return res.status(403).send({ message: "Registration is not allowed." });
  201. }
  202. /**
  203. * @type {import("express").Handler}
  204. */
  205. async function changeEmailRequest(req, res) {
  206. const { email, password } = req.body;
  207. const isMatch = await bcrypt.compare(password, req.user.password);
  208. if (!isMatch) {
  209. throw new CustomError("Password is wrong.", 400);
  210. }
  211. const currentUser = await query.user.find({ email });
  212. if (currentUser) {
  213. throw new CustomError("Can't use this email address.", 400);
  214. }
  215. const [updatedUser] = await query.user.update(
  216. { id: req.user.id },
  217. {
  218. change_email_address: email,
  219. change_email_token: uuid(),
  220. change_email_expires: addMinutes(new Date(), 30).toISOString()
  221. }
  222. );
  223. redis.remove.user(updatedUser);
  224. if (updatedUser) {
  225. await mail.changeEmail({ ...updatedUser, email });
  226. }
  227. return res.status(200).send({
  228. message:
  229. "If email address exists, an email " +
  230. "with a verification link has been sent."
  231. });
  232. }
  233. /**
  234. * @type {import("express").Handler}
  235. */
  236. async function changeEmail(req, res, next) {
  237. const { changeEmailToken } = req.params;
  238. if (changeEmailToken) {
  239. const foundUser = await query.user.find({
  240. change_email_token: changeEmailToken
  241. });
  242. if (!foundUser) return next();
  243. const [user] = await query.user.update(
  244. {
  245. change_email_token: changeEmailToken,
  246. change_email_expires: [">", new Date().toISOString()]
  247. },
  248. {
  249. change_email_token: null,
  250. change_email_expires: null,
  251. change_email_address: null,
  252. email: foundUser.change_email_address
  253. }
  254. );
  255. redis.remove.user(foundUser);
  256. if (user) {
  257. const token = utils.signToken(user);
  258. req.token = token;
  259. }
  260. }
  261. return next();
  262. }
  263. module.exports = {
  264. admin,
  265. apikey,
  266. changeEmail,
  267. changeEmailRequest,
  268. changePassword,
  269. cooldown,
  270. generateApiKey,
  271. jwt,
  272. jwtLoose,
  273. local,
  274. login,
  275. resetPassword,
  276. resetPasswordRequest,
  277. signup,
  278. signupAccess,
  279. verify,
  280. }