Search code examples
koa

Destroying a session in koa-session


So I have a simple authorization system where on login user is saved to a session. Problem is in situation like that, where I want to delete a session, thus logging the user out, session carries onto the next request.

app.get('/logout', ctx => {
    ctx.session = null;
    ctx.redirect('/');
});

So in this situation code below will render user info on the page after redirecting from logout:

app.get('/', ctx => ctx.body = ctx.session);

Cookies aren't cleared too.


Solution

  • I am fairly new to koa-session but was able to implement user authentication in a project a while back, by setting the user's id object to ctx.session.id.

    Login

    router.post('/login', async ctx => {
      const userDetails = ctx.request.body
      try {
            const userDetails = ctx.request.body
            const userId = await user.login(userDetails)
            ctx.session.authenticated = true
            ctx.session.id = userId
            ctx.redirect('/')
        } catch (error) {
            await ctx.render('login', {error: error})
        } finally {
            await user.tearDown()
        }
    })
    

    Logout

    router.get('/logout', async ctx => {
        if (ctx.session.authenticated === true) {
            ctx.session.authenticated = false
            ctx.session.id = undefined
        }
        ctx.redirect('/')
    })
    

    In your case, you may want to assign ctx.session.user = userObject, then when logging a user out, reassign to ctx.session.user = null.