ftp.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. var ftpd = require('ftpd'),
  2. fs = require('fs'),
  3. superagent = require('superagent'),
  4. path = require('path');
  5. var simpleAuth = process.env.SIMPLE_AUTH_URL && process.env.SIMPLE_AUTH_CLIENT_ID && process.env.API_ORIGIN;
  6. function verifyUser(username, password, callback) {
  7. if (!simpleAuth) {
  8. if (username === 'test' && password === 'test') return callback(null);
  9. else return callback(new Error('auth failed'));
  10. }
  11. var authPayload = {
  12. clientId: process.env.SIMPLE_AUTH_CLIENT_ID,
  13. username: username,
  14. password: password
  15. };
  16. superagent.post(process.env.SIMPLE_AUTH_URL + '/api/v1/login').send(authPayload).end(function (error, result) {
  17. if (error && error.status === 401) return callback(new Error('auth failed'));
  18. if (error) return callback(wrapRestError(error));
  19. if (result.status !== 200) return callback(new Error('auth failed'));
  20. callback(null);
  21. });
  22. }
  23. var server;
  24. var options = {
  25. host: '0.0.0.0',
  26. port: process.env.FTP_PORT || 7002,
  27. tls: null,
  28. };
  29. server = new ftpd.FtpServer(options.host, {
  30. getInitialCwd: function() {
  31. return '/';
  32. },
  33. getRoot: function() {
  34. return '/app/data/public';
  35. },
  36. pasvPortRangeStart: process.env.FTP_PORT_PASV_0 || 7003,
  37. pasvPortRangeEnd: process.env.FTP_PORT_PASV_3 || 7006,
  38. tlsOptions: options.tls,
  39. allowUnauthorizedTls: true,
  40. useWriteFile: false,
  41. useReadFile: false
  42. });
  43. server.on('error', function(error) {
  44. console.log('FTP Server error:', error);
  45. });
  46. server.on('client:connected', function(connection) {
  47. var username = null;
  48. console.log('client connected: ' + connection.remoteAddress);
  49. connection.on('command:user', function(user, success, failure) {
  50. if (user) {
  51. username = user;
  52. success();
  53. } else {
  54. failure();
  55. }
  56. });
  57. connection.on('command:pass', function(password, success, failure) {
  58. if (!password) return failure();
  59. verifyUser(username, password, function (error) {
  60. if (error) failure();
  61. else success(username);
  62. });
  63. });
  64. });
  65. server.debugging = 4;
  66. server.listen(options.port);
  67. console.log('Listening on port ' + options.port);