auth.handler.js 9.2 KB

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