urlController.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 { addIPCooldown } = require('../db/user');
  12. const {
  13. createShortUrl,
  14. createVisit,
  15. deleteCustomDomain,
  16. deleteUrl,
  17. findUrl,
  18. getCountUrls,
  19. getCustomDomain,
  20. getStats,
  21. getUrls,
  22. setCustomDomain,
  23. banUrl,
  24. } = require('../db/url');
  25. const {
  26. checkBannedDomain,
  27. checkBannedHost,
  28. cooldownCheck,
  29. malwareCheck,
  30. preservedUrls,
  31. urlCountsCheck,
  32. } = require('./validateBodyController');
  33. const transporter = require('../mail/mail');
  34. const redis = require('../redis');
  35. const { addProtocol, generateShortUrl, getStatsCacheTime } = require('../utils');
  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, realIp, user }, res) => {
  44. try {
  45. const domain = URL.parse(body.target).hostname;
  46. const queries = await Promise.all([
  47. process.env.GOOGLE_SAFE_BROWSING_KEY && cooldownCheck(user),
  48. process.env.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. if (!user && Number(process.env.NON_USER_COOLDOWN)) {
  88. addIPCooldown(realIp);
  89. }
  90. return res.json(url);
  91. } catch (error) {
  92. return res.status(400).json({ error: error.message });
  93. }
  94. };
  95. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  96. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  97. const filterInBrowser = agent => item =>
  98. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  99. const filterInOs = agent => item =>
  100. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  101. exports.goToUrl = async (req, res, next) => {
  102. const { host } = req.headers;
  103. const reqestedId = req.params.id || req.body.id;
  104. const id = reqestedId.replace('+', '');
  105. const domain = host !== process.env.DEFAULT_DOMAIN && host;
  106. const agent = useragent.parse(req.headers['user-agent']);
  107. const [browser = 'Other'] = browsersList.filter(filterInBrowser(agent));
  108. const [os = 'Other'] = osList.filter(filterInOs(agent));
  109. const referrer = req.header('Referer') && URL.parse(req.header('Referer')).hostname;
  110. const location = geoip.lookup(req.realIp);
  111. const country = location && location.country;
  112. const isBot = isbot(req.headers['user-agent']);
  113. let url;
  114. const cachedUrl = await redis.get(id + (domain || ''));
  115. if (cachedUrl) {
  116. url = JSON.parse(cachedUrl);
  117. } else {
  118. const urls = await findUrl({ id, domain });
  119. url =
  120. urls && urls.length && urls.find(item => (domain ? item.domain === domain : !item.domain));
  121. }
  122. if (!url) {
  123. if (host !== process.env.DEFAULT_DOMAIN) {
  124. const { homepage } = await getCustomDomain({ customDomain: domain });
  125. if (!homepage) return next();
  126. return res.redirect(301, homepage);
  127. }
  128. return next();
  129. }
  130. redis.set(id + (domain || ''), JSON.stringify(url), 'EX', 60 * 60 * 1);
  131. if (url.banned) {
  132. return res.redirect('/banned');
  133. }
  134. const doesRequestInfo = /.*\+$/gi.test(reqestedId);
  135. if (doesRequestInfo && !url.password) {
  136. req.urlTarget = url.target;
  137. req.pageType = 'info';
  138. return next();
  139. }
  140. if (url.password && !req.body.password) {
  141. req.protectedUrl = id;
  142. req.pageType = 'password';
  143. return next();
  144. }
  145. if (url.password) {
  146. const isMatch = await bcrypt.compare(req.body.password, url.password);
  147. if (!isMatch) {
  148. return res.status(401).json({ error: 'Password is not correct' });
  149. }
  150. if (url.user && !isBot) {
  151. createVisit({
  152. browser,
  153. country: country || 'Unknown',
  154. domain,
  155. id: url.id,
  156. os,
  157. referrer: referrer || 'Direct',
  158. });
  159. }
  160. return res.status(200).json({ target: url.target });
  161. }
  162. if (url.user && !isBot) {
  163. createVisit({
  164. browser,
  165. country: country || 'Unknown',
  166. domain,
  167. id: url.id,
  168. os,
  169. referrer: referrer || 'Direct',
  170. });
  171. }
  172. if (process.env.GOOGLE_ANALYTICS_UNIVERSAL && !isBot) {
  173. const visitor = ua(process.env.GOOGLE_ANALYTICS_UNIVERSAL);
  174. visitor
  175. .pageview({
  176. dp: `/${id}`,
  177. ua: req.headers['user-agent'],
  178. uip: req.realIp,
  179. aip: 1,
  180. })
  181. .send();
  182. }
  183. return res.redirect(url.target);
  184. };
  185. exports.getUrls = async ({ query, user }, res) => {
  186. const { countAll } = await getCountUrls({ user });
  187. const urlsList = await getUrls({ options: query, user });
  188. const isCountMissing = urlsList.list.some(url => typeof url.count === 'undefined');
  189. const { list } = isCountMissing
  190. ? await getUrls({ options: query, user, setCount: true })
  191. : urlsList;
  192. return res.json({ list, countAll });
  193. };
  194. exports.setCustomDomain = async ({ body, user }, res) => {
  195. const parsed = URL.parse(body.customDomain);
  196. const customDomain = parsed.hostname || parsed.href;
  197. if (!customDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  198. if (customDomain.length > 40) {
  199. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  200. }
  201. if (customDomain === process.env.DEFAULT_DOMAIN) {
  202. return res.status(400).json({ error: "You can't use default domain." });
  203. }
  204. const isValidHomepage =
  205. !body.homepage || urlRegex({ exact: true, strict: false }).test(body.homepage);
  206. if (!isValidHomepage) return res.status(400).json({ error: 'Homepage is not valid.' });
  207. const homepage =
  208. body.homepage &&
  209. (URL.parse(body.homepage).protocol ? body.homepage : `http://${body.homepage}`);
  210. const { email } = await getCustomDomain({ customDomain });
  211. if (email && email !== user.email) {
  212. return res
  213. .status(400)
  214. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  215. }
  216. const userCustomDomain = await setCustomDomain({
  217. user,
  218. customDomain,
  219. homepage,
  220. useHttps: body.useHttps,
  221. });
  222. if (userCustomDomain)
  223. return res.status(201).json({
  224. customDomain: userCustomDomain.name,
  225. homepage: userCustomDomain.homepage,
  226. useHttps: userCustomDomain.useHttps,
  227. });
  228. return res.status(400).json({ error: "Couldn't set custom domain." });
  229. };
  230. exports.deleteCustomDomain = async ({ user }, res) => {
  231. const response = await deleteCustomDomain({ user });
  232. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  233. return res.status(400).json({ error: "Couldn't delete custom domain." });
  234. };
  235. exports.customDomainRedirection = async (req, res, next) => {
  236. const { headers, path } = req;
  237. if (
  238. headers.host !== process.env.DEFAULT_DOMAIN &&
  239. (path === '/' ||
  240. preservedUrls.filter(u => u !== 'url-password').some(item => item === path.replace('/', '')))
  241. ) {
  242. const { homepage } = await getCustomDomain({ customDomain: headers.host });
  243. return res.redirect(301, homepage || `https://${process.env.DEFAULT_DOMAIN + path}`);
  244. }
  245. return next();
  246. };
  247. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  248. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  249. const customDomain = domain !== process.env.DEFAULT_DOMAIN && domain;
  250. const urls = await findUrl({ id, domain: customDomain });
  251. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  252. redis.del(id + (customDomain || ''));
  253. const response = await deleteUrl({ id, domain: customDomain, user });
  254. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  255. return res.status(400).json({ error: "Couldn't delete short URL." });
  256. };
  257. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  258. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  259. const customDomain = domain !== process.env.DEFAULT_DOMAIN && domain;
  260. const redisKey = id + (customDomain || '') + user.email;
  261. const cached = await redis.get(redisKey);
  262. if (cached) return res.status(200).json(JSON.parse(cached));
  263. const urls = await findUrl({ id, domain: customDomain });
  264. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  265. const [url] = urls;
  266. const stats = await getStats({ id, domain: customDomain, user });
  267. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  268. stats.shortUrl = `http${!domain ? 's' : ''}://${
  269. domain ? url.domain : process.env.DEFAULT_DOMAIN
  270. }/${url.id}`;
  271. stats.target = url.target;
  272. const cacheTime = getStatsCacheTime(stats.total);
  273. redis.set(redisKey, JSON.stringify(stats), 'EX', cacheTime);
  274. return res.status(200).json(stats);
  275. };
  276. exports.reportUrl = async ({ body: { url } }, res) => {
  277. if (!url) return res.status(400).json({ error: 'No URL has been provided.' });
  278. const isValidUrl = urlRegex({ exact: true, strict: false }).test(url);
  279. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  280. const mail = await transporter.sendMail({
  281. from: process.env.MAIL_USER,
  282. to: process.env.REPORT_MAIL,
  283. subject: '[REPORT]',
  284. text: url,
  285. html: url,
  286. });
  287. if (mail.accepted.length) {
  288. return res.status(200).json({ message: "Thanks for the report, we'll take actions shortly." });
  289. }
  290. return res.status(400).json({ error: "Couldn't submit the report. Try again later." });
  291. };
  292. exports.ban = async ({ body }, res) => {
  293. if (!body.id) return res.status(400).json({ error: 'No id has been provided.' });
  294. const urls = await findUrl({ id: body.id });
  295. const [url] = urls.filter(item => !item.domain);
  296. if (!url) return res.status(400).json({ error: "Couldn't find the URL." });
  297. if (url.banned) return res.status(200).json({ message: 'URL was banned already' });
  298. redis.del(body.id);
  299. const domain = URL.parse(url.target).hostname;
  300. let host;
  301. if (body.host) {
  302. try {
  303. const dnsRes = await dnsLookup(domain);
  304. host = dnsRes && dnsRes.address;
  305. } catch (error) {
  306. host = null;
  307. }
  308. }
  309. await banUrl({
  310. domain: body.domain && domain,
  311. host,
  312. id: body.id,
  313. user: body.user,
  314. });
  315. return res.status(200).json({ message: 'URL has been banned successfully' });
  316. };