urlController.js 12 KB

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