urlController.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. const urlRegex = require('url-regex');
  2. const URL = require('url');
  3. const generate = require('nanoid/generate');
  4. const useragent = require('useragent');
  5. const geoip = require('geoip-lite');
  6. const bcrypt = require('bcryptjs');
  7. const {
  8. createShortUrl,
  9. createVisit,
  10. findUrl,
  11. getStats,
  12. getUrls,
  13. getCustomDomain,
  14. setCustomDomain,
  15. deleteCustomDomain,
  16. deleteUrl,
  17. } = require('../db/url');
  18. const { addProtocol, generateShortUrl } = require('../utils');
  19. const config = require('../config');
  20. const generateId = async () => {
  21. const id = generate('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', 6);
  22. const urls = await findUrl({ id });
  23. if (!urls.length) return id;
  24. return generateId();
  25. };
  26. exports.urlShortener = async ({ body, user }, res) => {
  27. // if "reuse" is true, try to return
  28. // the existent URL without creating one
  29. if (user && body.reuse) {
  30. const urls = await findUrl({ target: addProtocol(body.target) });
  31. if (urls.length) {
  32. urls.sort((a, b) => a.createdAt > b.createdAt);
  33. const { domain: d, user: u, ...url } = urls[urls.length - 1];
  34. const data = {
  35. ...url,
  36. password: !!url.password,
  37. reuse: true,
  38. shortUrl: generateShortUrl(url.id, user.domain),
  39. };
  40. return res.json(data);
  41. }
  42. }
  43. // Check if custom URL already exists
  44. if (user && body.customurl) {
  45. const urls = await findUrl({ id: body.customurl || '' });
  46. if (urls.length) {
  47. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  48. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  49. if (urlWithNoDomain || urlWithDmoain) {
  50. return res.status(400).json({ error: 'Custom URL is already in use.' });
  51. }
  52. }
  53. }
  54. // Create new URL
  55. const id = (user && body.customurl) || (await generateId());
  56. const target = addProtocol(body.target);
  57. const url = await createShortUrl({ ...body, id, target, user });
  58. return res.json(url);
  59. };
  60. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  61. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  62. const botList = ['bot', 'dataminr', 'pinterest', 'yahoo', 'facebook', 'crawl'];
  63. const filterInBrowser = agent => item =>
  64. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  65. const filterInOs = agent => item =>
  66. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  67. exports.goToUrl = async (req, res, next) => {
  68. const { host } = req.headers;
  69. const id = req.params.id || req.body.id;
  70. const domain = host !== config.DEFAULT_DOMAIN && host;
  71. const agent = useragent.parse(req.headers['user-agent']);
  72. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  73. const [os = 'Other'] = osList.filter(filterInOs(agent));
  74. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  75. const location = geoip.lookup(req.realIp);
  76. const country = location && location.country;
  77. const urls = await findUrl({ id, domain });
  78. const isBot =
  79. botList.some(bot => agent.source.toLowerCase().includes(bot)) || agent.family === 'Other';
  80. if (!urls && !urls.length) return next();
  81. const [url] = urls;
  82. if (url.password && !req.body.password) {
  83. req.protectedUrl = id;
  84. return next();
  85. }
  86. if (url.password) {
  87. const isMatch = await bcrypt.compare(req.body.password, url.password);
  88. if (!isMatch) {
  89. return res.status(401).json({ error: 'Password is not correct' });
  90. }
  91. if (url.user && !isBot) {
  92. await createVisit({
  93. browser,
  94. country: country || 'Unknown',
  95. domain,
  96. id: url.id,
  97. os,
  98. referrer: referrer || 'Direct',
  99. });
  100. }
  101. return res.status(200).json({ target: url.target });
  102. }
  103. if (url.user && !isBot) {
  104. await createVisit({
  105. browser,
  106. country: country || 'Unknown',
  107. domain,
  108. id: url.id,
  109. os,
  110. referrer: referrer || 'Direct',
  111. });
  112. }
  113. return res.redirect(url.target);
  114. };
  115. exports.getUrls = async ({ query, user }, res) => {
  116. const urlsList = await getUrls({ options: query, user });
  117. return res.json(urlsList);
  118. };
  119. exports.setCustomDomain = async ({ body: { customDomain }, user }, res) => {
  120. if (customDomain.length > 40) {
  121. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  122. }
  123. if (customDomain === config.DEFAULT_DOMAIN) {
  124. return res.status(400).json({ error: "You can't use default domain." });
  125. }
  126. const isValidDomain = urlRegex({ exact: true, strict: false }).test(customDomain);
  127. if (!isValidDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  128. const isOwned = await getCustomDomain({ customDomain });
  129. if (isOwned && isOwned.email !== user.email) {
  130. return res
  131. .status(400)
  132. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  133. }
  134. const userCustomDomain = await setCustomDomain({ user, customDomain });
  135. if (userCustomDomain) return res.status(201).json({ customDomain: userCustomDomain.name });
  136. return res.status(400).json({ error: "Couldn't set custom domain." });
  137. };
  138. exports.deleteCustomDomain = async ({ user }, res) => {
  139. const response = await deleteCustomDomain({ user });
  140. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  141. return res.status(400).json({ error: "Couldn't delete custom domain." });
  142. };
  143. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  144. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  145. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  146. const urls = await findUrl({ id, domain: customDomain });
  147. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  148. const response = await deleteUrl({ id, domain: customDomain, user });
  149. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  150. return res.status(400).json({ error: "Couldn't delete short URL." });
  151. };
  152. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  153. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  154. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  155. const stats = await getStats({ id, domain: customDomain, user });
  156. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  157. return res.status(200).json(stats);
  158. };