urlController.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 ua = require('universal-analytics');
  11. const isbot = require('isbot');
  12. const {
  13. createShortUrl,
  14. createVisit,
  15. deleteCustomDomain,
  16. deleteUrl,
  17. findUrl,
  18. getCountUrls,
  19. getCustomDomain,
  20. getStats,
  21. getUrls,
  22. setCustomDomain,
  23. urlCountFromDate,
  24. banUrl,
  25. getBannedDomain,
  26. getBannedHost,
  27. } = require('../db/url');
  28. const transporter = require('../mail/mail');
  29. const redis = require('../redis');
  30. const { addProtocol, generateShortUrl } = require('../utils');
  31. const config = require('../config');
  32. const dnsLookup = promisify(dns.lookup);
  33. const generateId = async () => {
  34. const id = generate('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', 6);
  35. const urls = await findUrl({ id });
  36. if (!urls.length) return id;
  37. return generateId();
  38. };
  39. exports.urlShortener = async ({ body, user }, res) => {
  40. // Check if user has passed daily limit
  41. if (user) {
  42. const { count } = await urlCountFromDate({
  43. email: user.email,
  44. date: subDay(new Date(), 1).toJSON(),
  45. });
  46. if (count > config.USER_LIMIT_PER_DAY) {
  47. return res.status(429).json({
  48. error: `You have reached your daily limit (${config.USER_LIMIT_PER_DAY}). Please wait 24h.`,
  49. });
  50. }
  51. }
  52. // if "reuse" is true, try to return
  53. // the existent URL without creating one
  54. if (user && body.reuse) {
  55. const urls = await findUrl({ target: addProtocol(body.target) });
  56. if (urls.length) {
  57. urls.sort((a, b) => a.createdAt > b.createdAt);
  58. const { domain: d, user: u, ...url } = urls[urls.length - 1];
  59. const data = {
  60. ...url,
  61. password: !!url.password,
  62. reuse: true,
  63. shortUrl: generateShortUrl(url.id, user.domain),
  64. };
  65. return res.json(data);
  66. }
  67. }
  68. // Check if custom URL already exists
  69. if (user && body.customurl) {
  70. const urls = await findUrl({ id: body.customurl || '' });
  71. if (urls.length) {
  72. const urlWithNoDomain = !user.domain && urls.some(url => !url.domain);
  73. const urlWithDmoain = user.domain && urls.some(url => url.domain === user.domain);
  74. if (urlWithNoDomain || urlWithDmoain) {
  75. return res.status(400).json({ error: 'Custom URL is already in use.' });
  76. }
  77. }
  78. }
  79. // If domain or host is banned
  80. const domain = URL.parse(body.target).hostname;
  81. const isDomainBanned = await getBannedDomain(domain);
  82. let isHostBanned;
  83. try {
  84. const dnsRes = await dnsLookup(domain);
  85. isHostBanned = await getBannedHost(dnsRes && dnsRes.address);
  86. } catch (error) {
  87. isHostBanned = null;
  88. }
  89. if (isDomainBanned || isHostBanned) {
  90. return res.status(400).json({ error: 'URL is containing malware/scam.' });
  91. }
  92. // Create new URL
  93. const id = (user && body.customurl) || (await generateId());
  94. const target = addProtocol(body.target);
  95. const url = await createShortUrl({ ...body, id, target, user });
  96. return res.json(url);
  97. };
  98. const browsersList = ['IE', 'Firefox', 'Chrome', 'Opera', 'Safari', 'Edge'];
  99. const osList = ['Windows', 'Mac Os X', 'Linux', 'Chrome OS', 'Android', 'iOS'];
  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 = isbot(req.headers['user-agent']);
  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('/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 (config.GOOGLE_ANALYTICS && !isBot) {
  169. const visitor = ua(config.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: { customDomain }, user }, res) => {
  191. if (customDomain.length > 40) {
  192. return res.status(400).json({ error: 'Maximum custom domain length is 40.' });
  193. }
  194. if (customDomain === config.DEFAULT_DOMAIN) {
  195. return res.status(400).json({ error: "You can't use default domain." });
  196. }
  197. const isValidDomain = urlRegex({ exact: true, strict: false }).test(customDomain);
  198. if (!isValidDomain) return res.status(400).json({ error: 'Domain is not valid.' });
  199. const isOwned = await getCustomDomain({ customDomain });
  200. if (isOwned && isOwned.email !== user.email) {
  201. return res
  202. .status(400)
  203. .json({ error: 'Domain is already taken. Contact us for multiple users.' });
  204. }
  205. const userCustomDomain = await setCustomDomain({ user, customDomain });
  206. if (userCustomDomain) return res.status(201).json({ customDomain: userCustomDomain.name });
  207. return res.status(400).json({ error: "Couldn't set custom domain." });
  208. };
  209. exports.deleteCustomDomain = async ({ user }, res) => {
  210. const response = await deleteCustomDomain({ user });
  211. if (response) return res.status(200).json({ message: 'Domain deleted successfully' });
  212. return res.status(400).json({ error: "Couldn't delete custom domain." });
  213. };
  214. exports.deleteUrl = async ({ body: { id, domain }, user }, res) => {
  215. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  216. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  217. const urls = await findUrl({ id, domain: customDomain });
  218. if (!urls && !urls.length) return res.status(400).json({ error: "Couldn't find the short URL." });
  219. redis.del(id + (customDomain || ''));
  220. const response = await deleteUrl({ id, domain: customDomain, user });
  221. if (response) return res.status(200).json({ message: 'Sort URL deleted successfully' });
  222. return res.status(400).json({ error: "Couldn't delete short URL." });
  223. };
  224. exports.getStats = async ({ query: { id, domain }, user }, res) => {
  225. if (!id) return res.status(400).json({ error: 'No id has been provided.' });
  226. const customDomain = domain !== config.DEFAULT_DOMAIN && domain;
  227. const stats = await getStats({ id, domain: customDomain, user });
  228. if (!stats) return res.status(400).json({ error: 'Could not get the short URL stats.' });
  229. return res.status(200).json(stats);
  230. };
  231. exports.reportUrl = async ({ body: { url } }, res) => {
  232. if (!url) return res.status(400).json({ error: 'No URL has been provided.' });
  233. const isValidUrl = urlRegex({ exact: true, strict: false }).test(url);
  234. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  235. const mail = await transporter.sendMail({
  236. from: config.MAIL_USER,
  237. to: config.REPORT_MAIL,
  238. subject: '[REPORT]',
  239. text: url,
  240. html: url,
  241. });
  242. if (mail.accepted.length) {
  243. return res.status(200).json({ message: "Thanks for the report, we'll take actions shortly." });
  244. }
  245. return res.status(400).json({ error: "Couldn't submit the report. Try again later." });
  246. };
  247. exports.ban = async ({ body }, res) => {
  248. if (!body.id) return res.status(400).json({ error: 'No id has been provided.' });
  249. const urls = await findUrl({ id: body.id });
  250. const [url] = urls.filter(item => !item.domain);
  251. if (!url) return res.status(400).json({ error: "Couldn't find the URL." });
  252. if (url.banned) return res.status(200).json({ message: 'URL was banned already' });
  253. redis.del(body.id);
  254. const domain = URL.parse(url.target).hostname;
  255. let host;
  256. if (body.host) {
  257. try {
  258. const dnsRes = await dnsLookup(domain);
  259. host = dnsRes && dnsRes.address;
  260. } catch (error) {
  261. host = null;
  262. }
  263. }
  264. await banUrl({
  265. domain: body.domain && domain,
  266. host,
  267. id: body.id,
  268. user: body.user,
  269. });
  270. return res.status(200).json({ message: 'URL has been banned successfully' });
  271. };