auth.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { differenceInMinutes, addMinutes, subMinutes } from "date-fns";
  2. import { Handler } from "express";
  3. import passport from "passport";
  4. import bcrypt from "bcryptjs";
  5. import nanoid from "nanoid";
  6. import uuid from "uuid/v4";
  7. import axios from "axios";
  8. import { CustomError } from "../utils";
  9. import * as utils from "../utils";
  10. import * as mail from "../mail";
  11. import query from "../queries";
  12. import knex from "../knex";
  13. import * as redis from "../redis";
  14. import env from "../env";
  15. const authenticate = (
  16. type: "jwt" | "local" | "localapikey",
  17. error: string,
  18. isStrict = true
  19. ) =>
  20. async function auth(req, res, next) {
  21. if (req.user) return next();
  22. passport.authenticate(type, (err, user) => {
  23. if (err) return next(err);
  24. if (!user && isStrict) {
  25. throw new CustomError(error, 401);
  26. }
  27. if (user && isStrict && !user.verified) {
  28. throw new CustomError(
  29. "Your email address is not verified. " +
  30. "Click on signup to get the verification link again.",
  31. 400
  32. );
  33. }
  34. if (user && user.banned) {
  35. throw new CustomError("You're banned from using this website.", 403);
  36. }
  37. if (user) {
  38. req.user = {
  39. ...user,
  40. admin: utils.isAdmin(user.email)
  41. };
  42. return next();
  43. }
  44. return next();
  45. })(req, res, next);
  46. };
  47. export const local = authenticate("local", "Login credentials are wrong.");
  48. export const jwt = authenticate("jwt", "Unauthorized.");
  49. export const jwtLoose = authenticate("jwt", "Unauthorized.", false);
  50. export const apikey = authenticate(
  51. "localapikey",
  52. "API key is not correct.",
  53. false
  54. );
  55. export const cooldown: Handler = async (req, res, next) => {
  56. const cooldownConfig = env.NON_USER_COOLDOWN;
  57. if (req.user || !cooldownConfig) return next();
  58. const ip = await knex<IP>("ips")
  59. .where({ ip: req.realIP.toLowerCase() })
  60. .andWhere(
  61. "created_at",
  62. ">",
  63. subMinutes(new Date(), cooldownConfig).toISOString()
  64. )
  65. .first();
  66. if (ip) {
  67. const timeToWait =
  68. cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
  69. throw new CustomError(
  70. `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
  71. 400
  72. );
  73. }
  74. next();
  75. };
  76. export const recaptcha: Handler = async (req, res, next) => {
  77. if (env.isDev || req.user) return next();
  78. if (!env.RECAPTCHA_SECRET_KEY) return next();
  79. const isReCaptchaValid = await axios({
  80. method: "post",
  81. url: "https://www.google.com/recaptcha/api/siteverify",
  82. headers: {
  83. "Content-type": "application/x-www-form-urlencoded"
  84. },
  85. params: {
  86. secret: env.RECAPTCHA_SECRET_KEY,
  87. response: req.body.reCaptchaToken,
  88. remoteip: req.realIP
  89. }
  90. });
  91. if (!isReCaptchaValid.data.success) {
  92. throw new CustomError("reCAPTCHA is not valid. Try again.", 401);
  93. }
  94. return next();
  95. };
  96. export const admin: Handler = async (req, res, next) => {
  97. if (req.user.admin) return next();
  98. throw new CustomError("Unauthorized", 401);
  99. };
  100. export const signup: Handler = async (req, res) => {
  101. const salt = await bcrypt.genSalt(12);
  102. const password = await bcrypt.hash(req.body.password, salt);
  103. const user = await query.user.add(
  104. { email: req.body.email, password },
  105. req.user
  106. );
  107. await mail.verification(user);
  108. return res.status(201).send({ message: "Verification email has been sent." });
  109. };
  110. export const token: Handler = async (req, res) => {
  111. const token = utils.signToken(req.user);
  112. return res.status(200).send({ token });
  113. };
  114. export const verify: Handler = async (req, res, next) => {
  115. if (!req.params.verificationToken) return next();
  116. const [user] = await query.user.update(
  117. {
  118. verification_token: req.params.verificationToken,
  119. verification_expires: [">", new Date().toISOString()]
  120. },
  121. {
  122. verified: true,
  123. verification_token: null,
  124. verification_expires: null
  125. }
  126. );
  127. if (user) {
  128. const token = utils.signToken(user);
  129. req.token = token;
  130. }
  131. return next();
  132. };
  133. export const changePassword: Handler = async (req, res) => {
  134. const salt = await bcrypt.genSalt(12);
  135. const password = await bcrypt.hash(req.body.password, salt);
  136. const [user] = await query.user.update({ id: req.user.id }, { password });
  137. if (!user) {
  138. throw new CustomError("Couldn't change the password. Try again later.");
  139. }
  140. return res
  141. .status(200)
  142. .send({ message: "Your password has been changed successfully." });
  143. };
  144. export const generateApiKey = async (req, res) => {
  145. const apikey = nanoid(40);
  146. redis.remove.user(req.user);
  147. const [user] = await query.user.update({ id: req.user.id }, { apikey });
  148. if (!user) {
  149. throw new CustomError("Couldn't generate API key. Please try again later.");
  150. }
  151. return res.status(201).send({ apikey });
  152. };
  153. export const resetPasswordRequest = async (req, res) => {
  154. const [user] = await query.user.update(
  155. { email: req.body.email },
  156. {
  157. reset_password_token: uuid(),
  158. reset_password_expires: addMinutes(new Date(), 30).toISOString()
  159. }
  160. );
  161. if (user) {
  162. await mail.resetPasswordToken(user);
  163. }
  164. return res.status(200).json({
  165. error: "If email address exists, a reset password email has been sent."
  166. });
  167. };
  168. export const resetPassword = async (req, res, next) => {
  169. const { resetPasswordToken } = req.params;
  170. if (resetPasswordToken) {
  171. const [user] = await query.user.update(
  172. {
  173. reset_password_token: resetPasswordToken,
  174. reset_password_expires: [">", new Date().toISOString()]
  175. },
  176. { reset_password_expires: null, reset_password_token: null }
  177. );
  178. if (user) {
  179. const token = utils.signToken(user as UserJoined);
  180. req.token = token;
  181. }
  182. }
  183. return next();
  184. };