urlController.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. const urlRegex = require('url-regex');
  2. const URL = require('url');
  3. const dns = require('dns');
  4. const { promisify } = require('util');
  5. const generate = require('nanoid/generate');
  6. const useragent = require('useragent');
  7. const geoip = require('geoip-lite');
  8. const bcrypt = require('bcryptjs');
  9. const subDay = require('date-fns/sub_days');
  10. const ua = require('universal-analytics');
  11. const isbot = require('isbot');
  12. const {
  13. createShortUrl,
  14. createVisit,
  15. deleteCustomDomain,
  16. deleteUrl,
  17. findUrl,
  18. getCountUrls,
  19. getCustomDomain,
  20. getStats,
  21. getUrls,
  22. setCustomDomain,
  23. urlCountFromDate,
  24. banUrl,
  25. getBannedDomain,
  26. getBannedHost,
  27. } = require('../db/url');
  28. const { preservedUrls } = require('./validateBodyController');
  29. const transporter = require('../mail/mail');
  30. const redis = require('../redis');
  31. const { addProtocol, generateShortUrl, getStatsCacheTime } = require('../utils');
  32. const config = require('../config');
  33. const dnsLookup = promisify(dns.lookup);
  34. const generateId = async () => {
  35. const id = generate('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', 6);
  36. const urls = await findUrl({ id });
  37. if (!urls.length) return id;
  38. return generateId();
  39. };
  40. exports.urlShortener = async ({ body, user }, res) => {
  41. // Check if user has passed daily limit
  42. if (user) {
  43. const { count } = await urlCountFromDate({
  44. email: user.email,
  45. date: subDay(new Date(), 1).toJSON(),
  46. });
  47. if (count > config.USER_LIMIT_PER_DAY) {
  48. return res.status(429).json({
  49. error: `You have reached your daily limit (${config.USER_LIMIT_PER_DAY}). Please wait 24h.`,
  50. });
  51. }
  52. }
  53. // if "reuse" is true, try to return
  54. // the existent URL without creating one
  55. if (user && body.reuse) {
  56. const urls = await findUrl({ target: addProtocol(body.target) });
  57. if (urls.length) {
  58. urls.sort((a, b) => a.createdAt > b.createdAt);
  59. const { domain: d, user: u, ...url } = urls[urls.length - 1];
  60. const data = {
  61. ...url,
  62. password: !!url.password,
  63. reuse: true,
  64. shortUrl: generateShortUrl(url.id, user.domain),
  65. };
  66. return res.json(data);
  67. }
  68. }
  69. // Check if custom URL already exists
  70. if (user && body.customurl) {
  71. const urls = await findUrl({ id: body.customurl || '' });
  72. if (urls.length) {
  73. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  74. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  75. if (urlWithNoDomain || urlWithDmoain) {
  76. return res.status(400).json({ error: 'Custom URL is already in use.' });
  77. }
  78. }
  79. }
  80. // If domain or host is banned
  81. const domain = URL.parse(body.target).hostname;
  82. const isDomainBanned = await getBannedDomain(domain);
  83. let isHostBanned;
  84. try {
  85. const dnsRes = await dnsLookup(domain);
  86. isHostBanned = await getBannedHost(dnsRes && dnsRes.address);
  87. } catch (error) {
  88. isHostBanned = null;
  89. }
  90. if (isDomainBanned || isHostBanned) {
  91. return res.status(400).json({ error: 'URL is containing malware/scam.' });
  92. }
  93. // Create new URL
  94. const id = (user && body.customurl) || (await generateId());
  95. const target = addProtocol(body.target);
  96. const url = await createShortUrl({ ...body, id, target, user });
  97. return res.json(url);
  98. };
  99. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  100. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  101. const filterInBrowser = agent => item =>
  102. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  103. const filterInOs = agent => item =>
  104. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  105. exports.goToUrl = async (req, res, next) => {
  106. const { host } = req.headers;
  107. const reqestedId = req.params.id || req.body.id;
  108. const id = reqestedId.replace('+', '');
  109. const domain = host !== config.DEFAULT_DOMAIN && host;
  110. const agent = useragent.parse(req.headers['user-agent']);
  111. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  112. const [os = 'Other'] = osList.filter(filterInOs(agent));
  113. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  114. const location = geoip.lookup(req.realIp);
  115. const country = location && location.country;
  116. const isBot = isbot(req.headers['user-agent']);
  117. let url;
  118. const cachedUrl = await redis.get(id + (domain || ''));
  119. if (cachedUrl) {
  120. url = JSON.parse(cachedUrl);
  121. } else {
  122. const urls = await findUrl({ id, domain });
  123. if (!urls && !urls.length) return next();
  124. url = urls.find(item => (domain ? item.domain === domain : !item.domain));
  125. }
  126. if (!url) return next();
  127. redis.set(id + (domain || ''), JSON.stringify(url), 'EX', 60 * 60 * 1);
  128. if (url.banned) {
  129. return res.redirect('/banned');
  130. }
  131. const doesRequestInfo = /.*\+$/gi.test(reqestedId);
  132. if (doesRequestInfo && !url.password) {
  133. req.urlTarget = url.target;
  134. req.pageType = 'info';
  135. return next();
  136. }
  137. if (url.password && !req.body.password) {
  138. req.protectedUrl = id;
  139. req.pageType = 'password';
  140. return next();
  141. }
  142. if (url.password) {
  143. const isMatch = await bcrypt.compare(req.body.password, url.password);
  144. if (!isMatch) {
  145. return res.status(401).json({ error: 'Password is not correct' });
  146. }
  147. if (url.user && !isBot) {
  148. createVisit({
  149. browser,
  150. country: country || 'Unknown',
  151. domain,
  152. id: url.id,
  153. os,
  154. referrer: referrer || 'Direct',
  155. });
  156. }
  157. return res.status(200).json({ target: url.target });
  158. }
  159. if (url.user && !isBot) {
  160. createVisit({
  161. browser,
  162. country: country || 'Unknown',
  163. domain,
  164. id: url.id,
  165. os,
  166. referrer: referrer || 'Direct',
  167. });
  168. }
  169. if (config.GOOGLE_ANALYTICS && !isBot) {
  170. const visitor = ua(config.GOOGLE_ANALYTICS);
  171. visitor
  172. .pageview({
  173. dp: `/${id}`,
  174. ua: req.headers['user-agent'],
  175. uip: req.realIp,
  176. aip: 1,
  177. })
  178. .send();
  179. }
  180. return res.redirect(url.target);
  181. };
  182. exports.getUrls = async ({ query, user }, res) => {
  183. const { countAll } = await getCountUrls({ user });
  184. const urlsList = await getUrls({ options: query, user });
  185. const isCountMissing = urlsList.list.some(url => typeof url.count === 'undefined');
  186. const { list } = isCountMissing
  187. ? await getUrls({ options: query, user, setCount: true })
  188. : urlsList;
  189. return res.json({ list, countAll });
  190. };
  191. exports.setCustomDomain = async ({ body, user }, res) => {
  192. const parsed = URL.parse(body.customDomain);
  193. const customDomain = parsed.hostname || parsed.href;
  194. if (!customDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  195. if (customDomain.length > 40) {
  196. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  197. }
  198. if (customDomain === config.DEFAULT_DOMAIN) {
  199. return res.status(400).json({ error: "You can't use default domain." });
  200. }
  201. const isValidHomepage =
  202. !body.homepage || urlRegex({ exact: true, strict: false }).test(body.homepage);
  203. if (!isValidHomepage) return res.status(400).json({ error: 'Homepage is not valid.' });
  204. const homepage =
  205. body.homepage &&
  206. (URL.parse(body.homepage).protocol ? body.homepage : `http://${body.homepage}`);
  207. const { email } = await getCustomDomain({ customDomain });
  208. if (email !== user.email) {
  209. return res
  210. .status(400)
  211. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  212. }
  213. const userCustomDomain = await setCustomDomain({ user, customDomain, homepage });
  214. if (userCustomDomain)
  215. return res
  216. .status(201)
  217. .json({ customDomain: userCustomDomain.name, homepage: userCustomDomain.homepage });
  218. return res.status(400).json({ error: "Couldn't set custom domain." });
  219. };
  220. exports.deleteCustomDomain = async ({ user }, res) => {
  221. const response = await deleteCustomDomain({ user });
  222. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  223. return res.status(400).json({ error: "Couldn't delete custom domain." });
  224. };
  225. exports.customDomainRedirection = async (req, res, next) => {
  226. const { headers, path } = req;
  227. if (
  228. headers.host !== config.DEFAULT_DOMAIN &&
  229. (path === '/' ||
  230. preservedUrls.filter(u => u !== 'url-password').some(item => item === path.replace('/', '')))
  231. ) {
  232. const { homepage } = await getCustomDomain({ customDomain: headers.host });
  233. return res.redirect(301, homepage || `http://${config.DEFAULT_DOMAIN + path}`);
  234. }
  235. return next();
  236. };
  237. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  238. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  239. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  240. const urls = await findUrl({ id, domain: customDomain });
  241. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  242. redis.del(id + (customDomain || ''));
  243. const response = await deleteUrl({ id, domain: customDomain, user });
  244. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  245. return res.status(400).json({ error: "Couldn't delete short URL." });
  246. };
  247. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  248. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  249. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  250. const redisKey = id + (customDomain || '') + user.email;
  251. const cached = await redis.get(redisKey);
  252. if (cached) return res.status(200).json(JSON.parse(cached));
  253. const stats = await getStats({ id, domain: customDomain, user });
  254. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  255. const cacheTime = getStatsCacheTime(stats.total);
  256. redis.set(redisKey, JSON.stringify(stats), 'EX', cacheTime);
  257. return res.status(200).json(stats);
  258. };
  259. exports.reportUrl = async ({ body: { url } }, res) => {
  260. if (!url) return res.status(400).json({ error: 'No URL has been provided.' });
  261. const isValidUrl = urlRegex({ exact: true, strict: false }).test(url);
  262. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  263. const mail = await transporter.sendMail({
  264. from: config.MAIL_USER,
  265. to: config.REPORT_MAIL,
  266. subject: '[REPORT]',
  267. text: url,
  268. html: url,
  269. });
  270. if (mail.accepted.length) {
  271. return res.status(200).json({ message: "Thanks for the report, we'll take actions shortly." });
  272. }
  273. return res.status(400).json({ error: "Couldn't submit the report. Try again later." });
  274. };
  275. exports.ban = async ({ body }, res) => {
  276. if (!body.id) return res.status(400).json({ error: 'No id has been provided.' });
  277. const urls = await findUrl({ id: body.id });
  278. const [url] = urls.filter(item => !item.domain);
  279. if (!url) return res.status(400).json({ error: "Couldn't find the URL." });
  280. if (url.banned) return res.status(200).json({ message: 'URL was banned already' });
  281. redis.del(body.id);
  282. const domain = URL.parse(url.target).hostname;
  283. let host;
  284. if (body.host) {
  285. try {
  286. const dnsRes = await dnsLookup(domain);
  287. host = dnsRes && dnsRes.address;
  288. } catch (error) {
  289. host = null;
  290. }
  291. }
  292. await banUrl({
  293. domain: body.domain && domain,
  294. host,
  295. id: body.id,
  296. user: body.user,
  297. });
  298. return res.status(200).json({ message: 'URL has been banned successfully' });
  299. };