'use strict'; var path = require('path'); /** * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ const getNc = function (selector, args = {}) { if (typeof selector !== 'function') { console.error(selector); throw new Error('Invalid selector'); } return selector(args); }; /** * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ /** * You should always upload files and/or create users * before login, so that the cookies are NOT YET defined. * * @see https://docs.cypress.io/api/commands/session */ const login = function (user) { cy.session(user, function () { cy.request('/csrftoken').then(({ body }) => { var _a; const requestToken = body.token; cy.request({ method: 'POST', url: '/login', body: { user: user.userId, password: user.password, requesttoken: requestToken }, headers: { 'Content-Type': 'application/x-www-form-urlencoded', // Add the Origin header so that the request is not blocked by the browser. 'Origin': ((_a = Cypress.config('baseUrl')) !== null && _a !== void 0 ? _a : '').replace('index.php/', ''), }, followRedirect: false, }); }); }, { validate() { cy.request('/apps/files').its('status').should('eq', 200); }, }); }; /** * Theoretically, should rarely be needed as we * are either login in with another user, which * change the active session, or changing specs * which reset active sessions too * * @see https://docs.cypress.io/api/commands/session#Session-caching */ const logout = function () { cy.request('/csrftoken').then(({ body }) => { const requestToken = body.token; cy.visit(`/logout?requesttoken=${encodeURIComponent(requestToken)}`); }); cy.clearCookies(); }; /** * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ class User { constructor(user, password = user, language = 'en') { Object.defineProperty(this, "userId", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "password", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "language", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.userId = user; this.password = password; this.language = language; } static createRandom() { const uid = (Math.random() + 1).toString(36).substring(7); return new User(uid); } } /** * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ const randHash = () => Math.random().toString(36).replace(/[^a-z]+/g, '').slice(0, 10); /** * Create a random user */ const createRandomUser = function () { const user = new User(randHash()); cy.log(`Generated user ${user.userId}`); createUser(user); return cy.wrap(user); }; /** * Create a user * * **Warning**: Using this function will reset the previous session */ const createUser = function (user) { const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users?format=json`.replace('index.php/', ''); cy.clearCookies(); return cy.request({ method: 'POST', url, body: { userid: user.userId, password: user.password }, auth: { user: 'admin', pass: 'admin' }, headers: { 'OCS-ApiRequest': 'true', }, followRedirect: false, // Allow us to test failOnStatusCode: false, }).then((response) => { cy.log(`Created user ${user.userId}`); // Avoid that any follow up request reuses the admin cookies cy.clearCookies(); return cy.wrap(response); }); }; function listUsers(details = false) { const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users${details ? '/details' : ''}`.replace('index.php/', ''); cy.clearCookies(); return cy.request({ method: 'GET', url, auth: { user: 'admin', pass: 'admin' }, headers: { 'OCS-ApiRequest': 'true', }, }).then((response) => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(response.body, "text/xml"); if (!details) { const users = Array.from(xmlDoc.querySelectorAll('users element')).map(v => v.textContent); return users.filter(v => typeof v === 'string'); } else { const list = Array.from(xmlDoc.querySelectorAll('users > *')).map(v => { // We only handle simple text properties for the moment const properties = [...v.childNodes].filter(c => c.childNodes.length <= 1); return Object.fromEntries(properties.map(p => [p.nodeName, p.textContent || ''])); }); return list; } }); } /** * Delete an user on the Nextcloud instance * * **Warning**: Using this function will reset the previous session * @param user User to delete */ const deleteUser = function (user) { const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users/${user.userId}`.replace('index.php/', ''); cy.clearCookies(); return cy.request({ method: 'DELETE', url, form: true, auth: { user: 'admin', pass: 'admin' }, headers: { 'OCS-ApiRequest': 'true', 'Content-Type': 'application/x-www-form-urlencoded', }, failOnStatusCode: false, }).then((response) => { cy.log(`Deleted user ${user}`, response.status); cy.clearCookies(); return cy.wrap(response); }); }; /** * Modify an attribute of a given user on the Nextcloud instance * * @param user User who performs the modification * @param key Attribute name * @param value New attribute value */ const modifyUser = function (user, key, value) { const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users/${user.userId}`.replace('index.php/', ''); return cy.request({ method: 'PUT', url, form: true, body: { key, value }, auth: { user: user.userId, password: user.password }, headers: { 'OCS-ApiRequest': 'true', 'Content-Type': 'application/x-www-form-urlencoded', }, }).then((response) => { cy.log(`Updated user ${user} ${key} to ${value}`, response.status); return cy.wrap(response); }); }; /** * Query metadata for and in behalf of a given user * * @param user User to change */ const getUserData = function (user) { const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users/${user.userId}`.replace('index.php/', ''); return cy.request({ method: 'GET', url, auth: { user: user.userId, pass: user.password }, headers: { 'OCS-ApiRequest': 'true', }, }).then((response) => { cy.log(`Loaded metadata for user ${user}`, response.status); return cy.wrap(response); }); }; /** * Enable or disable a user * * @param {User} user the user to dis- / enable * @param {boolean} enable True if the user should be enable, false to disable */ const enableUser = function (user, enable = true) { const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users/${user.userId}/${enable ? 'enable' : 'disable'}`.replace('index.php/', ''); return cy.request({ method: 'PUT', url, form: true, auth: { user: 'admin', password: 'admin', }, headers: { 'OCS-ApiRequest': 'true', 'Content-Type': 'application/x-www-form-urlencoded', }, }).then((response) => { cy.log(`Enabled user ${user}`, response.status); return cy.wrap(response); }); }; /** * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ function getContainerName() { return cy.exec('pwd').then(({ stdout }) => { const name = path.basename(stdout).replace(' ', ''); return cy.wrap(`nextcloud-e2e-test-server_${name}`); }); } function runCommand(command, options) { var _a; const env = Object.entries((_a = options === null || options === void 0 ? void 0 : options.env) !== null && _a !== void 0 ? _a : {}) .map(([name, value]) => `-e '${name}=${value}'`) .join(' '); getContainerName() .then((containerName) => { // Wrapping command inside bash -c "..." to allow using '*'. return cy.exec(`docker exec --user www-data --workdir /var/www/html ${env} ${containerName} bash -c "${command}"`, options); }); } /** * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ function saveState() { const snapshot = Math.random().toString(36).substring(7); runCommand(`rm /var/www/html/data-${snapshot}.tar`, { failOnNonZeroExit: false }); runCommand(`tar cf /var/www/html/data-${snapshot}.tar ./data`); cy.log(`Created snapshot ${snapshot}`); return cy.wrap(snapshot); } function restoreState(snapshot = 'init') { runCommand(`rm -vfr ./data/*`); runCommand(`tar -xf '/var/www/html/data-${snapshot}.tar'`); cy.log(`Restored snapshot ${snapshot}`); } /** * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ function runOccCommand(command, options) { runCommand(`php ./occ ${command}`, options); } exports.createRandomUser = createRandomUser; exports.createUser = createUser; exports.deleteUser = deleteUser; exports.enableUser = enableUser; exports.getNc = getNc; exports.getUserData = getUserData; exports.listUsers = listUsers; exports.login = login; exports.logout = logout; exports.modifyUser = modifyUser; exports.randHash = randHash; exports.restoreState = restoreState; exports.runCommand = runCommand; exports.runOccCommand = runOccCommand; exports.saveState = saveState; //# sourceMappingURL=index.cjs.map