Morally, the excess of rent over the security deposit that accrues during the landlord's ownership of the property should go to them. At the point where the property is sold you'd then owe the subsequent rent to the new owners. The lender isn't entitled to rent from a property that they don't own yet. Foreclosure sales open up with a beginning bid amount that will completely pay off the foreclosing lender. That's where the bidding begins.
Any amount bid by outside bidders that exceeds the lender's balance goes to any junior lienors.
After the sale the new owners are entitled to possession of the property as they see fit. Perhaps that means that you will have to vacate, or perhaps they would want you to remain as tenants of theirs. But in any case, almost all jurisdictions require the new owners to give you a formal notice before you have to move out.