Back

How to protect non-public views

  • 0
  • Databases
  • Cloud
Mr English
10 Jun, 2024, 15:13

My website has public pages and non-public pages. Only a logged in user can access the non-public pages. My question is: how do we prevent non logged in people from accessing those pages.

The following nodejs controller method renders the view \admin\index. What code needs to be added to prevent non logged in users from accessing the view?

TypeScript
exports.getIndex = async(req,res) => {
    
    // How do I block this view from rendering if the user is not logged in?
    // I.e. how do I check to see if there is a session record when this view is accessed?
TL;DR
To protect non-public views on a NodeJS website, developers can check if the user is logged in before rendering the view. One approach is to retrieve the current user and, if no user is found, either block the rendering of the page or redirect them to the login page. This can be implemented by ensuring authentication is required to access non-public pages. By adding a check for a session record before rendering the view, developers can prevent non-logged-in users from accessing those pages.
Kenny
10 Jun, 2024, 15:14

Fetch the current user, if nothing is returned either don't render the page or redirect them to a login page.

Mr English
10 Jun, 2024, 15:15

Can the current User be fetched by a non logged in user?

Kenny
10 Jun, 2024, 15:15

if they're not logged in it will return nothing

Mr English
10 Jun, 2024, 15:17

I think in this case, an error would be generated.

Kenny
10 Jun, 2024, 15:18
TypeScript
try {
  const user = await account.get();
} catch (error) {
  redirect("login");
}
Kenny
10 Jun, 2024, 15:18

You can do something like this.

Mr English
10 Jun, 2024, 15:18

ok thanks Kenny.

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more