urlController.js 9.5 KB

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