urlController.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. const { promisify } = require('util');
  2. const urlRegex = require('url-regex');
  3. const dns = require('dns');
  4. const URL = require('url');
  5. const generate = require('nanoid/generate');
  6. const useragent = require('useragent');
  7. const geoip = require('geoip-lite');
  8. const bcrypt = require('bcryptjs');
  9. const ua = require('universal-analytics');
  10. const isbot = require('isbot');
  11. const {
  12. createShortUrl,
  13. createVisit,
  14. deleteCustomDomain,
  15. deleteUrl,
  16. findUrl,
  17. getCountUrls,
  18. getCustomDomain,
  19. getStats,
  20. getUrls,
  21. setCustomDomain,
  22. banUrl,
  23. } = require('../db/url');
  24. const {
  25. checkBannedDomain,
  26. checkBannedHost,
  27. cooldownCheck,
  28. malwareCheck,
  29. preservedUrls,
  30. urlCountsCheck,
  31. } = require('./validateBodyController');
  32. const transporter = require('../mail/mail');
  33. const redis = require('../redis');
  34. const { addProtocol, generateShortUrl, getStatsCacheTime } = require('../utils');
  35. const config = require('../config');
  36. const dnsLookup = promisify(dns.lookup);
  37. const generateId = async () => {
  38. const id = generate('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', 6);
  39. const urls = await findUrl({ id });
  40. if (!urls.length) return id;
  41. return generateId();
  42. };
  43. exports.urlShortener = async ({ body, user }, res) => {
  44. try {
  45. const domain = URL.parse(body.target).hostname;
  46. const queries = await Promise.all([
  47. config.GOOGLE_SAFE_BROWSING_KEY && cooldownCheck(user),
  48. config.GOOGLE_SAFE_BROWSING_KEY && malwareCheck(user, body.target),
  49. user && urlCountsCheck(user.email),
  50. user && body.reuse && findUrl({ target: addProtocol(body.target) }),
  51. user && body.customurl && findUrl({ id: body.customurl || '' }),
  52. (!user || !body.customurl) && generateId(),
  53. checkBannedDomain(domain),
  54. checkBannedHost(domain),
  55. ]);
  56. // if "reuse" is true, try to return
  57. // the existent URL without creating one
  58. if (user && body.reuse) {
  59. const urls = queries[3];
  60. if (urls.length) {
  61. urls.sort((a, b) => a.createdAt > b.createdAt);
  62. const { domain: d, user: u, ...url } = urls[urls.length - 1];
  63. const data = {
  64. ...url,
  65. password: !!url.password,
  66. reuse: true,
  67. shortUrl: generateShortUrl(url.id, user.domain, user.useHttps),
  68. };
  69. return res.json(data);
  70. }
  71. }
  72. // Check if custom URL already exists
  73. if (user && body.customurl) {
  74. const urls = queries[4];
  75. if (urls.length) {
  76. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  77. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  78. if (urlWithNoDomain || urlWithDmoain) {
  79. throw new Error('Custom URL is already in use.');
  80. }
  81. }
  82. }
  83. // Create new URL
  84. const id = (user && body.customurl) || queries[5];
  85. const target = addProtocol(body.target);
  86. const url = await createShortUrl({ ...body, id, target, user });
  87. return res.json(url);
  88. } catch (error) {
  89. return res.status(400).json({ error: error.message });
  90. }
  91. };
  92. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  93. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  94. const filterInBrowser = agent => item =>
  95. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  96. const filterInOs = agent => item =>
  97. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  98. exports.goToUrl = async (req, res, next) => {
  99. const { host } = req.headers;
  100. const reqestedId = req.params.id || req.body.id;
  101. const id = reqestedId.replace('+', '');
  102. const domain = host !== config.DEFAULT_DOMAIN && host;
  103. const agent = useragent.parse(req.headers['user-agent']);
  104. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  105. const [os = 'Other'] = osList.filter(filterInOs(agent));
  106. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  107. const location = geoip.lookup(req.realIp);
  108. const country = location && location.country;
  109. const isBot = isbot(req.headers['user-agent']);
  110. let url;
  111. const cachedUrl = await redis.get(id + (domain || ''));
  112. if (cachedUrl) {
  113. url = JSON.parse(cachedUrl);
  114. } else {
  115. const urls = await findUrl({ id, domain });
  116. url =
  117. urls && urls.length && urls.find(item => (domain ? item.domain === domain : !item.domain));
  118. }
  119. if (!url) {
  120. if (host !== config.DEFAULT_DOMAIN) {
  121. const { homepage } = await getCustomDomain({ customDomain: domain });
  122. if (!homepage) return next();
  123. return res.redirect(301, homepage);
  124. }
  125. return next();
  126. }
  127. redis.set(id + (domain || ''), JSON.stringify(url), 'EX', 60 * 60 * 1);
  128. if (url.banned) {
  129. return res.redirect('/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 && !isBot) {
  170. const visitor = ua(config.GOOGLE_ANALYTICS);
  171. visitor
  172. .pageview({
  173. dp: `/${id}`,
  174. ua: req.headers['user-agent'],
  175. uip: req.realIp,
  176. aip: 1,
  177. })
  178. .send();
  179. }
  180. return res.redirect(url.target);
  181. };
  182. exports.getUrls = async ({ query, user }, res) => {
  183. const { countAll } = await getCountUrls({ user });
  184. const urlsList = await getUrls({ options: query, user });
  185. const isCountMissing = urlsList.list.some(url => typeof url.count === 'undefined');
  186. const { list } = isCountMissing
  187. ? await getUrls({ options: query, user, setCount: true })
  188. : urlsList;
  189. return res.json({ list, countAll });
  190. };
  191. exports.setCustomDomain = async ({ body, user }, res) => {
  192. const parsed = URL.parse(body.customDomain);
  193. const customDomain = parsed.hostname || parsed.href;
  194. if (!customDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  195. if (customDomain.length > 40) {
  196. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  197. }
  198. if (customDomain === config.DEFAULT_DOMAIN) {
  199. return res.status(400).json({ error: "You can't use default domain." });
  200. }
  201. const isValidHomepage =
  202. !body.homepage || urlRegex({ exact: true, strict: false }).test(body.homepage);
  203. if (!isValidHomepage) return res.status(400).json({ error: 'Homepage is not valid.' });
  204. const homepage =
  205. body.homepage &&
  206. (URL.parse(body.homepage).protocol ? body.homepage : `http://${body.homepage}`);
  207. const { email } = await getCustomDomain({ customDomain });
  208. if (email && email !== user.email) {
  209. return res
  210. .status(400)
  211. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  212. }
  213. const userCustomDomain = await setCustomDomain({
  214. user,
  215. customDomain,
  216. homepage,
  217. useHttps: body.useHttps,
  218. });
  219. if (userCustomDomain)
  220. return res.status(201).json({
  221. customDomain: userCustomDomain.name,
  222. homepage: userCustomDomain.homepage,
  223. useHttps: userCustomDomain.useHttps,
  224. });
  225. return res.status(400).json({ error: "Couldn't set custom domain." });
  226. };
  227. exports.deleteCustomDomain = async ({ user }, res) => {
  228. const response = await deleteCustomDomain({ user });
  229. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  230. return res.status(400).json({ error: "Couldn't delete custom domain." });
  231. };
  232. exports.customDomainRedirection = async (req, res, next) => {
  233. const { headers, path } = req;
  234. if (
  235. headers.host !== config.DEFAULT_DOMAIN &&
  236. (path === '/' ||
  237. preservedUrls.filter(u => u !== 'url-password').some(item => item === path.replace('/', '')))
  238. ) {
  239. const { homepage } = await getCustomDomain({ customDomain: headers.host });
  240. return res.redirect(301, homepage || `https://${config.DEFAULT_DOMAIN + path}`);
  241. }
  242. return next();
  243. };
  244. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  245. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  246. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  247. const urls = await findUrl({ id, domain: customDomain });
  248. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  249. redis.del(id + (customDomain || ''));
  250. const response = await deleteUrl({ id, domain: customDomain, user });
  251. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  252. return res.status(400).json({ error: "Couldn't delete short URL." });
  253. };
  254. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  255. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  256. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  257. const redisKey = id + (customDomain || '') + user.email;
  258. const cached = await redis.get(redisKey);
  259. if (cached) return res.status(200).json(JSON.parse(cached));
  260. const urls = await findUrl({ id, domain: customDomain });
  261. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  262. const [url] = urls;
  263. const stats = await getStats({ id, domain: customDomain, user });
  264. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  265. stats.shortUrl = `http${!domain ? 's' : ''}://${domain ? url.domain : config.DEFAULT_DOMAIN}/${
  266. url.id
  267. }`;
  268. stats.target = url.target;
  269. const cacheTime = getStatsCacheTime(stats.total);
  270. redis.set(redisKey, JSON.stringify(stats), 'EX', cacheTime);
  271. return res.status(200).json(stats);
  272. };
  273. exports.reportUrl = async ({ body: { url } }, res) => {
  274. if (!url) return res.status(400).json({ error: 'No URL has been provided.' });
  275. const isValidUrl = urlRegex({ exact: true, strict: false }).test(url);
  276. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  277. const mail = await transporter.sendMail({
  278. from: config.MAIL_USER,
  279. to: config.REPORT_MAIL,
  280. subject: '[REPORT]',
  281. text: url,
  282. html: url,
  283. });
  284. if (mail.accepted.length) {
  285. return res.status(200).json({ message: "Thanks for the report, we'll take actions shortly." });
  286. }
  287. return res.status(400).json({ error: "Couldn't submit the report. Try again later." });
  288. };
  289. exports.ban = async ({ body }, res) => {
  290. if (!body.id) return res.status(400).json({ error: 'No id has been provided.' });
  291. const urls = await findUrl({ id: body.id });
  292. const [url] = urls.filter(item => !item.domain);
  293. if (!url) return res.status(400).json({ error: "Couldn't find the URL." });
  294. if (url.banned) return res.status(200).json({ message: 'URL was banned already' });
  295. redis.del(body.id);
  296. const domain = URL.parse(url.target).hostname;
  297. let host;
  298. if (body.host) {
  299. try {
  300. const dnsRes = await dnsLookup(domain);
  301. host = dnsRes && dnsRes.address;
  302. } catch (error) {
  303. host = null;
  304. }
  305. }
  306. await banUrl({
  307. domain: body.domain && domain,
  308. host,
  309. id: body.id,
  310. user: body.user,
  311. });
  312. return res.status(200).json({ message: 'URL has been banned successfully' });
  313. };