Granting and revoking permission programmatically


Following is what I want to achieve.

When the department is set to user, User permission should be added to that user for assigned department. Also previously assigned department should be revoked.

I have created a hook in my custom app on Employee.on_update event and added permission using

frappe.permissions.add_user_permission("Department", self.department, self.user_id)

But having problem revoking previously assigned department, as I could not able to get old value of department.

Is there any way I can get old attributes of the document or changed ones.

Thank you.

What version of frappe are u using ?
if it is 8 or above you can get what you want by using frappe.get_list as the user permission became a doctype e.g:

frappe.get_list("User Permission", filters = {"user": self.user_id, "allow": "Department"}, fields = ["for_value", "name"])

so you can use the above query to retrieve all of assigned departments for the user and you can delete them before setting a new one

to delete them you can make a for loop over the above query
for p in frappe.get_list("User Permission", filters = {"user": self.user_id, "allow": "Department"}, fields = ["for_value", "name"]) frappe.delete_doc("User Permission",

Thanks. I’ll check this solution.