auth.ts 5.6 KB

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