Trying to understand main.js

After my initial trouble in this topic I am now trying to initialize some stuff for my app from the main.js folder.

However, I am running into multiple problems, which makes me unsure what exactly I can use this file for.

I have the following code:

try {
  var authLib = require('/lib/xp/auth');
  var authenticatedUser = authLib.login({
    user: 'su', 
    password: 'password',
    userStore: 'system'
  });
  log.info("Login-object: %s", authenticatedUser);
  log.info("Logged in user: %s", authLib.getUser());

  var repoLib = require('/lib/xp/repo');
  repoLib.create({
    id: 'my-first-repo'
  });
} catch (e) {
  log.warning("Failed initializing app. \nError: %s.", e);
}

This produces these errors:

15:05:53.961 INFO  c.e.x.c.i.app.ApplicationServiceImpl - Application [no.vegard.it.xp.formbuilder] installed successfully
15:05:54.114 INFO  no.vegard.it.xp.formbuilder - (/main.js) Login-object: {"authenticated":true,"user":{"type":"user","key":"user:system:su","displayName":"Super User","disabled":false,"login":"su","userStore":"system"}}
15:05:54.122 INFO  no.vegard.it.xp.formbuilder - (/main.js) Logged in user: null
15:05:54.138 WARN  no.vegard.it.xp.formbuilder - (/main.js) Failed initializing app.
Error: com.enonic.xp.exception.ForbiddenAccessException: Access denied to user [unknown] .

As you can see, I receive an object back from the login-call which indicates the superuser is logged in, but getting the current user returns null.

Trying to create a repo produces a ForbiddenAccessException.

Am I doing something wrong? Are there restrictions on what libs, etc. that can/should be used from the main.js file?

Some of the lib functions expect to be called in the context of an HTTP request.

I have not tested it, but something you could try is using contextLib.run and doing the same things inside the callback function, instead of using authLib.login.

http://repo.enonic.com/public/com/enonic/xp/docs/6.9.0/docs-6.9.0-libdoc.zip!/module-lib_xp_context.html#.run

3 Likes

Nice, I had not discovered that lib yet!

It worked like a charm, and I was able to initialize my repo as well.
I am really excited about the possibilities in the latest release! :smiley:

4 Likes