auth.handler.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. res.locals.isAdmin = utils.isAdmin(user.email);
  34. req.user = {
  35. ...user,
  36. admin: utils.isAdmin(user.email)
  37. };
  38. return next();
  39. }
  40. return next();
  41. })(req, res, next);
  42. }
  43. }
  44. const local = authenticate("local", "Login credentials are wrong.", true);
  45. const jwt = authenticate("jwt", "Unauthorized.", true);
  46. const jwtLoose = authenticate("jwt", "Unauthorized.", false);
  47. const apikey = authenticate("localapikey", "API key is not correct.", false);
  48. /**
  49. * @type {import("express").Handler}
  50. */
  51. async function cooldown(req, res, next) {
  52. if (env.DISALLOW_ANONYMOUS_LINKS) return next();
  53. const cooldownConfig = env.NON_USER_COOLDOWN;
  54. if (req.user || !cooldownConfig) return next();
  55. const ip = await query.ip.find({
  56. ip: req.realIP.toLowerCase(),
  57. created_at: [">", subMinutes(new Date(), cooldownConfig).toISOString()]
  58. });
  59. if (ip) {
  60. const timeToWait =
  61. cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
  62. throw new CustomError(
  63. `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
  64. 400
  65. );
  66. }
  67. next();
  68. }
  69. /**
  70. * @type {import("express").Handler}
  71. */
  72. function admin(req, res, next) {
  73. // FIXME: attaching to req is risky, find another way
  74. if (req.user.admin) return next();
  75. throw new CustomError("Unauthorized", 401);
  76. }
  77. /**
  78. * @type {import("express").Handler}
  79. */
  80. async function signup(req, res) {
  81. const salt = await bcrypt.genSalt(12);
  82. const password = await bcrypt.hash(req.body.password, salt);
  83. const user = await query.user.add(
  84. { email: req.body.email, password },
  85. req.user
  86. );
  87. await mail.verification(user);
  88. if (req.isHTML) {
  89. res.render("partials/auth/verify");
  90. return;
  91. }
  92. return res.status(201).send({ message: "A verification email has been sent." });
  93. }
  94. /**
  95. * @type {import("express").Handler}
  96. */
  97. function login(req, res) {
  98. const token = utils.signToken(req.user);
  99. if (req.isHTML) {
  100. res.cookie("token", token, {
  101. maxAge: 1000 * 60 * 60 * 24 * 7, // expire after seven days
  102. httpOnly: true,
  103. secure: env.isProd
  104. });
  105. res.render("partials/auth/welcome");
  106. return;
  107. }
  108. return res.status(200).send({ token });
  109. }
  110. /**
  111. * @type {import("express").Handler}
  112. */
  113. async function verify(req, res, next) {
  114. if (!req.params.verificationToken) return next();
  115. const [user] = await query.user.update(
  116. {
  117. verification_token: req.params.verificationToken,
  118. verification_expires: [">", new Date().toISOString()]
  119. },
  120. {
  121. verified: true,
  122. verification_token: null,
  123. verification_expires: null
  124. }
  125. );
  126. if (user) {
  127. const token = utils.signToken(user);
  128. req.token = token;
  129. }
  130. return next();
  131. }
  132. /**
  133. * @type {import("express").Handler}
  134. */
  135. async function changePassword(req, res) {
  136. const isMatch = await bcrypt.compare(req.body.currentpassword, req.user.password);
  137. if (!isMatch) {
  138. const message = "Current password is not correct.";
  139. res.locals.errors = { currentpassword: message };
  140. throw new CustomError(message, 401);
  141. }
  142. const salt = await bcrypt.genSalt(12);
  143. const newpassword = await bcrypt.hash(req.body.newpassword, salt);
  144. const [user] = await query.user.update({ id: req.user.id }, { password: newpassword });
  145. if (!user) {
  146. throw new CustomError("Couldn't change the password. Try again later.");
  147. }
  148. await utils.sleep(1000);
  149. if (req.isHTML) {
  150. res.setHeader("HX-Trigger-After-Swap", "resetChangePasswordForm");
  151. res.render("partials/settings/change_password", {
  152. success: "Password has been changed."
  153. });
  154. return;
  155. }
  156. return res
  157. .status(200)
  158. .send({ message: "Your password has been changed successfully." });
  159. }
  160. /**
  161. * @type {import("express").Handler}
  162. */
  163. async function generateApiKey(req, res) {
  164. const apikey = nanoid(40);
  165. redis.remove.user(req.user);
  166. const [user] = await query.user.update({ id: req.user.id }, { apikey });
  167. if (!user) {
  168. throw new CustomError("Couldn't generate API key. Please try again later.");
  169. }
  170. await utils.sleep(1000);
  171. if (req.isHTML) {
  172. res.render("partials/settings/apikey", {
  173. user: { apikey },
  174. });
  175. return;
  176. }
  177. return res.status(201).send({ apikey });
  178. }
  179. /**
  180. * @type {import("express").Handler}
  181. */
  182. async function resetPasswordRequest(req, res) {
  183. const [user] = await query.user.update(
  184. { email: req.body.email },
  185. {
  186. reset_password_token: uuid(),
  187. reset_password_expires: addMinutes(new Date(), 30).toISOString()
  188. }
  189. );
  190. if (user) {
  191. await mail.resetPasswordToken(user);
  192. }
  193. return res.status(200).send({
  194. message: "If email address exists, a reset password email has been sent."
  195. });
  196. }
  197. /**
  198. * @type {import("express").Handler}
  199. */
  200. async function resetPassword(req, res, next) {
  201. const { resetPasswordToken } = req.params;
  202. if (resetPasswordToken) {
  203. const [user] = await query.user.update(
  204. {
  205. reset_password_token: resetPasswordToken,
  206. reset_password_expires: [">", new Date().toISOString()]
  207. },
  208. { reset_password_expires: null, reset_password_token: null }
  209. );
  210. if (user) {
  211. const token = utils.signToken(user);
  212. req.token = token;
  213. }
  214. }
  215. return next();
  216. }
  217. /**
  218. * @type {import("express").Handler}
  219. */
  220. function signupAccess(req, res, next) {
  221. if (!env.DISALLOW_REGISTRATION) return next();
  222. return res.status(403).send({ message: "Registration is not allowed." });
  223. }
  224. /**
  225. * @type {import("express").Handler}
  226. */
  227. async function changeEmailRequest(req, res) {
  228. const { email, password } = req.body;
  229. const isMatch = await bcrypt.compare(password, req.user.password);
  230. if (!isMatch) {
  231. const error = "Password is not correct.";
  232. res.locals.errors = { password: error };
  233. throw new CustomError(error, 401);
  234. }
  235. const currentUser = await query.user.find({ email });
  236. if (currentUser) {
  237. const error = "Can't use this email address.";
  238. res.locals.errors = { email: error };
  239. throw new CustomError(error, 400);
  240. }
  241. const [updatedUser] = await query.user.update(
  242. { id: req.user.id },
  243. {
  244. change_email_address: email,
  245. change_email_token: uuid(),
  246. change_email_expires: addMinutes(new Date(), 30).toISOString()
  247. }
  248. );
  249. redis.remove.user(updatedUser);
  250. if (updatedUser) {
  251. await mail.changeEmail({ ...updatedUser, email });
  252. }
  253. const message = "A verification link has been sent to the requested email address."
  254. if (req.isHTML) {
  255. res.setHeader("HX-Trigger-After-Swap", "resetChangeEmailForm");
  256. res.render("partials/settings/change_email", {
  257. success: message
  258. });
  259. return;
  260. }
  261. return res.status(200).send({ message });
  262. }
  263. /**
  264. * @type {import("express").Handler}
  265. */
  266. async function changeEmail(req, res, next) {
  267. const { changeEmailToken } = req.params;
  268. if (changeEmailToken) {
  269. const foundUser = await query.user.find({
  270. change_email_token: changeEmailToken
  271. });
  272. if (!foundUser) return next();
  273. const [user] = await query.user.update(
  274. {
  275. change_email_token: changeEmailToken,
  276. change_email_expires: [">", new Date().toISOString()]
  277. },
  278. {
  279. change_email_token: null,
  280. change_email_expires: null,
  281. change_email_address: null,
  282. email: foundUser.change_email_address
  283. }
  284. );
  285. redis.remove.user(foundUser);
  286. if (user) {
  287. const token = utils.signToken(user);
  288. req.token = token;
  289. }
  290. }
  291. return next();
  292. }
  293. module.exports = {
  294. admin,
  295. apikey,
  296. changeEmail,
  297. changeEmailRequest,
  298. changePassword,
  299. cooldown,
  300. generateApiKey,
  301. jwt,
  302. jwtLoose,
  303. local,
  304. login,
  305. resetPassword,
  306. resetPasswordRequest,
  307. signup,
  308. signupAccess,
  309. verify,
  310. }