Search code examples
javascriptnode.jshapihapi-auth-cookie

Hapi auth cookie sets but request.auth.credentials is null


I have read the docs of hapi-auth-cookie to try to make validation in my website.

The cookie sets and I can see it in my chrome browser dev tools application tab

however when I console.log request.auth.credentials the result is null

What I want to accomplish with this is to restrict user to http://localhost:3000/restricted and I think that the missing link is the request.auth.credentials because it is null

here is my code

const users = [
    {
        username: 'john',
        password: '$2b$10$nrkw6Mco2j7YyBqZSWRAx.P3XEZsZg3MNfma2ECO8rGMUTcF9gHO.',   // 'secret'
        name: 'John Doe',
        id: '2133d32a'
    }
];


await server.register(require('hapi-auth-cookie'));

    //strategy
    server.auth.strategy('session', 'cookie', {
        cookie: {
            name: 'sid-example',
            password: '!wsYhFA*C2U6nz=Bu^%A@^F#SF3&kSR6',
            isSecure: false
        },
        redirectTo: '/login',
        validateFunc: async (request, session) => {

            const account = await users.find(
                (user) => (user.id === session.id)
            );

            if (!account) {

                return { valid: false };
            }

            return { valid: true, credentials: account };
        }
    });


    server.auth.default({strategy: 'session', mode: 'try'});

   //login post
    server.route({
        method: 'POST',
        path: '/login',
        handler: async (request, h) => {

           console.log(request.payload)
            const { username, password } = request.payload;
            const account = users.find(
                (user) => user.username === username
            );

            if (!account || !(await Bcrypt.compare(password, users[0].password))) {
                console.log('user or password incorrect')
                return h.view('login');
            }

            request.cookieAuth.set({ id: users.id });
            console.log('login successful')
            return h.redirect().location("/")
         }
    })


    //restricted
    server.route({
        method: 'GET',
        path: '/restricted',
        options: {
            auth: {
                mode: 'required',
                strategy: 'session'
            }
        },
        handler: (request, h) => {


            return new Promise ((resolve, reject) => {

                let views = () => {
                    return h.view('restricted');
                }

                return resolve(views());


            });

        }
    });

I tried setting the options.auth.mode to 'try' inside the restricted route and trying to remove options altogether.

All routes are working fine but the restricted route cannot be opened even if I am logged in.

Please help


Solution

  • You are not setting the cookie authentication correctly, your id is undefined, replace the users.id with account.id:

    request.cookieAuth.set({ id: account.id });