urlController.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 axios = require('axios');
  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 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, 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. if (user && body.customurl) {
  47. if (!/^[a-zA-Z1-9-_]+$/g.test(body.customurl.trim())) {
  48. return res.status(400).json({ error: 'Custom URL is not valid.' });
  49. }
  50. if (preservedUrls.some(url => url === body.customurl)) {
  51. return res.status(400).json({ error: "You can't use this custom URL name." });
  52. }
  53. if (body.customurl.length > 64) {
  54. return res.status(400).json({ error: 'Maximum custom URL length is 64.' });
  55. }
  56. const urls = await findUrl({ id: body.customurl || '' });
  57. if (urls.length) {
  58. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  59. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  60. if (urlWithNoDomain || urlWithDmoain) {
  61. return res.status(400).json({ error: 'Custom URL is already in use.' });
  62. }
  63. }
  64. }
  65. const isMalware = await axios.post(
  66. `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${
  67. config.GOOGLE_SAFE_BROWSING_KEY
  68. }`,
  69. {
  70. client: {
  71. clientId: config.DEFAULT_DOMAIN.toLowerCase().replace('.', ''),
  72. clientVersion: '1.0.0',
  73. },
  74. threatInfo: {
  75. threatTypes: ['MALWARE', 'SOCIAL_ENGINEERING'],
  76. platformTypes: ['WINDOWS'],
  77. threatEntryTypes: ['URL'],
  78. threatEntries: [{ url: body.target }],
  79. },
  80. }
  81. );
  82. if (isMalware.data && isMalware.data.matches) {
  83. return res.status(400).json({ error: 'Malware detected!' });
  84. }
  85. const url = await createShortUrl({ ...body, target, user });
  86. return res.json(url);
  87. };
  88. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  89. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  90. const filterInBrowser = agent => item =>
  91. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  92. const filterInOs = agent => item =>
  93. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  94. exports.goToUrl = async (req, res, next) => {
  95. const { host } = req.headers;
  96. const id = req.params.id || req.body.id;
  97. const domain = host !== config.DEFAULT_DOMAIN && host;
  98. const agent = useragent.parse(req.headers['user-agent']);
  99. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  100. const [os = 'Other'] = osList.filter(filterInOs(agent));
  101. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  102. const location = geoip.lookup(req.realIp);
  103. const country = location && location.country;
  104. const urls = await findUrl({ id, domain });
  105. if (!urls && !urls.length) return next();
  106. const [url] = urls;
  107. if (url.password && !req.body.password) {
  108. req.protectedUrl = id;
  109. return next();
  110. }
  111. if (url.password) {
  112. const isMatch = await bcrypt.compare(req.body.password, url.password);
  113. if (!isMatch) {
  114. return res.status(401).json({ error: 'Password is not correct' });
  115. }
  116. if (url.user) {
  117. await createVisit({
  118. browser,
  119. country: country || 'Unknown',
  120. domain,
  121. id: url.id,
  122. os,
  123. referrer: referrer || 'Direct',
  124. });
  125. }
  126. return res.status(200).json({ target: url.target });
  127. }
  128. if (url.user) {
  129. await createVisit({
  130. browser,
  131. country: country || 'Unknown',
  132. domain,
  133. id: url.id,
  134. os,
  135. referrer: referrer || 'Direct',
  136. });
  137. }
  138. return res.redirect(url.target);
  139. };
  140. exports.getUrls = async ({ body, user }, res) => {
  141. const urlsList = await getUrls({ options: body, user });
  142. return res.json(urlsList);
  143. };
  144. exports.setCustomDomain = async ({ body: { customDomain }, user }, res) => {
  145. if (customDomain.length > 40) {
  146. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  147. }
  148. if (customDomain === config.DEFAULT_DOMAIN) {
  149. return res.status(400).json({ error: "You can't use default domain." });
  150. }
  151. const isValidDomain = urlRegex({ exact: true, strict: false }).test(customDomain);
  152. if (!isValidDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  153. const isOwned = await getCustomDomain({ customDomain });
  154. if (isOwned && isOwned.email !== user.email) {
  155. return res
  156. .status(400)
  157. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  158. }
  159. const userCustomDomain = await setCustomDomain({ user, customDomain });
  160. if (userCustomDomain) return res.status(201).json({ customDomain: userCustomDomain.name });
  161. return res.status(400).json({ error: "Couldn't set custom domain." });
  162. };
  163. exports.deleteCustomDomain = async ({ user }, res) => {
  164. const response = await deleteCustomDomain({ user });
  165. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  166. return res.status(400).json({ error: "Couldn't delete custom domain." });
  167. };
  168. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  169. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  170. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  171. const urls = await findUrl({ id, domain: customDomain });
  172. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  173. const response = await deleteUrl({ id, domain: customDomain, user });
  174. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  175. return res.status(400).json({ error: "Couldn't delete short URL." });
  176. };
  177. exports.getStats = async ({ body: { id, domain }, user }, res) => {
  178. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  179. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  180. const stats = await getStats({ id, domain: customDomain, user });
  181. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  182. return res.status(200).json(stats);
  183. };