Advertisement
Guest User

Untitled

a guest
Jan 6th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function superTokensMiddleware(
  2.     req: express.Request,
  3.     res: express.Response,
  4.     next: express.NextFunction
  5. ): Promise<void> {
  6.     try {
  7.         const cookies = parseCookies(req);
  8.         if (cookies.sAccessToken && cookies.sIdRefreshToken) {
  9.             req.session = await SuperTokens.getSession(req, res, false);
  10.             return next();
  11.         }
  12.         req.session = await SuperTokens.createNewSession(res, 0);
  13.         next();
  14.     } catch (err) {
  15.         if (SuperTokens.Error.isErrorFromAuth(err)) {
  16.             if (err.errType === SuperTokens.Error.GENERAL_ERROR) {
  17.                 next(err);
  18.             } else if (err.errType === SuperTokens.Error.UNAUTHORISED) {
  19.                 req.session = await SuperTokens.createNewSession(res, 0);
  20.                 next();
  21.             } else {
  22.                 try {
  23.                     req.session = await SuperTokens.refreshSession(req, res);
  24.                     next();
  25.                 } catch (e) {
  26.                     res.status(440).send(
  27.                         "Please call the refresh token endpoint"
  28.                     );
  29.                 }
  30.                 res.status(440).send("Please call the refresh token endpoint");
  31.             }
  32.         }
  33.  
  34.         if (err.errType === 2000) {
  35.             return res.redirect("/");
  36.         }
  37.         next(err);
  38.     }
  39. }
  40.  
  41. export const userCheckMiddleware = (req: Request, res: Response, next: Function) => {
  42.     if (req.session && req.session.getUserId() > 0) {
  43.         return next();
  44.     }
  45.     res.status(401).send("Unauthorised");
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement