| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296 |
- import { differenceInMinutes, addMinutes, subMinutes } from "date-fns";
- import { Handler } from "express";
- import passport from "passport";
- import bcrypt from "bcryptjs";
- import nanoid from "nanoid";
- import { v4 as uuid } from "uuid";
- import axios from "axios";
- import { CustomError } from "../utils";
- import * as utils from "../utils";
- import * as redis from "../redis";
- import * as mail from "../mail";
- import query from "../queries";
- import env from "../env";
- const authenticate = (
- type: "jwt" | "local" | "localapikey",
- error: string,
- isStrict = true
- ) =>
- async function auth(req, res, next) {
- if (req.user) return next();
- passport.authenticate(type, (err, user) => {
- if (err) return next(err);
- if (!user && isStrict) {
- throw new CustomError(error, 401);
- }
- if (user && isStrict && !user.verified) {
- throw new CustomError(
- "Your email address is not verified. " +
- "Click on signup to get the verification link again.",
- 400
- );
- }
- if (user && user.banned) {
- throw new CustomError("You're banned from using this website.", 403);
- }
- if (user) {
- req.user = {
- ...user,
- admin: utils.isAdmin(user.email)
- };
- return next();
- }
- return next();
- })(req, res, next);
- };
- export const local = authenticate("local", "Login credentials are wrong.");
- export const jwt = authenticate("jwt", "Unauthorized.");
- export const jwtLoose = authenticate("jwt", "Unauthorized.", false);
- export const apikey = authenticate(
- "localapikey",
- "API key is not correct.",
- false
- );
- export const cooldown: Handler = async (req, res, next) => {
- if (env.DISALLOW_ANONYMOUS_LINKS) return next();
- const cooldownConfig = env.NON_USER_COOLDOWN;
- if (req.user || !cooldownConfig) return next();
- const ip = await query.ip.find({
- ip: req.realIP.toLowerCase(),
- created_at: [">", subMinutes(new Date(), cooldownConfig).toISOString()]
- });
- if (ip) {
- const timeToWait =
- cooldownConfig - differenceInMinutes(new Date(), new Date(ip.created_at));
- throw new CustomError(
- `Non-logged in users are limited. Wait ${timeToWait} minutes or log in.`,
- 400
- );
- }
- next();
- };
- export const recaptcha: Handler = async (req, res, next) => {
- if (env.isDev || req.user) return next();
- if (env.DISALLOW_ANONYMOUS_LINKS) return next();
- if (!env.RECAPTCHA_SECRET_KEY) return next();
- const isReCaptchaValid = await axios({
- method: "post",
- url: "https://www.google.com/recaptcha/api/siteverify",
- headers: {
- "Content-type": "application/x-www-form-urlencoded"
- },
- params: {
- secret: env.RECAPTCHA_SECRET_KEY,
- response: req.body.reCaptchaToken,
- remoteip: req.realIP
- }
- });
- if (!isReCaptchaValid.data.success) {
- throw new CustomError("reCAPTCHA is not valid. Try again.", 401);
- }
- return next();
- };
- export const admin: Handler = async (req, res, next) => {
- if (req.user.admin) return next();
- throw new CustomError("Unauthorized", 401);
- };
- export const signup: Handler = async (req, res) => {
- const salt = await bcrypt.genSalt(12);
- const password = await bcrypt.hash(req.body.password, salt);
- const user = await query.user.add(
- { email: req.body.email, password },
- req.user
- );
- await mail.verification(user);
- return res.status(201).send({ message: "Verification email has been sent." });
- };
- export const token: Handler = async (req, res) => {
- const token = utils.signToken(req.user);
- return res.status(200).send({ token });
- };
- export const verify: Handler = async (req, res, next) => {
- if (!req.params.verificationToken) return next();
- const [user] = await query.user.update(
- {
- verification_token: req.params.verificationToken,
- verification_expires: [">", new Date().toISOString()]
- },
- {
- verified: true,
- verification_token: null,
- verification_expires: null
- }
- );
- if (user) {
- const token = utils.signToken(user);
- req.token = token;
- }
- return next();
- };
- export const changePassword: Handler = async (req, res) => {
- const salt = await bcrypt.genSalt(12);
- const password = await bcrypt.hash(req.body.password, salt);
- const [user] = await query.user.update({ id: req.user.id }, { password });
- if (!user) {
- throw new CustomError("Couldn't change the password. Try again later.");
- }
- return res
- .status(200)
- .send({ message: "Your password has been changed successfully." });
- };
- export const generateApiKey: Handler = async (req, res) => {
- const apikey = nanoid(40);
- redis.remove.user(req.user);
- const [user] = await query.user.update({ id: req.user.id }, { apikey });
- if (!user) {
- throw new CustomError("Couldn't generate API key. Please try again later.");
- }
- return res.status(201).send({ apikey });
- };
- export const resetPasswordRequest: Handler = async (req, res) => {
- const [user] = await query.user.update(
- { email: req.body.email },
- {
- reset_password_token: uuid(),
- reset_password_expires: addMinutes(new Date(), 30).toISOString()
- }
- );
- if (user) {
- await mail.resetPasswordToken(user);
- }
- return res.status(200).send({
- message: "If email address exists, a reset password email has been sent."
- });
- };
- export const resetPassword: Handler = async (req, res, next) => {
- const { resetPasswordToken } = req.params;
- if (resetPasswordToken) {
- const [user] = await query.user.update(
- {
- reset_password_token: resetPasswordToken,
- reset_password_expires: [">", new Date().toISOString()]
- },
- { reset_password_expires: null, reset_password_token: null }
- );
- if (user) {
- const token = utils.signToken(user as UserJoined);
- req.token = token;
- }
- }
- return next();
- };
- export const signupAccess: Handler = (req, res, next) => {
- if (!env.DISALLOW_REGISTRATION) return next();
- return res.status(403).send({ message: "Registration is not allowed." });
- };
- export const changeEmailRequest: Handler = async (req, res) => {
- const { email, password } = req.body;
- const isMatch = await bcrypt.compare(password, req.user.password);
- if (!isMatch) {
- throw new CustomError("Password is wrong.", 400);
- }
- const currentUser = await query.user.find({ email });
- if (currentUser) {
- throw new CustomError("Can't use this email address.", 400);
- }
- const [updatedUser] = await query.user.update(
- { id: req.user.id },
- {
- change_email_address: email,
- change_email_token: uuid(),
- change_email_expires: addMinutes(new Date(), 30).toISOString()
- }
- );
- redis.remove.user(updatedUser);
- if (updatedUser) {
- await mail.changeEmail({ ...updatedUser, email });
- }
- return res.status(200).send({
- message:
- "If email address exists, an email " +
- "with a verification link has been sent."
- });
- };
- export const changeEmail: Handler = async (req, res, next) => {
- const { changeEmailToken } = req.params;
- if (changeEmailToken) {
- const foundUser = await query.user.find({
- change_email_token: changeEmailToken
- });
- if (!foundUser) return next();
- const [user] = await query.user.update(
- {
- change_email_token: changeEmailToken,
- change_email_expires: [">", new Date().toISOString()]
- },
- {
- change_email_token: null,
- change_email_expires: null,
- change_email_address: null,
- email: foundUser.change_email_address
- }
- );
- redis.remove.user(foundUser);
- if (user) {
- const token = utils.signToken(user as UserJoined);
- req.token = token;
- }
- }
- return next();
- };
|