public async Task <IActionResult> SaveServer(PavlovServerViewModel server)
        {
            if (!ModelState.IsValid)
            {
                return(View("Server", server));
            }

            if (!await RightsHandler.HasRightsToThisPavlovServer(HttpContext.User,
                                                                 await _userservice.getUserFromCp(HttpContext.User), server.Id, _service, _pavlovServerService))
            {
                return(Forbid());
            }

            server.LiteDbUsers = (await _userservice.FindAll()).ToList();

            server.Owner = (await _userservice.FindAll())
                           .FirstOrDefault(x => x.Id == new ObjectId(server.LiteDbUserId));
            var resultServer = new PavlovServer();

            server.SshServer = await _service.FindOne(server.sshServerId);

            if (server.create)
            {
                // Duplicate Database entries check
                try
                {
                    await _pavlovServerService.IsValidOnly(server, false);

                    if (string.IsNullOrEmpty(server.SshServer.SshPassword))
                    {
                        throw new ValidateException("Id",
                                                    "Please add a sshPassword to the ssh user (Not root user). Sometimes the systems asks for the password even if the keyfile and passphrase is used.");
                    }
                    if (string.IsNullOrEmpty(server.ServerFolderPath))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath is needed!");
                    }
                    if (!server.ServerFolderPath.EndsWith("/"))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath needs a / at the end!");
                    }
                    if (!server.ServerFolderPath.StartsWith("/"))
                    {
                        throw new ValidateException("ServerFolderPath",
                                                    "The server ServerFolderPath needs a / at the start!");
                    }
                    if (server.ServerPort <= 0)
                    {
                        throw new ValidateException("ServerPort", "The server port is needed!");
                    }
                    if (server.TelnetPort <= 0)
                    {
                        throw new ValidateException("TelnetPort", "The rcon port is needed!");
                    }
                    if (string.IsNullOrEmpty(server.ServerSystemdServiceName))
                    {
                        throw new ValidateException("ServerSystemdServiceName",
                                                    "The server service name is needed!");
                    }
                    if (string.IsNullOrEmpty(server.Name))
                    {
                        throw new ValidateException("Name", "The Gui name is needed!");
                    }
                }
                catch (ValidateException e)
                {
                    ModelState.AddModelError(e.FieldName, e.Message);
                    return(await GoBackEditServer(server,
                                                  "Field is not set: " + e.Message));
                }

                if (server.SshKeyFileNameForm != null)
                {
                    await using var ms = new MemoryStream();
                    await server.SshKeyFileNameForm.CopyToAsync(ms);

                    var fileBytes = ms.ToArray();
                    server.SshKeyFileNameRoot = fileBytes;
                    // act on the Base64 data
                }

                try
                {
                    await _pavlovServerService.CreatePavlovServer(server);
                }
                catch (Exception e)
                {
                    return(await GoBackEditServer(server, e.Message, true));
                }
            }

            try
            {
                //save and validate server a last time
                resultServer = await _pavlovServerService.Upsert(server.toPavlovServer(server));
            }
            catch (ValidateException e)
            {
                ModelState.AddModelError(e.FieldName, e.Message);
                return(await GoBackEditServer(server,
                                              "Could not validate server -> " + e.Message, server.create));
            }

            if (ModelState.ErrorCount > 0)
            {
                return(await EditServer(server));
            }
            if (server.create)
            {
                return(Redirect("/PavlovServer/EditServerSelectedMaps/" + resultServer.Id));
            }

            return(RedirectToAction("Index", "SshServer"));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> CreateServer(string apiKey, int sshServerId, bool shack, string email)
        {
            if (!HasAccess(apiKey))
            {
                return(BadRequest("No AuthKey set or wrong auth key!"));
            }
            var sshServer = await _sshServerSerivce.FindOne(sshServerId);

            if (sshServer == null)
            {
                return(BadRequest("The ssh server does not exist!"));
            }
            if (!sshServer.IsForHosting)
            {
                return(BadRequest("The ssh server ist not for hosting!"));
            }

            var guid  = Guid.NewGuid().ToString();
            var model = new PavlovServerViewModel
            {
                Name                     = "Autogenerated: " + guid,
                TelnetPort               = sshServer.PavlovServers.Max(x => x.TelnetPort) + 1,
                DeletAfter               = 7,
                TelnetPassword           = Guid.NewGuid().ToString(),
                ServerPort               = sshServer.PavlovServers.Max(x => x.ServerPort) + 1,
                ServerFolderPath         = GeneratedServerPath + guid + "/",
                ServerSystemdServiceName = "pavlov" + guid.Replace("-", ""),
                ServerType               = ServerType.Community,
                ServerServiceState       = ServerServiceState.disabled,
                SshServer                = sshServer,
                AutoBalance              = false,
                SaveStats                = true,
                Shack                    = shack,
                sshServerId              = sshServer.Id,
                create                   = true,
                SshUsernameRoot          = sshServer.SshUsernameRootForHosting,
                SshPasswordRoot          = sshServer.SshPasswordRootForHosting,
                SshKeyFileNameRoot       = sshServer.SshKeyFileNameRootForHosting,
                SshPassphraseRoot        = sshServer.SshPassphraseRootForHosting
            };

            var user = await _userService.GetUserByEmail(email);

            if (user != null)
            {
                model.LiteDbUserId = user.Id.ToString();
                model.Owner        = user;
                if (!await _userManager.IsInRoleAsync(user, "ServerRent"))
                {
                    await _userManager.AddToRoleAsync(user, "ServerRent");
                }
            }

            try
            {
                await _pavlovServerService.CreatePavlovServer(model);
            }
            catch (Exception e)
            {
                await _sshServerSerivce.RemovePavlovServerFromDisk(model, true);

                DataBaseLogger.LogToDatabaseAndResultPlusNotify("Could not create rented server! " + model.Name, LogEventLevel.Fatal, _notifyService);
                return(BadRequest(e.Message));
            }


            var resultServer = await _pavlovServerService.Upsert(model.toPavlovServer(model));

            if (user == null)
            {
                await _reservedServersService.Add(new ReservedServer()
                {
                    Email = email, ServerId = resultServer.Id
                });
            }
            return(Ok(resultServer.Id));
        }