📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Developed a system refresh tokens.
Yevhenii Kulisidi2926a3fe4d59
diff --git a/.env.example b/.env.exampleindex 97d33bfe5..4bfb7a80d 100644--- a/.env.example+++ b/.env.example@@ -5,8 +5,9 @@ TWO_FACTOR_AUTHENTICATION_APP_NAME=Swetrix# AppCLIENT_URL='http://localhost:3000'-# JWT Access Token+# JWT TokensJWT_ACCESS_TOKEN_SECRET='jwt-access-token-secret'+JWT_REFRESH_TOKEN_SECRET='jwt-refresh-token-secret'# DatabaseMYSQL_HOST=localhostdiff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex cf72235f0..86f632c4f 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -25,7 +25,7 @@ import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'import { checkRateLimit } from 'src/common/utils'import { UserService } from 'src/user/user.service'import { AuthService } from './auth.service'-import { Public, CurrentUserId } from './decorators'+import { Public, CurrentUserId, CurrentUser } from './decorators'import {RegisterResponseDto,RegisterRequestDto,@@ -39,7 +39,7 @@ import {ConfirmChangeEmailDto,RequestChangeEmailDto,} from './dtos'-import { JwtAccessTokenGuard } from './guards'+import { JwtAccessTokenGuard, JwtRefreshTokenGuard } from './guards'@ApiTags('Auth')@Controller({ path: 'auth', version: '1' })@@ -96,11 +96,12 @@ export class AuthController {body.password,)- const accessToken = await this.authService.generateJwtAccessToken(- newUser.id,- )+ const jwtTokens = await this.authService.generateJwtTokens(newUser.id)- return { accessToken }+ return {+ accessToken: jwtTokens.accessToken,+ refreshToken: jwtTokens.refreshToken,+ }}@ApiOperation({ summary: 'Login a user' })@@ -130,12 +131,15 @@ export class AuthController {await this.authService.sendTelegramNotification(user.id, headers, ip)- const accessToken = await this.authService.generateJwtAccessToken(+ const jwtTokens = await this.authService.generateJwtTokens(user.id,user.isTwoFactorAuthenticationEnabled,)- return { accessToken }+ return {+ accessToken: jwtTokens.accessToken,+ refreshToken: jwtTokens.refreshToken,+ }}@ApiOperation({ summary: 'Verify a user email' })@@ -320,4 +324,40 @@ export class AuthController {await this.authService.confirmChangeEmail(actionToken)}++ @ApiOperation({ summary: 'Refresh a token' })+ @ApiOkResponse({+ description: 'Token refreshed',+ })+ @Public()+ @UseGuards(JwtRefreshTokenGuard)+ @Post('refresh-token')+ @HttpCode(200)+ public async refreshToken(+ @CurrentUserId() userId: string,+ @CurrentUser('refreshToken') refreshToken: string,+ @I18n() i18n: I18nContext,+ ): Promise<{ accessToken: string }> {+ const user = await this.userService.findUserById(userId)++ if (!user) {+ throw new UnauthorizedException()+ }++ const isRefreshTokenValid = await this.authService.checkRefreshToken(+ user.id,+ refreshToken,+ )++ if (!isRefreshTokenValid) {+ throw new ConflictException(i18n.t('auth.invalidRefreshToken'))+ }++ const accessToken = await this.authService.generateJwtAccessToken(+ user.id,+ user.isTwoFactorAuthenticationEnabled,+ )++ return { accessToken }+ }}diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.tsindex 71a0f3c66..31f7b74ae 100644--- a/src/auth/auth.module.ts+++ b/src/auth/auth.module.ts@@ -6,7 +6,7 @@ import { MailerModule } from 'src/mailer/mailer.module'import { UserModule } from 'src/user/user.module'import { AuthController } from './auth.controller'import { AuthService } from './auth.service'-import { JwtAccessTokenStrategy } from './strategies'+import { JwtAccessTokenStrategy, JwtRefreshTokenStrategy } from './strategies'@Module({imports: [@@ -18,6 +18,6 @@ import { JwtAccessTokenStrategy } from './strategies'ActionTokensModule,],controllers: [AuthController],- providers: [AuthService, JwtAccessTokenStrategy],+ providers: [AuthService, JwtAccessTokenStrategy, JwtRefreshTokenStrategy],})export class AuthModule {}diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex c2804109d..b2343ae4d 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -337,4 +337,49 @@ export class AuthService {LetterTemplate.MailAddressHadChanged,)}++ private async generateJwtRefreshToken(+ userId: string,+ isSecondFactorAuthenticated = false,+ ) {+ const refreshToken = await this.jwtService.signAsync(+ {+ sub: userId,+ isSecondFactorAuthenticated,+ },+ {+ algorithm: 'HS256',+ expiresIn: 60 * 60 * 24 * 30,+ secret: this.configService.get('JWT_REFRESH_TOKEN_SECRET'),+ },+ )++ await this.userService.saveRefreshToken(userId, refreshToken)++ return refreshToken+ }++ public async checkRefreshToken(+ userId: string,+ refreshToken: string,+ ): Promise<boolean> {+ const token = await this.userService.findRefreshToken(userId, refreshToken)+ return Boolean(token)+ }++ public async generateJwtTokens(+ userId: string,+ isSecondFactorAuthenticated = false,+ ) {+ const accessToken = await this.generateJwtAccessToken(+ userId,+ isSecondFactorAuthenticated,+ )+ const refreshToken = await this.generateJwtRefreshToken(+ userId,+ isSecondFactorAuthenticated,+ )++ return { accessToken, refreshToken }+ }}diff --git a/src/auth/decorators/current-user.decorator.ts b/src/auth/decorators/current-user.decorator.tsnew file mode 100644index 000000000..0b5e9dac0--- /dev/null+++ b/src/auth/decorators/current-user.decorator.ts@@ -0,0 +1,14 @@+import { createParamDecorator, ExecutionContext } from '@nestjs/common'+import { IJwtRefreshTokenPayload } from '../interfaces'++export const CurrentUser = createParamDecorator(+ (+ data: keyof IJwtRefreshTokenPayload | undefined,+ context: ExecutionContext,+ ) => {+ const request = context.switchToHttp().getRequest()+ const user = request.user++ return data ? user && user[data] : user+ },+)diff --git a/src/auth/decorators/index.ts b/src/auth/decorators/index.tsindex c7ed42c34..7a764cdbf 100644--- a/src/auth/decorators/index.ts+++ b/src/auth/decorators/index.ts@@ -1,3 +1,4 @@export * from './validators'export * from './current-user-id.decorator'export * from './public.decorator'+export * from './current-user.decorator'diff --git a/src/auth/dtos/login.dto.ts b/src/auth/dtos/login.dto.tsindex 54fe0421f..0e16aaa90 100644--- a/src/auth/dtos/login.dto.ts+++ b/src/auth/dtos/login.dto.ts@@ -7,4 +7,5 @@ export class LoginRequestDto extends OmitType(RegisterRequestDto, [export class LoginResponseDto extends PickType(RegisterResponseDto, ['accessToken',+ 'refreshToken',] as const) {}diff --git a/src/auth/dtos/register.dto.ts b/src/auth/dtos/register.dto.tsindex 3ce6ca9dc..93f0da119 100644--- a/src/auth/dtos/register.dto.ts+++ b/src/auth/dtos/register.dto.ts@@ -35,4 +35,9 @@ export class RegisterResponseDto {description: 'Access token (JWT)',})public readonly accessToken: string++ @ApiProperty({+ description: 'Refresh token (JWT)',+ })+ public readonly refreshToken: string}diff --git a/src/auth/guards/index.ts b/src/auth/guards/index.tsindex 7f84f519e..fce21343f 100644--- a/src/auth/guards/index.ts+++ b/src/auth/guards/index.ts@@ -1 +1,2 @@-export * from './access-token.guard'+export * from './jwt-access-token.guard'+export * from './jwt-refresh-token.guard'diff --git a/src/auth/guards/access-token.guard.ts b/src/auth/guards/jwt-access-token.guard.tssimilarity index 100%rename from src/auth/guards/access-token.guard.tsrename to src/auth/guards/jwt-access-token.guard.tsdiff --git a/src/auth/guards/jwt-refresh-token.guard.ts b/src/auth/guards/jwt-refresh-token.guard.tsnew file mode 100644index 000000000..062deaec0--- /dev/null+++ b/src/auth/guards/jwt-refresh-token.guard.ts@@ -0,0 +1,7 @@+import { AuthGuard } from '@nestjs/passport'++export class JwtRefreshTokenGuard extends AuthGuard('jwt-refresh-token') {+ constructor() {+ super()+ }+}diff --git a/src/auth/interfaces/jwt-payload.interface.ts b/src/auth/interfaces/jwt-payload.interface.tsindex a38bd4838..ed0c28c74 100644--- a/src/auth/interfaces/jwt-payload.interface.ts+++ b/src/auth/interfaces/jwt-payload.interface.ts@@ -2,3 +2,7 @@ export interface IJwtPayload {sub: stringisSecondFactorAuthenticated: boolean}++export interface IJwtRefreshTokenPayload extends IJwtPayload {+ refreshToken: string+}diff --git a/src/auth/strategies/index.ts b/src/auth/strategies/index.tsindex 06ba33043..20e4bbdce 100644--- a/src/auth/strategies/index.ts+++ b/src/auth/strategies/index.ts@@ -1 +1,2 @@-export * from './access-token.strategy'+export * from './jwt-access-token.strategy'+export * from './jwt-refresh-token.strategy'diff --git a/src/auth/strategies/access-token.strategy.ts b/src/auth/strategies/jwt-access-token.strategy.tssimilarity index 100%rename from src/auth/strategies/access-token.strategy.tsrename to src/auth/strategies/jwt-access-token.strategy.tsdiff --git a/src/auth/strategies/jwt-refresh-token.strategy.ts b/src/auth/strategies/jwt-refresh-token.strategy.tsnew file mode 100644index 000000000..ecb72b03b--- /dev/null+++ b/src/auth/strategies/jwt-refresh-token.strategy.ts@@ -0,0 +1,28 @@+import { ForbiddenException, Injectable } from '@nestjs/common'+import { ConfigService } from '@nestjs/config'+import { PassportStrategy } from '@nestjs/passport'+import { Request } from 'express'+import { ExtractJwt, Strategy } from 'passport-jwt'+import { IJwtPayload } from '../interfaces'++@Injectable()+export class JwtRefreshTokenStrategy extends PassportStrategy(+ Strategy,+ 'jwt-refresh-token',+) {+ constructor(public readonly configService: ConfigService) {+ super({+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),+ secretOrKey: configService.get('JWT_REFRESH_TOKEN_SECRET'),+ passReqToCallback: true,+ })+ }++ public validate(request: Request, payload: IJwtPayload) {+ const refreshToken = request.headers.authorization.split(' ')[1]++ if (!refreshToken) throw new ForbiddenException()++ return { ...payload, refreshToken }+ }+}diff --git a/src/i18n/en/auth.json b/src/i18n/en/auth.jsonindex 556e909c5..5f090f3b4 100644--- a/src/i18n/en/auth.json+++ b/src/i18n/en/auth.json@@ -8,5 +8,6 @@"emailAlreadyVerified": "Email already verified.","maxEmailRequestsReached": "Maximum number of email requests reached.","emailAlreadyTaken": "Email already taken.",- "invalidChangeEmailToken": "Invalid change email token."+ "invalidChangeEmailToken": "Invalid change email token.",+ "invalidRefreshToken": "Invalid refresh token."}diff --git a/src/user/entities/refresh-token.entity.ts b/src/user/entities/refresh-token.entity.tsnew file mode 100644index 000000000..f97e5218a--- /dev/null+++ b/src/user/entities/refresh-token.entity.ts@@ -0,0 +1,26 @@+import {+ Column,+ Entity,+ JoinColumn,+ ManyToOne,+ PrimaryGeneratedColumn,+} from 'typeorm'+import { User } from './user.entity'++@Entity()+export class RefreshToken {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @Column('varchar', { length: 36 })+ userId: string++ @Column('text')+ refreshToken: string++ @ManyToOne(() => User, user => user.refreshTokens, {+ onDelete: 'CASCADE',+ })+ @JoinColumn()+ user: User+}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex 8741185bf..89a73bd8c 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -13,6 +13,7 @@ import { Extension } from '../../marketplace/extensions/entities/extension.entitimport { ExtensionToUser } from '../../marketplace/extensions/entities/extension-to-user.entity'import { Comment } from '../../marketplace/comments/entities/comment.entity'import { Complaint } from '../../marketplace/complaints/entities/complaint.entity'+import { RefreshToken } from './refresh-token.entity'export enum PlanCode {free = 'free',freelancer = 'freelancer',@@ -221,4 +222,8 @@ export class User {@OneToMany(() => Complaint, complaint => complaint.user)@JoinTable()complaints: Complaint[]++ @OneToMany(() => RefreshToken, refreshToken => refreshToken.user)+ @JoinTable()+ refreshTokens: RefreshToken[]}diff --git a/src/user/user.module.ts b/src/user/user.module.tsindex ff84bbd59..6a7b2e79d 100644--- a/src/user/user.module.ts+++ b/src/user/user.module.ts@@ -9,10 +9,11 @@ import { MailerModule } from '../mailer/mailer.module'import { OldAuthModule } from '../old-auth/auth.module'import { AppLoggerModule } from '../logger/logger.module'import { ProjectModule } from '../project/project.module'+import { RefreshToken } from './entities/refresh-token.entity'@Module({imports: [- TypeOrmModule.forFeature([User]),+ TypeOrmModule.forFeature([User, RefreshToken]),ActionTokensModule,MailerModule,forwardRef(() => OldAuthModule),diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex a6097d69c..8df3251b0 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -8,12 +8,15 @@ import * as _omit from 'lodash/omit'import { Pagination, PaginationOptionsInterface } from '../common/pagination'import { User } from './entities/user.entity'import { UserProfileDTO } from './dto/user.dto'+import { RefreshToken } from './entities/refresh-token.entity'@Injectable()export class UserService {constructor(@InjectRepository(User)private usersRepository: Repository<User>,+ @InjectRepository(RefreshToken)+ private readonly refreshTokenRepository: Repository<RefreshToken>,) {}async create(userDTO: UserProfileDTO | User): Promise<User> {@@ -154,4 +157,20 @@ export class UserService {public async updateUser(id: string, user: Partial<Omit<User, 'id'>>) {return await this.usersRepository.update({ id }, user)}++ public async saveRefreshToken(userId: string, refreshToken: string) {+ return await this.refreshTokenRepository.save({+ userId,+ refreshToken,+ })+ }++ public async findRefreshToken(userId: string, refreshToken: string) {+ return await this.refreshTokenRepository.findOne({+ where: {+ userId,+ refreshToken,+ },+ })+ }}