Hello, i will share my solution for the problem but this is might be no the optimal solution but this is how i tackled
1- The strapi instance initialization.
2- Granting the permissions for the Authenticated role to my controllers.
3- How to create a user and assign the role ‘Authenticated’ to this mock user.
1- The strapi instance initialization is pretty much like @Aashis said but with minor modification. Should be like that
const Strapi = require("@strapi/strapi");
let instance;
async function setupStrapi() {
if (!instance) {
await Strapi().start();
instance = strapi;
}
return instance;
}
to make an API call - this is different than the docs
it("Should login user and return jwt token", async () => {
const { user } = await getAuthenticatedUser(); // this is will be covered in point 3.
await request(strapi.server.httpServer) // app server is an instance of Class: http.Server
.post("/api/auth/local")
.set("accept", "application/json")
.set("Content-Type", "application/json")
.send({
identifier: mockUser.email,
password: mockUser.password,
})
.expect("Content-Type", /json/)
.expect(200)
.then(data => {
expect(data.body.jwt).toBeDefined();
});
});
2- Granting the permissions for the Authenticated role to my controllers.
I’m pretty sure that should be another optimal solution instead of the one that i’m currently using. But this is will work just fine but it’s an extra step after all.
i created a method called grantPrivilege to add the permissions to the Authenticated role. Or to allow the Authenticated user to use any controller if the permissions is granted.
here is the function
/**
* Grants database `permissions` table that role can access an endpoint/controllers
*
* @param {int} roleID, 1 Autentihected, 2 Public, etc
* @param {Object} body
*/
const grantPrivilege = async (roleID = 1) => {
return strapi.plugin("users-permissions").service("role").updateRole(roleID, authenticatedRolePermissions); // i will add a sample for that below
};
the authenticatedRolePermissions is an object with the whole controllers or plugins that i have
const authenticatedRolePermissions = {
name: "Authenticated",
description: "Default role given to authenticated user.",
permissions: {
"api::article": {
controllers: {
article: {
find: { enabled: true, policy: "" },
findOne: { enabled: true, policy: "" },
create: { enabled: true, policy: "" },
update: { enabled: true, policy: "" },
delete: { enabled: true, policy: "" },
// If there is any custom methods will need to add it here
myCustomMethod: { enable : true, policy: "" }
}
}
}
},
}
Then to complete the setup you will need to fire grantPrivilage in beforeAll jest method
beforeAll(async () => {
await setupStrapi(); // singleton so it can be called many times
await grantPrivilege();
});
This will allow the Authenticated role - this role is automatically assigned to any authenticated use -.
3- How to create a user and assign the role ‘Authenticated’ to this mock user.
Last but not least to create a user with Authenticated role. To do that you can just use the code right below.
const createUserWithAuthenticatedRole = async (newUser = {}) => {
const mockUserData = {
username: "tester",
email: "tester@test.com",
provider: "local",
password: "1234abc",
confirmed: true,
blocked: null,
};
const advanced = await strapi.store({ type: "plugin", name: "users-permissions", key: "advanced" }).get();
const defaultRole = await strapi
.query("plugin::users-permissions.role")
.findOne({ where: { type: advanced.default_role } });
mockUserData.role = defaultRole.id; // Assign the Authenticated role to the user
const user = await strapi.plugins["users-permissions"].services.user.add({
...mockUserData,
...newUser,
});
return user;
};
/**
* Create user with role Authenticated
* @returns {Object}
*/
const getAuthenticatedUser = async () => {
let user;
user = await strapi.db.query("plugin::users-permissions.user").findOne({
where: {
email: "tester@test.com",
},
populate: { role: true },
});
if (!user) {
user = await createUserWithAuthenticatedRole();
}
// Issue a token for this user - to test the private routes
const jwt = strapi.plugin("users-permissions").service("jwt").issue({
id: user.id,
});
return {
user,
jwt,
};
};
module.exports = {
getAuthenticatedUser,
createUserWithAuthenticatedRole,
};