import type { Page } from '@playwright/test'; import type { IUser } from '@rocket.chat/core-typings'; import { MongoClient } from 'mongodb'; import * as constants from '../config/constants'; import type { IUserState } from '../fixtures/userStates'; import { expect } from '../utils/test'; export class LoginPage { constructor(protected readonly page: Page) {} get loginButton() { return this.page.getByRole('button', { name: 'Login', exact: true }); } /** * Ideally the previous action should ensure the user is logged out and we should just assume to be at the login page * */ async waitForIt() { await this.loginButton.waitFor(); } /** Navigates to `url` and waits for the login screen — for routes that bounce an anonymous visitor. */ async goto(url = '/home'): Promise { await this.page.goto(url); await this.waitForIt(); } protected async waitForLogin() { await expect(this.loginButton).not.toBeVisible(); await expect(this.page.getByRole('main')).toBeVisible(); } async loginByUserState(userState: IUserState, options: { except: string[] } = { except: [] }) { // Creates a login token for the user const connection = await MongoClient.connect(constants.URL_MONGODB); await connection .db() .collection('users') .updateOne( { username: userState.data.username }, { $addToSet: { 'services.resume.loginTokens': { when: userState.data.loginExpire, hashedToken: userState.data.hashedToken } } }, ); await connection.close(); const localStorageItems = userState.state.origins[0].localStorage.filter((item) => options.except.indexOf(item.name) === -1); // Injects the login token to the local storage await this.page.evaluate((items) => { items.forEach(({ name, value }) => { window.localStorage.setItem(name, value); }); require('meteor/accounts-base').Accounts._pollStoredLoginToken(); }, localStorageItems); await this.waitForLogin(); } }