urlController.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. const urlRegex = require('url-regex');
  2. const URL = require('url');
  3. const useragent = require('useragent');
  4. const geoip = require('geoip-lite');
  5. const bcrypt = require('bcryptjs');
  6. const {
  7. createShortUrl,
  8. createVisit,
  9. findUrl,
  10. getStats,
  11. getUrls,
  12. getUrlsWithIp,
  13. getCustomDomain,
  14. setCustomDomain,
  15. deleteCustomDomain,
  16. deleteUrl,
  17. } = require('../db/url');
  18. const config = require('../config');
  19. const preservedUrls = [
  20. 'login',
  21. 'logout',
  22. 'signup',
  23. 'reset-password',
  24. 'resetpassword',
  25. 'url-password',
  26. 'settings',
  27. 'stats',
  28. 'verify',
  29. 'api',
  30. '404',
  31. 'static',
  32. 'images',
  33. ];
  34. exports.preservedUrls = preservedUrls;
  35. exports.urlShortener = async ({ body, ip, user }, res) => {
  36. if (!body.target) return res.status(400).json({ error: 'No target has been provided.' });
  37. if (body.target.length > 1024) {
  38. return res.status(400).json({ error: 'Maximum URL length is 1024.' });
  39. }
  40. const isValidUrl = urlRegex({ exact: true, strict: false }).test(body.target);
  41. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  42. const target = URL.parse(body.target).protocol ? body.target : `http://${body.target}`;
  43. if (body.password && body.password.length > 64) {
  44. return res.status(400).json({ error: 'Maximum password length is 64.' });
  45. }
  46. // const urlsWithIp = await getUrlsWithIp({ ip });
  47. // if (urlsWithIp && urlsWithIp.length > 200) {
  48. // return res
  49. // .status(400)
  50. // .json({ error: 'Too much requests! You can request again after one day.' });
  51. // }
  52. if (user && body.customurl) {
  53. if (!/^[a-zA-Z1-9-_]+$/g.test(body.customurl.trim())) {
  54. return res.status(400).json({ error: 'Custom URL is not valid.' });
  55. }
  56. if (preservedUrls.some(url => url === body.customurl)) {
  57. return res.status(400).json({ error: "You can't use this custom URL name." });
  58. }
  59. if (body.customurl.length > 64) {
  60. return res.status(400).json({ error: 'Maximum custom URL length is 64.' });
  61. }
  62. const urls = await findUrl({ id: body.customurl || '' });
  63. if (urls.length) {
  64. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  65. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  66. if (urlWithNoDomain || urlWithDmoain) {
  67. return res.status(400).json({ error: 'Custom URL is already in use.' });
  68. }
  69. }
  70. }
  71. const url = await createShortUrl({ ...body, ip, 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 filterInBrowser = agent => item =>
  77. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  78. const filterInOs = agent => item =>
  79. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  80. exports.goToUrl = async (req, res, next) => {
  81. const { host } = req.headers;
  82. const id = req.params.id || req.body.id;
  83. const domain = host !== config.DEFAULT_DOMAIN && host;
  84. const agent = useragent.parse(req.headers['user-agent']);
  85. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  86. const [os = 'Other'] = osList.filter(filterInOs(agent));
  87. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  88. const location = geoip.lookup(req.realIp);
  89. const country = location && location.country;
  90. const urls = await findUrl({ id, domain });
  91. if (!urls && !urls.length) return next();
  92. const [url] = urls;
  93. if (url.password && !req.body.password) {
  94. req.protectedUrl = id;
  95. return next();
  96. }
  97. if (url.password) {
  98. const isMatch = await bcrypt.compare(req.body.password, url.password);
  99. if (!isMatch) {
  100. return res.status(401).json({ error: 'Password is not correct' });
  101. }
  102. if (url.user) {
  103. await createVisit({
  104. browser,
  105. country: country || 'Unknown',
  106. domain,
  107. id: url.id,
  108. os,
  109. referrer: referrer || 'Direct',
  110. });
  111. }
  112. return res.status(200).json({ target: url.target });
  113. }
  114. if (url.user) {
  115. await createVisit({
  116. browser,
  117. country: country || 'Unknown',
  118. domain,
  119. id: url.id,
  120. os,
  121. referrer: referrer || 'Direct',
  122. });
  123. }
  124. return res.redirect(url.target);
  125. };
  126. exports.getUrls = async ({ body, user }, res) => {
  127. const urlsList = await getUrls({ options: body, user });
  128. return res.json(urlsList);
  129. };
  130. exports.setCustomDomain = async ({ body: { customDomain }, user }, res) => {
  131. if (customDomain.length > 40) {
  132. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  133. }
  134. if (customDomain === config.DEFAULT_DOMAIN) {
  135. return res.status(400).json({ error: "You can't use default domain." });
  136. }
  137. const isValidDomain = urlRegex({ exact: true, strict: false }).test(customDomain);
  138. if (!isValidDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  139. const isOwned = await getCustomDomain({ customDomain });
  140. if (isOwned && isOwned.email !== user.email) {
  141. return res
  142. .status(400)
  143. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  144. }
  145. const userCustomDomain = await setCustomDomain({ user, customDomain });
  146. if (userCustomDomain) return res.status(201).json({ customDomain: userCustomDomain.name });
  147. return res.status(400).json({ error: "Couldn't set custom domain." });
  148. };
  149. exports.deleteCustomDomain = async ({ user }, res) => {
  150. const response = await deleteCustomDomain({ user });
  151. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  152. return res.status(400).json({ error: "Couldn't delete custom domain." });
  153. };
  154. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  155. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  156. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  157. const urls = await findUrl({ id, domain: customDomain });
  158. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  159. const response = await deleteUrl({ id, domain: customDomain, user });
  160. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  161. return res.status(400).json({ error: "Couldn't delete short URL." });
  162. };
  163. exports.getStats = async ({ body: { id, domain }, user }, res) => {
  164. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  165. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  166. const stats = await getStats({ id, domain: customDomain, user });
  167. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  168. return res.status(200).json(stats);
  169. };