/**
 * atk_unauthorized_access.cy.js
 *
 * Validate unauthorized access.
 *
 */

/** ESLint directives */
/* eslint-disable import/first */

/// <reference types='Cypress' />

// Set up ATK.
import * as atkCommands from '../../support/atk_commands' // eslint-disable-line no-unused-vars
// eslint-disable-next-line no-unused-vars
import * as atkUtilities from '../../support/atk_utilities'
// eslint-disable-next-line no-unused-vars
import atkConfig from '../../../cypress.atk.config'

// Standard accounts that use user accounts created
// by QA Accounts. QA Accounts are created when the QA
// Accounts module is enabled.
// eslint-disable-next-line no-unused-vars
import qaUserAccounts from '../../data/qaUsers.json'

describe('Unauthorized Access Tests', () => {
  //
  // Test unauthorized access to the resource not under the Drupal's control.
  // It will check authorization by the OS file permission.
  // Webserver process must run under the different user.
  // This test may not work under DDEV.
  //
  it('(ATK-CY-1230) should return 401 for the resource that isn\'t under the Drupal\'s control ', { tags: ['@ATK-1230', '@fedramp', '@unauthorized'] }, () => {
    cy.execDrush('file:create sites/default/files/test-content/test.txt --permissions 0600')

    Cypress.config()
    cy.request({
      url: '/sites/default/files/test-content/test.txt',
      failOnStatusCode: false,
    }).then((response) => {
      expect(response.status).eq(401)
    })
  })

  //
  // List of URLs that should be unauthorized by anonymous user.
  //
  const ANONYMOUS_URL_LIST = ['admin', 'user/1']
  // eslint-disable-next-line no-restricted-syntax
  for (const url of ANONYMOUS_URL_LIST) {
    it(`(ATK-CY-1231) should return 403 for unauthorized access to ${url}`, () => {
      cy.request({
        url,
        failOnStatusCode: false,
      }).then((response) => {
        expect(response.status).eq(403)
      })
    })
  }

  //
  // List of URLs that should be unauthorized by authenticated user.
  //
  const AUTHENTICATED_URL_LIST = ['admin', 'user/1']
  // eslint-disable-next-line no-restricted-syntax
  for (const url of AUTHENTICATED_URL_LIST) {
    it(`(ATK-CY-1232) should return 403 for unauthorized access to ${url}`, () => {
      cy.logInViaForm(qaUserAccounts.authenticated)
      cy.intercept(url).as('page')
      cy.visit(url, { failOnStatusCode: false })
      cy.get('@page').then((response) => {
        expect(response.response.statusCode).eq(403)
      })
    })
  }
})
