Redirect to the previous URL

Hi,

I want to implement a redirect upon login. When a user navigates the community and he is not logged in, when he goes to a private group he is redirected to the login interface. Because we have our own custom authentication, the user interface is not part of the community( so I can't use window.history.back()), so after login the user is redirected to the community homepage and that previous url is lost.

How can I save that url before the community asks the user to login or register? What can I plugin can I built to check that right after login a user is redirected to that url, is there an event for that?

Regards!