You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.4KB

  1. import * as fs from 'fs';
  2. import { v2 as webdav } from 'webdav-server';
  3. function getConfig(name: string) : any {
  4. let config = {};
  5. let base = "./config/" + name;
  6. let debug = base + '.debug.json';
  7. let prod = base + '.json';
  8. let path = fs.existsSync(debug) ? debug : prod;
  9. if (fs.existsSync(path)) {
  10. try {
  11. config = JSON.parse(fs.readFileSync(path, 'utf8'));
  12. }
  13. catch (err) {
  14. }
  15. }
  16. return config;
  17. }
  18. const config = getConfig('srvconfig');
  19. const users = getConfig('users');
  20. if (typeof config.port === undefined)
  21. config.port = 8080;
  22. if (typeof config.realm === undefined)
  23. config.realm = "WebDAV";
  24. let mountNames : string[] = [];
  25. for (let mount in config['mounts']) {
  26. if (!!config['mounts'][mount] && fs.existsSync(config['mounts'][mount]))
  27. mountNames.push(mount);
  28. }
  29. // User manager (tells who are the users)
  30. const userManager: webdav.SimpleUserManager = new webdav.SimpleUserManager();
  31. const privilegeManager: webdav.SimplePathPrivilegeManager = new webdav.SimplePathPrivilegeManager();
  32. for (let nuser = 0 ; nuser < users.length; nuser++) {
  33. let isAdmin = !!users[nuser]['isAdmin'];
  34. const user = userManager.addUser(users[nuser]['username'], users[nuser]['password'], isAdmin);
  35. if (isAdmin) {
  36. privilegeManager.setRights(user, '/', [ 'all' ]);
  37. }
  38. else {
  39. if (!!users[nuser]['access']) {
  40. for (let userMount in users[nuser]['access']) {
  41. if (mountNames.includes(userMount) && !!users[nuser]['access'][userMount]) {
  42. privilegeManager.setRights(user, '/' + userMount, users[nuser]['access'][userMount]);
  43. }
  44. }
  45. }
  46. }
  47. console.log(user);
  48. }
  49. const httpAuthentication = new webdav.HTTPBasicAuthentication(userManager);
  50. const serverOptions: webdav.WebDAVServerOptions = {
  51. port: config.port || 8080,
  52. requireAuthentification: true,
  53. httpAuthentication,
  54. privilegeManager,
  55. };
  56. //serverOptions['userManager'] = userManager;
  57. const server = new webdav.WebDAVServer(serverOptions);
  58. let nMount = 0;
  59. //@ts-ignore
  60. function mountAndStart() : void {
  61. if (nMount < mountNames.length) {
  62. let fsEntry = mountNames[nMount];
  63. let realPath = config['mounts'][fsEntry];
  64. nMount++;
  65. console.log(`FileSystem ${fsEntry} -> ${realPath}`)
  66. server.setFileSystem(
  67. '/' + fsEntry, new webdav.PhysicalFileSystem(realPath), (_success) => {mountAndStart();});
  68. }
  69. else {
  70. server.start(httpServer => {
  71. console.log('Server started with success on the port : ' + httpServer.address()['port']);
  72. });
  73. }
  74. }
  75. mountAndStart();