urlController.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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(), 1).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 reqestedId = req.params.id || req.body.id;
  84. const id = reqestedId.replace('+', '');
  85. const domain = host !== config.DEFAULT_DOMAIN && host;
  86. const agent = useragent.parse(req.headers['user-agent']);
  87. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  88. const [os = 'Other'] = osList.filter(filterInOs(agent));
  89. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  90. const location = geoip.lookup(req.realIp);
  91. const country = location && location.country;
  92. const urls = await findUrl({ id, domain });
  93. const isBot =
  94. botList.some(bot => agent.source.toLowerCase().includes(bot)) || agent.family === 'Other';
  95. if (!urls && !urls.length) return next();
  96. const url = urls.find(item => (domain ? item.domain === domain : !item.domain));
  97. const doesRequestInfo = /.*\+$/gi.test(reqestedId);
  98. if (doesRequestInfo && !url.password) {
  99. req.urlTarget = url.target;
  100. req.pageType = 'info';
  101. return next();
  102. }
  103. if (url.password && !req.body.password) {
  104. req.protectedUrl = id;
  105. req.pageType = 'password';
  106. return next();
  107. }
  108. if (url.password) {
  109. const isMatch = await bcrypt.compare(req.body.password, url.password);
  110. if (!isMatch) {
  111. return res.status(401).json({ error: 'Password is not correct' });
  112. }
  113. if (url.user && !isBot) {
  114. await createVisit({
  115. browser,
  116. country: country || 'Unknown',
  117. domain,
  118. id: url.id,
  119. os,
  120. referrer: referrer || 'Direct',
  121. });
  122. }
  123. return res.status(200).json({ target: url.target });
  124. }
  125. if (url.user && !isBot) {
  126. await createVisit({
  127. browser,
  128. country: country || 'Unknown',
  129. domain,
  130. id: url.id,
  131. os,
  132. referrer: referrer || 'Direct',
  133. });
  134. }
  135. return res.redirect(url.target);
  136. };
  137. exports.getUrls = async ({ query, user }, res) => {
  138. const urlsList = await getUrls({ options: query, user });
  139. return res.json(urlsList);
  140. };
  141. exports.setCustomDomain = async ({ body: { customDomain }, user }, res) => {
  142. if (customDomain.length > 40) {
  143. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  144. }
  145. if (customDomain === config.DEFAULT_DOMAIN) {
  146. return res.status(400).json({ error: "You can't use default domain." });
  147. }
  148. const isValidDomain = urlRegex({ exact: true, strict: false }).test(customDomain);
  149. if (!isValidDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  150. const isOwned = await getCustomDomain({ customDomain });
  151. if (isOwned && isOwned.email !== user.email) {
  152. return res
  153. .status(400)
  154. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  155. }
  156. const userCustomDomain = await setCustomDomain({ user, customDomain });
  157. if (userCustomDomain) return res.status(201).json({ customDomain: userCustomDomain.name });
  158. return res.status(400).json({ error: "Couldn't set custom domain." });
  159. };
  160. exports.deleteCustomDomain = async ({ user }, res) => {
  161. const response = await deleteCustomDomain({ user });
  162. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  163. return res.status(400).json({ error: "Couldn't delete custom domain." });
  164. };
  165. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  166. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  167. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  168. const urls = await findUrl({ id, domain: customDomain });
  169. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  170. const response = await deleteUrl({ id, domain: customDomain, user });
  171. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  172. return res.status(400).json({ error: "Couldn't delete short URL." });
  173. };
  174. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  175. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  176. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  177. const stats = await getStats({ id, domain: customDomain, user });
  178. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  179. return res.status(200).json(stats);
  180. };