#User Services in cookieExtractor function.

10 messages · Page 1 of 1 (latest)

fast sigil
#

Hello
I want to create a new token if a provided one is expired.
For this i use cookieExtractor :

const cookieExtractor = (req: Request) => {
    let token = null;
    if (req && req.headers && req.headers.authorization) {
        token = req.headers.authorization.split(" ")[1];
    }

    console.log(token)
    jwt.verify(
        token,
        `${process.env.SECRET}`,
        { ignoreExpiration: false, algorithms: ['HS256'] },
        (error, decoded) => {
          if (error instanceof TokenExpiredError) {
            // create new token
          }
        }
    )

    return token;
}

And function that creates new token by refresh one:

async function refresh(refreshToken: string) {
    if (!refreshToken) {
        throw new BadRequestException('refresh token is not valid');
    }

    const userData = await this.tokenService.validateRefreshToken(refreshToken);
    const tokenFromDb = this.tokenService.findToken(refreshToken);
    if (!userData && !tokenFromDb) {
        throw new UnauthorizedException();
    }

    const user = await this.userService.findOneById(userData.userId);
    console.log(user.toObject({versionKey: false}));
    return (await this.tokenService.generateToken(user.toObject({versionKey: false}))).accessToken
}

So the problem is that i can't use tokenService and userService in refresh function because it outside of

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) ...

So how can i reach Services method?

#

the whole code:

#
const cookieExtractor = (req: Request) => {
    let token = null;
    if (req && req.headers && req.headers.authorization) {
        token = req.headers.authorization.split(" ")[1];
    }

    console.log(token)
    jwt.verify(
        token,
        `${process.env.SECRET}`,
        { ignoreExpiration: false, algorithms: ['HS256'] },
        (error, decoded) => {
                    if (error instanceof TokenExpiredError) {
                        // create new token
                    }
                }
    )

    return token;
}

async function refresh(refreshToken: string) {
    if (!refreshToken) {
        throw new BadRequestException('refresh token is not valid');
    }

    const userData = await this.tokenService.validateRefreshToken(refreshToken);
    const tokenFromDb = this.tokenService.findToken(refreshToken);
    if (!userData && !tokenFromDb) {
        throw new UnauthorizedException();
    }

    const user = await this.userService.findOneById(userData.userId);
    console.log(user.toObject({versionKey: false}));
    return (await this.tokenService.generateToken(user.toObject({versionKey: false}))).accessToken
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(private tokenService: TokenService, private userService: UsersService) {
        super({
           ...
        });
    }

    async validate(req: Request, payload: UserDto) {
        console.log('validate');
        return payload;
    }
}
unkempt spire
#

to my knowledge if a jwt that's passed into the request has expired or is invalid it will automatically throw an error I believe, there might be some work arounds to this, but I could be wrong in that sense

#

what I suggest to do is create a verifySession() or validateToken() method that basically checks if your database has a refresh token for x user

#

which instead checks the refresh token and sees if that has expired or not and if it is null you can request make a request to both the access and refresh token

#
  async getSession(id: string) {
    const user = await this.prisma.user.findUnique({
      where: { id: id },
      select: {
        id: true,
        username: true,
        firstName: true,
        lastName: true,
        email: true,
        image: true,
        session: true,
      },
    });

    if (!user.session || new Date(user.session.expires).getTime() < Date.now())
      return null;

    return {
      status: 'ok',
      statusCode: 200,
      data: {
        id: user.id,
        username: user.username,
        name: `${user.firstName} ${user.lastName}`,
        email: user.email,
        image: user.image,
      },
    };
  }
#

if the user's session is null you can take that null response and redirect the user accordingly

#

as for checking if it's expired/the same token, you could choose to redirect them like in the above response or you could validate that it's the same token and if it is expired you can call your auth service to return you new access/refresh tokens

#

keep in mind this is my own personal method of doing it and there many others