| 268 | } |
| 269 | |
| 270 | const loginFunction = async name => { |
| 271 | const I = container.support('I') |
| 272 | const userSession = config.users[name] |
| 273 | |
| 274 | if (!userSession) { |
| 275 | throw new Error(`User '${name}' was not configured for authorization in auth plugin. Add it to the plugin config`) |
| 276 | } |
| 277 | |
| 278 | const test = store.currentTest |
| 279 | |
| 280 | // we are in BeforeSuite hook |
| 281 | if (!test) { |
| 282 | enableAuthBeforeEachTest(name) |
| 283 | return |
| 284 | } |
| 285 | |
| 286 | const section = new Section(`I am logged in as ${name}`) |
| 287 | |
| 288 | if (config.saveToFile && !store[`${name}_session`]) { |
| 289 | loadCookiesFromFile(config) |
| 290 | } |
| 291 | |
| 292 | if (isPlaywrightSession() && test?.opts?.cookies) { |
| 293 | if (test.opts.user == name) { |
| 294 | output.debug(`Cookies already loaded for ${name}`) |
| 295 | |
| 296 | alreadyLoggedIn(name) |
| 297 | return |
| 298 | } else { |
| 299 | output.debug(`Cookies already loaded for ${test.opts.user}, but not for ${name}`) |
| 300 | await I.deleteCookie() |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | section.start() |
| 305 | |
| 306 | const cookies = store[`${name}_session`] |
| 307 | const shouldAwait = isAsyncFunction(userSession.login) || isAsyncFunction(userSession.restore) || isAsyncFunction(userSession.check) |
| 308 | |
| 309 | const loginAndSave = async () => { |
| 310 | if (shouldAwait) { |
| 311 | await userSession.login(I) |
| 312 | } else { |
| 313 | userSession.login(I) |
| 314 | } |
| 315 | |
| 316 | section.end() |
| 317 | const cookies = await userSession.fetch(I) |
| 318 | if (!cookies) { |
| 319 | output.debug("Cannot save user session with empty cookies from auto login's fetch method") |
| 320 | return |
| 321 | } |
| 322 | if (config.saveToFile) { |
| 323 | output.debug(`Saved user session into file for ${name}`) |
| 324 | fs.writeFileSync(path.join(store.outputDir, `${name}_session.json`), JSON.stringify(cookies)) |
| 325 | } |
| 326 | store[`${name}_session`] = cookies |
| 327 | } |
no test coverage detected