Эх сурвалжийг харах

use id instead of email for jwt payload sub

Pouria Ezzati 1 жил өмнө
parent
commit
f6247d0b91

+ 6 - 1
server/passport.js

@@ -15,7 +15,12 @@ const jwtOptions = {
 passport.use(
   new JwtStrategy(jwtOptions, async (payload, done) => {
     try {
-      const user = await query.user.find({ email: payload.sub });
+      // 'sub' used to be the email address
+      // this check makes sure to invalidate old JWTs where the sub is still the email address
+      if (typeof payload.sub === "string") {
+        return done(null, false);
+      }
+      const user = await query.user.find({ id: payload.sub });
       if (!user) return done(null, false);
       return done(null, user, payload);
     } catch (err) {

+ 4 - 4
server/queries/user.queries.js

@@ -8,8 +8,8 @@ const knex = require("../knex");
 const env = require("../env");
 
 async function find(match) {
-  if ((match.email || match.apikey) && env.REDIS_ENABLED) {
-    const key = redis.key.user(match.email || match.apikey);
+  if ((match.id || match.apikey) && env.REDIS_ENABLED) {
+    const key = redis.key.user(match.id || match.apikey);
     const cachedUser = await redis.client.get(key);
     if (cachedUser) return JSON.parse(cachedUser);
   }
@@ -22,8 +22,8 @@ async function find(match) {
   const user = await query.first();
   
   if (user && env.REDIS_ENABLED) {
-    const emailKey = redis.key.user(user.email);
-    redis.client.set(emailKey, JSON.stringify(user), "EX", 60 * 15);
+    const idKey = redis.key.user(user.id);
+    redis.client.set(idKey, JSON.stringify(user), "EX", 60 * 15);
   
     if (user.apikey) {
       const apikeyKey = redis.key.user(user.apikey);

+ 3 - 3
server/redis.js

@@ -18,7 +18,7 @@ const key = {
   domain: (address) => `d-${address}`,
   stats: (link_id) => `s-${link_id}`,
   host: (address) => `h-${address}`,
-  user: (emailOrKey) => `u-${emailOrKey}`
+  user: (idOrKey) => `u-${idOrKey}`
 };
 
 const remove = {
@@ -37,8 +37,8 @@ const remove = {
   user: (user) => {
     if (!user) return;
     return Promise.all([
-      client.del(key.user(user.email)),
-      client.del(key.user(user.apikey))
+      client.del(key.user(user.id)),
+      client.del(key.user(user.apikey)),
     ]);
   }
 };

+ 1 - 2
server/utils/utils.js

@@ -29,8 +29,7 @@ function signToken(user) {
   return JWT.sign(
       {
         iss: "ApiAuth",
-        sub: user.email,
-        domain: user.domain || "",
+        sub: user.id,
         iat: parseInt((new Date().getTime() / 1000).toFixed(0)),
         exp: parseInt((addDays(new Date(), 7).getTime() / 1000).toFixed(0))
       },