Back

Validate User Server Side

  • 0
  • Self Hosted
  • Web
popemob1le
12 Sep, 2024, 17:44

I want to check if the user has a valid session before fetching data

TypeScript
import { Client, Users } from 'node-appwrite';

export async function GET() {
    const client = new Client()
        .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT as string)
        .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID as string)
        .setKey(process.env.APPWRITE_API_KEY as string); // Securely use API key

    const usersAPI = new Users(client);

    try {
        // Fetch the user list from Appwrite
        const usersList = await usersAPI.list();

        // Log the labels for each user
        usersList.users.forEach((user) => {
            console.log(`User: ${user.name}, Labels: `, user.labels);
        });

        const users = usersList.users.map((user) => ({
            name: user.name || 'N/A',
            email: user.email,
            phone: user.phone || 'N/A',
            emailVerification: user.emailVerification, 
            phoneVerification: user.phoneVerification,
            isAdmin: user.labels.includes('admin') // Check if 'admin' label exists in labels array
        }));

        return NextResponse.json({ totalUsers: usersList.total, users });
    } catch (error: any) {
        console.error('Error fetching users:', error);
        return NextResponse.json({ totalUsers: 0, users: [] }, { status: 500 });
    }
}

I am trying to make some middleware that validates a users session and checkf for some custom permissions or the admin label before allowing them to proceed. Using app router in NextJs.

TL;DR
Utilize .setSession to impersonate user instead of using full admin access. Ensure to validate user session before fetching data. The code provided lists users from Appwrite and checks for admin label.
D5
12 Sep, 2024, 17:53

If you're using API key, then you have full access to everything

D5
12 Sep, 2024, 17:54

I think you should use .setSession in your case in order to work as the user instead of full admin server side

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