Reputation: 71
I would like to retrieve the role associated to specific user using strapi, but I can't.I tried this query but still not getting the role.
Can anyone help me ?
Thank you
Upvotes: 6
Views: 8090
Reputation: 368
Meanwhile, you can simply populate the role for users-permissions
users.
This both works:
/api/users/:id?populate=role
and /api/users/me?populate=role
You need to grant your user's role the following permission though: Admin panel -> settings -> users & permissions -> Roles -> your user's role -> users-permissions -> role -> find (note: findOne will not work !)
Upvotes: 8
Reputation: 71
Finally, there is no solution because populate doesn't work for user-permission. But I found an alternative solution in this post :
https://github.com/strapi/strapi/issues/11957
Upvotes: 1
Reputation: 25
I had the same problem with my project.
The first solution : there is actually an endpoint "api/users/me" you can see more here: https://forum.strapi.io/t/is-it-possible-to-know-user-role-on-authentication/14221 it will return something like this:
"role": {
"id": "string",
"name": "string",
"description": "string",
"type": "string",
"permissions": [
"string"
],
"users": [
"string"
],
"created_by": "string",
"updated_by": "string"
}
the header of the request has to contain:
"Authorization": `Bearer ${token}`
the final code would look like this:
const userData = async() => {
const response = await fetch('http://localhost:1337/api/users/me',
headers: {
authorization: `Bearer ${JsonWebToken}`,
})
const res = await response.json()
console.log(res)
}
Second solution another solution is using GraphQL
Const endPoint = "http://localhost:1337/graphql"
you have to install graphql though.
And by letting the token access the me data in setting > role > user-permission >user>me
your will get the response.
my code looks like this I am using react , graphql-request
import { GraphQLClient, gql } from "graphql-request"
const graphQLClient = new GraphQLClient(endPoint, {
headers: {
authorization: `Bearer ${WebToken}`,
},
})
const query = gql`
{
me {
role {
name
}
}
}
`
const data = await graphQLClient.request(query)
console.log(JSON.stringify(data))
the result is
{"me":{"role":{"name":"client"}}}
Upvotes: 0