How to use cookies - 10 common examples

To help you get started, we’ve selected a few cookies examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github abecms / abecms / src / server / routes / users / post / login.js View on Github external
// return res.status(401).json({ error: info });
      }
      var expires = moment().add(7, 'days').valueOf()
      var token = jwt.encode(
        {
          iss: user.id,
          exp: expires,
          username: user.username,
          name: user.name,
          email: user.email,
          role: user.role
        },
        secret
      )

      var cookies = new Cookies(req, res, {
        secure: config.cookie.secure
      })
      cookies.set('x-access-token', token)

      var username = ''
      if (user && user.username) {
        username = user.username
      }
      Manager.instance.events.activity.emit('activity', {
        operation: 'connect',
        post: '',
        user: username
      })
      res.redirect('/abe/editor/')
    })(req, res, next)
  })
github nrw / kanso-spine-todos / packages / duality / duality / core.js View on Github external
}
        }
    }
    // splats are available for rewriting match.to, but not accessible on
    // the request object (couchdb 1.1.x), storing in a separate variable
    // for now
    var splat = exports.rewriteSplat(match.from, url);
    var to = exports.replaceGroups(match.to, query, splat);
    var req = {
        method: method,
        query: query,
        headers: {},
        path: to.split('/'),
        client: true,
        initial_hit: utils.initial_hit,
        cookie: cookies.readBrowserCookies()
    };
    if (data) {
        req.form = data;
    }

    db.newUUID(100, function (err, uuid) {
        if (err) {
            return callback(err);
        }
        req.uuid = uuid;

        if (utils.userCtx) {
            req.userCtx = utils.userCtx;
            return callback(null, req);
        }
        else {
github caolan / blog / packages / duality / duality / core.js View on Github external
}
        }
    }
    // splats are available for rewriting match.to, but not accessible on
    // the request object (couchdb 1.1.x), storing in a separate variable
    // for now
    var splat = exports.rewriteSplat(match.from, url);
    var to = exports.replaceGroups(match.to, query, splat);
    var req = {
        method: method,
        query: query,
        headers: {},
        path: to.split('/'),
        client: true,
        initial_hit: utils.initial_hit,
        cookie: cookies.readBrowserCookies()
    };
    if (data) {
        req.form = data;
    }

    db.newUUID(100, function (err, uuid) {
        if (err) {
            return callback(err);
        }
        req.uuid = uuid;

        if (utils.userCtx) {
            req.userCtx = utils.userCtx;
            return callback(null, req);
        }
        else {
github caolan / blog / packages / duality / duality / core.js View on Github external
if (!(res instanceof Object)) {
        res = {code: 200, body: res};
    }
    else {
        res = exports.parseResponse(req, res);
    }
    events.emit('beforeResponseStart', info, req, res);
    events.emit('beforeResponseData', info, req, res, res.body || '');

    if (flashmessages) {
        res = flashmessages.updateResponse(req, res);
    } else {
        // set the baseURL cookie for the browser
        var baseURL = utils.getBaseURL(req);
        cookies.setResponseCookie(req, res, {
            name: 'baseURL',
            value : baseURL,
            path : baseURL
        });
    }
    req.response_received = true;
    return res;
};
github caolan / blog / packages / duality / duality / core.js View on Github external
start = function (res) {
        start_res = res;
        events.emit('beforeResponseStart', info, req, res);
        if (res.body) {
            events.emit('beforeResponseData', info, req, res, res.body);
        }
        if (flashmessages) {
            res = flashmessages.updateResponse(req, res);
        } else {
                // set the baseURL cookie for the browser
                var baseURL = utils.getBaseURL(req);
                cookies.setResponseCookie(req, res, {
                    name: 'baseURL',
                    value : baseURL,
                    path : baseURL
                });
        }
        _start(res);
    };
    var _send = send;
github jkettmann / universal-react-relay-starter-kit / server / graphql / sessionMiddleware.js View on Github external
function verifyToken(req, res, next) {
  const cookies = new Cookies(req, res, { keys: [process.env.COOKIE_SECRET] })
  const session = createUserSession(cookies)
  Object.assign(req, { session })

  if (!cookies.accessToken) {
    next()
    return
  }

  verifyAccessToken(cookies.accessToken)
    .then(() => next())
    .catch((err) => {
      // eslint-disable-next-line no-undef
      log(err)
      session.resetUser()
      next()
    })
github nuxt / nuxt-services-experimental / services / auth.js View on Github external
constructor(ctx) {
    super(ctx)
    const { ws, req } = ctx
    // this.$axios = $axios
    // this.$axios = $axios
    const cookies = Cookies(req)

    // Get jwt cookie
    const jwt = cookies.get('jwt')
    this.$axios.setToken(jwt, 'Bearer')
  }
github codejamninja / reactant / packages / base / src / init / server.js View on Github external
app.get('/*', async (req, res, next) => {
    const css = new Set();
    let context = {};
    try {
      context = await createWebStore({
        cookieJar: new NodeCookiesWrapper(new Cookies(req, res)),
        insertCss: (...styles) => {
          return styles.forEach(style => css.add(style._getCss()));
        },
        location: req.url
      });
      context.persistor = await new Promise(resolve => {
        const { store } = context;
        const persistor = persistStore(store, config.initialState, () => {
          return resolve(persistor);
        });
      });
      initialProps.context = context;
      initialProps.location = context.location;
      const appHtml = renderToString();
      // const appCss = renderToStaticMarkup(getStyleElement());
      const $ = cheerio.load(indexHtml);
github verdaccio / verdaccio / src / api / endpoint / api / user.ts View on Github external
token,
        });
      });
    }
  });

  route.delete('/-/user/token/*', function(req: $RequestExtend, res: Response, next: $NextFunctionVer): void {
    res.status(HTTP_STATUS.OK);
    next({
      ok: API_MESSAGE.LOGGED_OUT,
    });
  });

  // placeholder 'cause npm require to be authenticated to publish
  // we do not do any real authentication yet
  route.post('/_session', Cookies.express(), function(req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer): void {
    res.cookies.set('AuthSession', String(Math.random()), createSessionToken());

    next({
      ok: true,
      name: 'somebody',
      roles: [],
    });
  });
}
github pencilblue / pencilblue / test / include / http / middleware / index.spec.js View on Github external
it('should set the cookie when the flag setSessionCookie is set on the request object', function(done) {
            req.setSessionCookie = true;
            req.session = { uid: 'abc123' };
            sandbox.stub(this.pb.SessionHandler, 'getSessionCookie')
                .withArgs(req.session).returns();
            sandbox.stub(this.pb.log, 'error');
            sandbox.stub(Cookies.prototype, 'set')
                .withArgs(this.pb.SessionHandler.COOKIE_NAME, req.session.uid, sinon.match.any);
            var self = this;
            this.pb.Middleware.writeSessionCookie(req, res, function(err) {
                should(err).eql(undefined);
                self.pb.SessionHandler.getSessionCookie.calledOnce.should.eql(true);
                self.pb.log.error.called.should.eql(false);
                done();
            });
        });
    });