auth.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 redis from "../redis";
  11. import queries from "../queries";
  12. import * as mail from "../mail";
  13. import query from "../queries";
  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 queries.ip.find({
  59. ip: req.realIP.toLowerCase(),
  60. created_at: [">", subMinutes(new Date(), cooldownConfig).toISOString()]
  61. });
  62. if (ip) {
  63. const timeToWait =
  64. cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
  65. throw new CustomError(
  66. `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
  67. 400
  68. );
  69. }
  70. next();
  71. };
  72. export const recaptcha: Handler = async (req, res, next) => {
  73. if (env.isDev || req.user) return next();
  74. if (!env.RECAPTCHA_SECRET_KEY) return next();
  75. const isReCaptchaValid = await axios({
  76. method: "post",
  77. url: "https://www.google.com/recaptcha/api/siteverify",
  78. headers: {
  79. "Content-type": "application/x-www-form-urlencoded"
  80. },
  81. params: {
  82. secret: env.RECAPTCHA_SECRET_KEY,
  83. response: req.body.reCaptchaToken,
  84. remoteip: req.realIP
  85. }
  86. });
  87. if (!isReCaptchaValid.data.success) {
  88. throw new CustomError("reCAPTCHA is not valid. Try again.", 401);
  89. }
  90. return next();
  91. };
  92. export const admin: Handler = async (req, res, next) => {
  93. if (req.user.admin) return next();
  94. throw new CustomError("Unauthorized", 401);
  95. };
  96. export const signup: Handler = async (req, res) => {
  97. const salt = await bcrypt.genSalt(12);
  98. const password = await bcrypt.hash(req.body.password, salt);
  99. const user = await query.user.add(
  100. { email: req.body.email, password },
  101. req.user
  102. );
  103. await mail.verification(user);
  104. return res.status(201).send({ message: "Verification email has been sent." });
  105. };
  106. export const token: Handler = async (req, res) => {
  107. const token = utils.signToken(req.user);
  108. return res.status(200).send({ token });
  109. };
  110. export const verify: Handler = async (req, res, next) => {
  111. if (!req.params.verificationToken) return next();
  112. const [user] = await query.user.update(
  113. {
  114. verification_token: req.params.verificationToken,
  115. verification_expires: [">", new Date().toISOString()]
  116. },
  117. {
  118. verified: true,
  119. verification_token: null,
  120. verification_expires: null
  121. }
  122. );
  123. if (user) {
  124. const token = utils.signToken(user);
  125. req.token = token;
  126. }
  127. return next();
  128. };
  129. export const changePassword: Handler = async (req, res) => {
  130. const salt = await bcrypt.genSalt(12);
  131. const password = await bcrypt.hash(req.body.password, salt);
  132. const [user] = await query.user.update({ id: req.user.id }, { password });
  133. if (!user) {
  134. throw new CustomError("Couldn't change the password. Try again later.");
  135. }
  136. return res
  137. .status(200)
  138. .send({ message: "Your password has been changed successfully." });
  139. };
  140. export const generateApiKey = async (req, res) => {
  141. const apikey = nanoid(40);
  142. redis.remove.user(req.user);
  143. const [user] = await query.user.update({ id: req.user.id }, { apikey });
  144. if (!user) {
  145. throw new CustomError("Couldn't generate API key. Please try again later.");
  146. }
  147. return res.status(201).send({ apikey });
  148. };
  149. export const resetPasswordRequest = async (req, res) => {
  150. const [user] = await query.user.update(
  151. { email: req.body.email },
  152. {
  153. reset_password_token: uuid(),
  154. reset_password_expires: addMinutes(new Date(), 30).toISOString()
  155. }
  156. );
  157. if (user) {
  158. await mail.resetPasswordToken(user);
  159. }
  160. return res.status(200).json({
  161. error: "If email address exists, a reset password email has been sent."
  162. });
  163. };
  164. export const resetPassword = async (req, res, next) => {
  165. const { resetPasswordToken } = req.params;
  166. if (resetPasswordToken) {
  167. const [user] = await query.user.update(
  168. {
  169. reset_password_token: resetPasswordToken,
  170. reset_password_expires: [">", new Date().toISOString()]
  171. },
  172. { reset_password_expires: null, reset_password_token: null }
  173. );
  174. if (user) {
  175. const token = utils.signToken(user as UserJoined);
  176. req.token = token;
  177. }
  178. }
  179. return next();
  180. };