Please share any ideas and solutions for my requirement.
Drop the “function or a stored procedure” requirement, use an external application language instead. Node.js for example.
Separate the listing of extra/missing privileges from the execution of code to fix those things.
You didn’t mention how the software is supposed to know what is the correct set of permissions. If you haven’t worked through that detail conceptually, and with some manual query execution to prove out that it works, that should be the first feature to design and implement.
David J.