Hi, I have marked one employee as left and added resign date and relieving date. But, still employee is able to login into their user account and able to submit leave request. How can I automatically disable left employee user login and remove all permissions for that user?
Hi there,
There are a few different options, depending on your needs.
The simplest would be to use an on_save
hook with the Employee doctype, marking the user inactive if the employee has left.
A more pro-active solution would be to use a session-level on_login
hook. You could check that the user is matched to an active employee and terminate the session if not. This would be more secure but slightly more complex.
Require client script?
I would suggest doing this server-side, not with a client script. Client scripts are great for UX conveniences, but anything data- or authentication-linked is usually better done with a server-based hook.
Where should we paste this script?
Below is the working code.
frappe.ui.form.on('Employee', {
status: function(frm) {
// Check if status has changed and is not "Active"
if (frm.doc.status !== "Active" && frm.doc.user_id) {
// Confirm with the user
frappe.confirm(
__('Employee status is changed to "{0}". Do you want to disable the linked user account?', [frm.doc.status]),
function() {
// User clicked "Yes"
frappe.call({
method: "frappe.client.set_value",
args: {
doctype: "User",
name: frm.doc.user_id,
fieldname: "enabled",
value: 0
},
callback: function(r) {
if (r.message && r.message.enabled === 0) {
frappe.show_alert({
message: __("User {0} has been disabled", [frm.doc.user_id]),
indicator: 'green'
}, 5);
}
}
});
},
function() {
// User clicked "No"
// Do nothing
}
);
} else if (frm.doc.status === "Active" && frm.doc.user_id) {
// Optionally enable user if status is changed to Active
frappe.call({
method: "frappe.client.set_value",
args: {
doctype: "User",
name: frm.doc.user_id,
fieldname: "enabled",
value: 1
},
callback: function(r) {
if (r.message && r.message.enabled === 1) {
frappe.show_alert({
message: __("User {0} has been enabled", [frm.doc.user_id]),
indicator: 'green'
}, 5);
}
}
});
}
},
after_save: function(frm) {
// Double-check after save to ensure user status matches employee status
if (frm.doc.status !== "Active" && frm.doc.user_id) {
frappe.call({
method: "frappe.client.get_value",
args: {
doctype: "User",
filters: {
name: frm.doc.user_id
},
fieldname: ["enabled"]
},
callback: function(r) {
if (r.message && r.message.enabled === 1) {
// User is still enabled but should be disabled
frappe.call({
method: "frappe.client.set_value",
args: {
doctype: "User",
name: frm.doc.user_id,
fieldname: "enabled",
value: 0
}
});
}
}
});
}
}
});
When you change Employee Status to anything other than Active, it will throw a confirmation popup to disable linked user.
If you click on Yes, it disables user account.
If you change back status to Active again, it will enable the user.