urlController.js 6.7 KB

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