auth.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 { v4 as uuid } from "uuid";
  7. import axios from "axios";
  8. import { CustomError } from "../utils";
  9. import * as utils from "../utils";
  10. import * as redis from "../redis";
  11. import * as mail from "../mail";
  12. import query from "../queries";
  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("You're 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. if (env.DISALLOW_ANONYMOUS_LINKS) return next();
  56. const cooldownConfig = env.NON_USER_COOLDOWN;
  57. if (req.user || !cooldownConfig) return next();
  58. const ip = await query.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.DISALLOW_ANONYMOUS_LINKS) return next();
  75. if (!env.RECAPTCHA_SECRET_KEY) return next();
  76. const isReCaptchaValid = await axios({
  77. method: "post",
  78. url: "https://www.google.com/recaptcha/api/siteverify",
  79. headers: {
  80. "Content-type": "application/x-www-form-urlencoded"
  81. },
  82. params: {
  83. secret: env.RECAPTCHA_SECRET_KEY,
  84. response: req.body.reCaptchaToken,
  85. remoteip: req.realIP
  86. }
  87. });
  88. if (!isReCaptchaValid.data.success) {
  89. throw new CustomError("reCAPTCHA is not valid. Try again.", 401);
  90. }
  91. return next();
  92. };
  93. export const admin: Handler = async (req, res, next) => {
  94. if (req.user.admin) return next();
  95. throw new CustomError("Unauthorized", 401);
  96. };
  97. export const signup: Handler = async (req, res) => {
  98. const salt = await bcrypt.genSalt(12);
  99. const password = await bcrypt.hash(req.body.password, salt);
  100. const user = await query.user.add(
  101. { email: req.body.email, password },
  102. req.user
  103. );
  104. await mail.verification(user);
  105. return res.status(201).send({ message: "Verification email has been sent." });
  106. };
  107. export const token: Handler = async (req, res) => {
  108. const token = utils.signToken(req.user);
  109. return res.status(200).send({ token });
  110. };
  111. export const verify: Handler = async (req, res, next) => {
  112. if (!req.params.verificationToken) return next();
  113. const [user] = await query.user.update(
  114. {
  115. verification_token: req.params.verificationToken,
  116. verification_expires: [">", new Date().toISOString()]
  117. },
  118. {
  119. verified: true,
  120. verification_token: null,
  121. verification_expires: null
  122. }
  123. );
  124. if (user) {
  125. const token = utils.signToken(user);
  126. req.token = token;
  127. }
  128. return next();
  129. };
  130. export const changePassword: Handler = async (req, res) => {
  131. const salt = await bcrypt.genSalt(12);
  132. const password = await bcrypt.hash(req.body.password, salt);
  133. const [user] = await query.user.update({ id: req.user.id }, { password });
  134. if (!user) {
  135. throw new CustomError("Couldn't change the password. Try again later.");
  136. }
  137. return res
  138. .status(200)
  139. .send({ message: "Your password has been changed successfully." });
  140. };
  141. export const generateApiKey: Handler = async (req, res) => {
  142. const apikey = nanoid(40);
  143. redis.remove.user(req.user);
  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: Handler = 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).send({
  162. message: "If email address exists, a reset password email has been sent."
  163. });
  164. };
  165. export const resetPassword: Handler = 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. };
  182. export const signupAccess: Handler = (req, res, next) => {
  183. if (!env.DISALLOW_REGISTRATION) return next();
  184. return res.status(403).send({ message: "Registration is not allowed." });
  185. };
  186. export const changeEmailRequest: Handler = async (req, res) => {
  187. const { email, password } = req.body;
  188. const isMatch = await bcrypt.compare(password, req.user.password);
  189. if (!isMatch) {
  190. throw new CustomError("Password is wrong.", 400);
  191. }
  192. const currentUser = await query.user.find({ email });
  193. if (currentUser) {
  194. throw new CustomError("Can't use this email address.", 400);
  195. }
  196. const [updatedUser] = await query.user.update(
  197. { id: req.user.id },
  198. {
  199. change_email_address: email,
  200. change_email_token: uuid(),
  201. change_email_expires: addMinutes(new Date(), 30).toISOString()
  202. }
  203. );
  204. redis.remove.user(updatedUser);
  205. if (updatedUser) {
  206. await mail.changeEmail({ ...updatedUser, email });
  207. }
  208. return res.status(200).send({
  209. message:
  210. "If email address exists, an email " +
  211. "with a verification link has been sent."
  212. });
  213. };
  214. export const changeEmail: Handler = async (req, res, next) => {
  215. const { changeEmailToken } = req.params;
  216. if (changeEmailToken) {
  217. const foundUser = await query.user.find({
  218. change_email_token: changeEmailToken
  219. });
  220. if (!foundUser) return next();
  221. const [user] = await query.user.update(
  222. {
  223. change_email_token: changeEmailToken,
  224. change_email_expires: [">", new Date().toISOString()]
  225. },
  226. {
  227. change_email_token: null,
  228. change_email_expires: null,
  229. change_email_address: null,
  230. email: foundUser.change_email_address
  231. }
  232. );
  233. redis.remove.user(foundUser);
  234. if (user) {
  235. const token = utils.signToken(user as UserJoined);
  236. req.token = token;
  237. }
  238. }
  239. return next();
  240. };