urlController.js 9.8 KB

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