Server script restricted to only System Manage role

Did a test server script from the example.

# respond to API

if frappe.form_dict.message == "ping":
	frappe.response['message'] = "pong"
else:
	frappe.response['message'] = "ok"

It works. Tested using postman.

“Allow Guest” is ticked.

With “Allow Guest” unticked it does not work. Good.

Then I used the token of a website user in postman and the script works. Which is not good for this script.

Is there some code that can be placed above the test code so that it will check the role of the authentication and only allow if it is “System Manager”?

Tried the following code but does not work.

# Restrict to System Manager only
session_user = frappe.session.user
user_roles = frappe.get_roles(session_user)
    
# Allow only System Manager roles.
if "System Manager" not in user_roles:
    frappe.throw("Access Denied: Only System Managers can access this API", frappe.PermissionError)

Postman is giving the following error.

"exception": "AttributeError: module has no attribute 'get_roles'",

Looks like frappe.get_roles cannot be used.

Please share some solution to this.

Got the above idea from the following post.

The above working with a file in an erpnext app.

My problem is in the gui of erpnext, there is a Server script doctype.

An api can be created there and the above solution does not seem to work in the gui Server Script of erpnext.

I hope I am using the correct terms.

I am not a programmer.

Looks like I can only use some methods.

Might have to use sql.

Any advice?

Hi @pvanthony

The way I understand it - this example is just to ping the server and see if it is responding

Create two users - one with access to customer list and one without. Get their API key and secret and then put in postman

When you make a GET request for the customer list the first one will be allowed and the second will be denied. The permission check kicks in and each api key is allowed based on their authorizations

Hope it helps

Hello,

unfortunately get_role is not whitelisted function on Server Script.

You can use this workaround:

roles = frappe.get_all(

    "Has Role",

    filters={"parent": frappe.session.user},

    pluck="role",

)

if ("System Manager" in roles):
   #something

I hope it will help.

Jirka

2 Likes

Thank you very much for the code. It works great!!!

1 Like

Thank you for the reply.

So the permissions are set at the doctype. Noted.

For my use case, the solution above was what I was looking for.