auth.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. if (accepts === "html") {
  21. return utils.sleep(2000).then(() => {
  22. return res.render("partials/login_signup", {
  23. layout: null,
  24. error
  25. });
  26. });
  27. } else {
  28. throw new CustomError(error, 401);
  29. }
  30. }
  31. if (user && isStrict && !user.verified) {
  32. const errorMessage = "Your email address is not verified. " +
  33. "Sign up to get the verification link again."
  34. if (accepts === "html") {
  35. return res.render("partials/login_signup", {
  36. layout: null,
  37. error: errorMessage
  38. });
  39. } else {
  40. throw new CustomError(errorMessage, 400);
  41. }
  42. }
  43. if (user && user.banned) {
  44. const errorMessage = "You're banned from using this website.";
  45. if (accepts === "html") {
  46. return res.render("partials/login_signup", {
  47. layout: null,
  48. error: errorMessage
  49. });
  50. } else {
  51. throw new CustomError(errorMessage, 403);
  52. }
  53. }
  54. if (user) {
  55. req.user = {
  56. ...user,
  57. admin: utils.isAdmin(user.email)
  58. };
  59. return next();
  60. }
  61. return next();
  62. })(req, res, next);
  63. }
  64. }
  65. const local = authenticate("local", "Login credentials are wrong.", true);
  66. const jwt = authenticate("jwt", "Unauthorized.", true);
  67. const jwtLoose = authenticate("jwt", "Unauthorized.", false);
  68. const apikey = authenticate("localapikey", "API key is not correct.", false);
  69. /**
  70. * @type {import("express").Handler}
  71. */
  72. async function cooldown(req, res, next) {
  73. if (env.DISALLOW_ANONYMOUS_LINKS) return next();
  74. const cooldownConfig = env.NON_USER_COOLDOWN;
  75. if (req.user || !cooldownConfig) return next();
  76. const ip = await query.ip.find({
  77. ip: req.realIP.toLowerCase(),
  78. created_at: [">", subMinutes(new Date(), cooldownConfig).toISOString()]
  79. });
  80. if (ip) {
  81. const timeToWait =
  82. cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
  83. throw new CustomError(
  84. `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
  85. 400
  86. );
  87. }
  88. next();
  89. }
  90. /**
  91. * @type {import("express").Handler}
  92. */
  93. function admin(req, res, next) {
  94. // FIXME: attaching to req is risky, find another way
  95. if (req.user.admin) return next();
  96. throw new CustomError("Unauthorized", 401);
  97. }
  98. /**
  99. * @type {import("express").Handler}
  100. */
  101. async function signup(req, res) {
  102. const salt = await bcrypt.genSalt(12);
  103. const password = await bcrypt.hash(req.body.password, salt);
  104. const accepts = req.accepts(["json", "html"]);
  105. const user = await query.user.add(
  106. { email: req.body.email, password },
  107. req.user
  108. );
  109. await mail.verification(user);
  110. if (accepts === "html") {
  111. return res.render("partials/signup_verify_email", { layout: null });
  112. }
  113. return res.status(201).send({ message: "A verification email has been sent." });
  114. }
  115. /**
  116. * @type {import("express").Handler}
  117. */
  118. function login(req, res) {
  119. const token = utils.signToken(req.user);
  120. const accepts = req.accepts(["json", "html"]);
  121. if (accepts === "html") {
  122. res.cookie("token", token, {
  123. maxAge: 1000 * 60 * 15, // expire after seven days
  124. httpOnly: true,
  125. secure: env.isProd
  126. });
  127. return res.render("partials/login_welcome", { layout: false });
  128. }
  129. return res.status(200).send({ token });
  130. }
  131. /**
  132. * @type {import("express").Handler}
  133. */
  134. async function verify(req, res, next) {
  135. if (!req.params.verificationToken) return next();
  136. const [user] = await query.user.update(
  137. {
  138. verification_token: req.params.verificationToken,
  139. verification_expires: [">", new Date().toISOString()]
  140. },
  141. {
  142. verified: true,
  143. verification_token: null,
  144. verification_expires: null
  145. }
  146. );
  147. if (user) {
  148. const token = utils.signToken(user);
  149. req.token = token;
  150. }
  151. return next();
  152. }
  153. /**
  154. * @type {import("express").Handler}
  155. */
  156. async function changePassword(req, res) {
  157. const salt = await bcrypt.genSalt(12);
  158. const password = await bcrypt.hash(req.body.password, salt);
  159. const [user] = await query.user.update({ id: req.user.id }, { password });
  160. if (!user) {
  161. throw new CustomError("Couldn't change the password. Try again later.");
  162. }
  163. return res
  164. .status(200)
  165. .send({ message: "Your password has been changed successfully." });
  166. }
  167. /**
  168. * @type {import("express").Handler}
  169. */
  170. async function generateApiKey(req, res) {
  171. const apikey = nanoid(40);
  172. redis.remove.user(req.user);
  173. const [user] = await query.user.update({ id: req.user.id }, { apikey });
  174. if (!user) {
  175. throw new CustomError("Couldn't generate API key. Please try again later.");
  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. throw new CustomError("Password is wrong.", 400);
  232. }
  233. const currentUser = await query.user.find({ email });
  234. if (currentUser) {
  235. throw new CustomError("Can't use this email address.", 400);
  236. }
  237. const [updatedUser] = await query.user.update(
  238. { id: req.user.id },
  239. {
  240. change_email_address: email,
  241. change_email_token: uuid(),
  242. change_email_expires: addMinutes(new Date(), 30).toISOString()
  243. }
  244. );
  245. redis.remove.user(updatedUser);
  246. if (updatedUser) {
  247. await mail.changeEmail({ ...updatedUser, email });
  248. }
  249. return res.status(200).send({
  250. message:
  251. "If email address exists, an email " +
  252. "with a verification link has been sent."
  253. });
  254. }
  255. /**
  256. * @type {import("express").Handler}
  257. */
  258. async function changeEmail(req, res, next) {
  259. const { changeEmailToken } = req.params;
  260. if (changeEmailToken) {
  261. const foundUser = await query.user.find({
  262. change_email_token: changeEmailToken
  263. });
  264. if (!foundUser) return next();
  265. const [user] = await query.user.update(
  266. {
  267. change_email_token: changeEmailToken,
  268. change_email_expires: [">", new Date().toISOString()]
  269. },
  270. {
  271. change_email_token: null,
  272. change_email_expires: null,
  273. change_email_address: null,
  274. email: foundUser.change_email_address
  275. }
  276. );
  277. redis.remove.user(foundUser);
  278. if (user) {
  279. const token = utils.signToken(user);
  280. req.token = token;
  281. }
  282. }
  283. return next();
  284. }
  285. module.exports = {
  286. admin,
  287. apikey,
  288. changeEmail,
  289. changeEmailRequest,
  290. changePassword,
  291. cooldown,
  292. generateApiKey,
  293. jwt,
  294. jwtLoose,
  295. local,
  296. login,
  297. resetPassword,
  298. resetPasswordRequest,
  299. signup,
  300. signupAccess,
  301. verify,
  302. }