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 mail from "../mail";
  11. import query from "../queries";
  12. import knex from "../knex";
  13. import env from "../env";
  14. const authenticate = (
  15. type: "jwt" | "local" | "localapikey",
  16. error: string,
  17. isStrict = true
  18. ) =>
  19. async function auth(req, res, next) {
  20. if (req.user) return next();
  21. passport.authenticate(type, (err, user) => {
  22. if (err) return next(err);
  23. if (!user && isStrict) {
  24. throw new CustomError(error, 401);
  25. }
  26. if (user && isStrict && !user.verified) {
  27. throw new CustomError(
  28. "Your email address is not verified. " +
  29. "Click on signup to get the verification link again.",
  30. 400
  31. );
  32. }
  33. if (user && user.banned) {
  34. throw new CustomError("Your are banned from using this website.", 403);
  35. }
  36. if (user) {
  37. req.user = {
  38. ...user,
  39. admin: utils.isAdmin(user.email)
  40. };
  41. return next();
  42. }
  43. return next();
  44. })(req, res, next);
  45. };
  46. export const local = authenticate("local", "Login credentials are wrong.");
  47. export const jwt = authenticate("jwt", "Unauthorized.");
  48. export const jwtLoose = authenticate("jwt", "Unauthorized.", false);
  49. export const apikey = authenticate(
  50. "localapikey",
  51. "API key is not correct.",
  52. false
  53. );
  54. export const cooldown: Handler = async (req, res, next) => {
  55. const cooldownConfig = env.NON_USER_COOLDOWN;
  56. if (req.user || !cooldownConfig) return next();
  57. const ip = await knex<IP>("ips")
  58. .where({ ip: req.realIP.toLowerCase() })
  59. .andWhere(
  60. "created_at",
  61. ">",
  62. subMinutes(new Date(), cooldownConfig).toISOString()
  63. )
  64. .first();
  65. if (ip) {
  66. const timeToWait =
  67. cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
  68. throw new CustomError(
  69. `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
  70. 400
  71. );
  72. }
  73. next();
  74. };
  75. export const recaptcha: Handler = async (req, res, next) => {
  76. if (env.isDev || req.user) 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 = async (req, res) => {
  143. const apikey = nanoid(40);
  144. const [user] = await query.user.update({ id: req.user.id }, { apikey });
  145. if (!user) {
  146. throw new CustomError("Couldn't generate API key. Please try again later.");
  147. }
  148. return res.status(201).send({ apikey });
  149. };
  150. export const resetPasswordRequest = async (req, res) => {
  151. const [user] = await query.user.update(
  152. { email: req.body.email },
  153. {
  154. reset_password_token: uuid(),
  155. reset_password_expires: addMinutes(new Date(), 30).toISOString()
  156. }
  157. );
  158. if (user) {
  159. await mail.resetPasswordToken(user);
  160. }
  161. return res.status(200).json({
  162. error: "If email address exists, a reset password email has been sent."
  163. });
  164. };
  165. export const resetPassword = async (req, res, next) => {
  166. const { resetPasswordToken } = req.params;
  167. if (resetPasswordToken) {
  168. const [user] = await query.user.update(
  169. {
  170. reset_password_token: resetPasswordToken,
  171. reset_password_expires: [">", new Date().toISOString()]
  172. },
  173. { reset_password_expires: null, reset_password_token: null }
  174. );
  175. if (user) {
  176. const token = utils.signToken(user as UserJoined);
  177. req.token = token;
  178. }
  179. }
  180. return next();
  181. };