urlController.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. const urlRegex = require('url-regex');
  2. const URL = require('url');
  3. const dns = require('dns');
  4. const { promisify } = require('util');
  5. const generate = require('nanoid/generate');
  6. const useragent = require('useragent');
  7. const geoip = require('geoip-lite');
  8. const bcrypt = require('bcryptjs');
  9. const subDay = require('date-fns/sub_days');
  10. const {
  11. createShortUrl,
  12. createVisit,
  13. deleteCustomDomain,
  14. deleteUrl,
  15. findUrl,
  16. getCountUrls,
  17. getCustomDomain,
  18. getStats,
  19. getUrls,
  20. setCustomDomain,
  21. urlCountFromDate,
  22. banUrl,
  23. getBannedDomain,
  24. getBannedHost,
  25. } = require('../db/url');
  26. const redis = require('../redis');
  27. const { addProtocol, generateShortUrl } = require('../utils');
  28. const config = require('../config');
  29. const dnsLookup = promisify(dns.lookup);
  30. const generateId = async () => {
  31. const id = generate('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', 6);
  32. const urls = await findUrl({ id });
  33. if (!urls.length) return id;
  34. return generateId();
  35. };
  36. exports.urlShortener = async ({ body, user }, res) => {
  37. // Check if user has passed daily limit
  38. if (user) {
  39. const { count } = await urlCountFromDate({
  40. email: user.email,
  41. date: subDay(new Date(), 1).toJSON(),
  42. });
  43. if (count > config.USER_LIMIT_PER_DAY) {
  44. return res.status(429).json({
  45. error: `You have reached your daily limit (${config.USER_LIMIT_PER_DAY}). Please wait 24h.`,
  46. });
  47. }
  48. }
  49. // if "reuse" is true, try to return
  50. // the existent URL without creating one
  51. if (user && body.reuse) {
  52. const urls = await findUrl({ target: addProtocol(body.target) });
  53. if (urls.length) {
  54. urls.sort((a, b) => a.createdAt > b.createdAt);
  55. const { domain: d, user: u, ...url } = urls[urls.length - 1];
  56. const data = {
  57. ...url,
  58. password: !!url.password,
  59. reuse: true,
  60. shortUrl: generateShortUrl(url.id, user.domain),
  61. };
  62. return res.json(data);
  63. }
  64. }
  65. // Check if custom URL already exists
  66. if (user && body.customurl) {
  67. const urls = await findUrl({ id: body.customurl || '' });
  68. if (urls.length) {
  69. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  70. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  71. if (urlWithNoDomain || urlWithDmoain) {
  72. return res.status(400).json({ error: 'Custom URL is already in use.' });
  73. }
  74. }
  75. }
  76. // If domain or host is banned
  77. const domain = URL.parse(body.target).hostname;
  78. const isDomainBanned = await getBannedDomain(domain);
  79. let isHostBanned;
  80. try {
  81. const dnsRes = await dnsLookup(domain);
  82. isHostBanned = await getBannedHost(dnsRes && dnsRes.address);
  83. } catch (error) {
  84. isHostBanned = null;
  85. }
  86. if (isDomainBanned || isHostBanned) {
  87. return res.status(400).json({ error: 'URL is containing malware/scam.' });
  88. }
  89. // Create new URL
  90. const id = (user && body.customurl) || (await generateId());
  91. const target = addProtocol(body.target);
  92. const url = await createShortUrl({ ...body, id, target, user });
  93. return res.json(url);
  94. };
  95. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  96. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  97. const botList = ['bot', 'dataminr', 'pinterest', 'yahoo', 'facebook', 'crawl'];
  98. const filterInBrowser = agent => item =>
  99. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  100. const filterInOs = agent => item =>
  101. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  102. exports.goToUrl = async (req, res, next) => {
  103. const { host } = req.headers;
  104. const reqestedId = req.params.id || req.body.id;
  105. const id = reqestedId.replace('+', '');
  106. const domain = host !== config.DEFAULT_DOMAIN && host;
  107. const agent = useragent.parse(req.headers['user-agent']);
  108. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  109. const [os = 'Other'] = osList.filter(filterInOs(agent));
  110. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  111. const location = geoip.lookup(req.realIp);
  112. const country = location && location.country;
  113. const isBot =
  114. botList.some(bot => agent.source.toLowerCase().includes(bot)) || agent.family === 'Other';
  115. let url;
  116. const cachedUrl = await redis.get(id + domain || '');
  117. if (cachedUrl) {
  118. url = JSON.parse(cachedUrl);
  119. } else {
  120. const urls = await findUrl({ id, domain });
  121. if (!urls && !urls.length) return next();
  122. url = urls.find(item => (domain ? item.domain === domain : !item.domain));
  123. }
  124. if (!url) return next();
  125. redis.set(id + domain || '', JSON.stringify(url), 'EX', 60 * 60 * 1);
  126. if (url.banned) {
  127. return res.redirect('/banned');
  128. }
  129. const doesRequestInfo = /.*\+$/gi.test(reqestedId);
  130. if (doesRequestInfo && !url.password) {
  131. req.urlTarget = url.target;
  132. req.pageType = 'info';
  133. return next();
  134. }
  135. if (url.password && !req.body.password) {
  136. req.protectedUrl = id;
  137. req.pageType = 'password';
  138. return next();
  139. }
  140. if (url.password) {
  141. const isMatch = await bcrypt.compare(req.body.password, url.password);
  142. if (!isMatch) {
  143. return res.status(401).json({ error: 'Password is not correct' });
  144. }
  145. if (url.user && !isBot) {
  146. createVisit({
  147. browser,
  148. country: country || 'Unknown',
  149. domain,
  150. id: url.id,
  151. os,
  152. referrer: referrer || 'Direct',
  153. });
  154. }
  155. return res.status(200).json({ target: url.target });
  156. }
  157. if (url.user && !isBot) {
  158. createVisit({
  159. browser,
  160. country: country || 'Unknown',
  161. domain,
  162. id: url.id,
  163. os,
  164. referrer: referrer || 'Direct',
  165. });
  166. }
  167. return res.redirect(url.target);
  168. };
  169. exports.getUrls = async ({ query, user }, res) => {
  170. const { countAll } = await getCountUrls({ user });
  171. const urlsList = await getUrls({ options: query, user });
  172. return res.json({ ...urlsList, countAll });
  173. };
  174. exports.setCustomDomain = async ({ body: { customDomain }, user }, res) => {
  175. if (customDomain.length > 40) {
  176. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  177. }
  178. if (customDomain === config.DEFAULT_DOMAIN) {
  179. return res.status(400).json({ error: "You can't use default domain." });
  180. }
  181. const isValidDomain = urlRegex({ exact: true, strict: false }).test(customDomain);
  182. if (!isValidDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  183. const isOwned = await getCustomDomain({ customDomain });
  184. if (isOwned && isOwned.email !== user.email) {
  185. return res
  186. .status(400)
  187. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  188. }
  189. const userCustomDomain = await setCustomDomain({ user, customDomain });
  190. if (userCustomDomain) return res.status(201).json({ customDomain: userCustomDomain.name });
  191. return res.status(400).json({ error: "Couldn't set custom domain." });
  192. };
  193. exports.deleteCustomDomain = async ({ user }, res) => {
  194. const response = await deleteCustomDomain({ user });
  195. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  196. return res.status(400).json({ error: "Couldn't delete custom domain." });
  197. };
  198. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  199. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  200. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  201. const urls = await findUrl({ id, domain: customDomain });
  202. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  203. redis.del(id + customDomain || '');
  204. const response = await deleteUrl({ id, domain: customDomain, user });
  205. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  206. return res.status(400).json({ error: "Couldn't delete short URL." });
  207. };
  208. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  209. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  210. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  211. const stats = await getStats({ id, domain: customDomain, user });
  212. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  213. return res.status(200).json(stats);
  214. };
  215. exports.ban = async ({ body }, res) => {
  216. if (!body.id) return res.status(400).json({ error: 'No id has been provided.' });
  217. const urls = await findUrl({ id: body.id });
  218. const [url] = urls.filter(item => !item.domain);
  219. if (!url) return res.status(400).json({ error: "Couldn't find the URL." });
  220. if (url.banned) return res.status(200).json({ message: 'URL was banned already' });
  221. redis.del(body.id);
  222. const domain = URL.parse(url.target).hostname;
  223. let host;
  224. if (body.host) {
  225. try {
  226. const dnsRes = await dnsLookup(domain);
  227. host = dnsRes && dnsRes.address;
  228. } catch (error) {
  229. host = null;
  230. }
  231. }
  232. await banUrl({
  233. domain: body.domain && domain,
  234. host,
  235. id: body.id,
  236. user: body.user,
  237. });
  238. return res.status(200).json({ message: 'URL has been banned successfully' });
  239. };