auth.ts 5.9 KB

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