0.14.3 • Published 5 months ago

@peersyst/auth-module v0.14.3

Weekly downloads
-
License
-
Repository
-
Last release
5 months ago

Description

Nest framework TypeScript base auth module.

Installation

$ npm install --save @peersyst/auth-module

How to use it

Base auth module (no 3rd party logins or 2fa)

  • Import and register AuthModule in AppModule
import { AuthModule } from "@peersyst/auth-module";

@Module({
    imports: [
        ConfigModule.forRoot(...),
        TypeOrmModule.forRootAsync(...),
        UserModule,
        AuthModule.register(UserModule, ConfigModule, ConfigService, {}),
    ],
})
export class AppModule {}
  • UserModule should export a provider named UserService
@Module({
    imports: [
        TypeOrmModule.forFeature([User]),
    ],
    providers: [MyUserService, { provide: "UserService", useClass: MyUserService }],
    controllers: [UserController],
    exports: [MyUserService, { provide: "UserService", useClass: MyUserService }, TypeOrmModule],
})
export class UserModule {}
  • Add configService configuration variables
export default (): any => ({
    server: {
        secretKey: process.env.APP_JWT_KEY, ...
    },
});
  • Add AuthErrorCode and AuthErrorBody to app ErrorCodes
import { HttpStatus } from "@nestjs/common";
import { AuthErrorCode, AuthErrorBody } from "@peersyst/auth-module";

// Define app error codes
enum AppErrorCode {}

export const ErrorCode = { ...AppErrorCode, ...AuthErrorCode };
export type ErrorCodeType = AppErrorCode | AuthErrorCode;

export const ErrorBody: { [code in ErrorCodeType]: { statusCode: HttpStatus; message: string } } = {
    // Define app error code bodies
    ...AuthErrorBody,
};
  • Implement AuthUserI for User entity
import { AuthUserI, UserType } from "@peersyst/auth-module";

@Entity("user")
export class User implements AuthUserI {...}
  • Implement AuthUserServiceI for UserService
import { AuthUserServiceI } from "@peersyst/auth-module";

@Injectable()
export class UserService implements AuthUserServiceI {...}
  • Use authenticated in controllers
import { Authenticated } from "@peersyst/auth-module";

@ApiTags("user")
@Controller("users")
@ApiErrorDecorators()
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Authenticated(UserType.ADMIN)
    @Post("create")
    @ApiOperation({ summary: "Create user" })
    async create(@Body() createUserRequestDto: CreateUserRequest): Promise<UserDto> {
        return this.userService.createUser(createUserRequestDto);
    }

    @Authenticated()
    @Get("info")
    @ApiOperation({ summary: "Show user info" })
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    async info(@Request() req): Promise<UserDto> {
        return this.userService.findById(req.user.id);
    }
}

Add Google login

  • Set googleAuth to true in register module
AuthModule.register(UserModule, ConfigModule, ConfigService, {
    googleAuth: true,
}),
  • Add configService configuration variables
export default (): any => ({
    server: {
        secretKey: process.env.APP_JWT_KEY,
        frontUrl: process.env.FRONT_URL,
        baseUrl: process.env.BASE_URL,
    },
    googleAuth: {
        clientId: process.env.GOOGLE_AUTH_CLIENT_ID,
        clientSecret: process.env.GOOGLE_AUTH_CLIENT_SECRET,
    },
});
  • Implement AuthGoogleUserI for User entity
import { AuthUserI, AuthGoogleUserI, UserType } from "@peersyst/auth-module";

@Entity("user")
export class User implements AuthUserI, AuthGoogleUserI {...}
  • Implement ThirdPartyUserServiceI for UserService
import { AuthUserServiceI, ThirdPartyUserServiceI } from "@peersyst/auth-module";

@Injectable()
export class UserService implements AuthUserServiceI, ThirdPartyUserServiceI {...}

Add Twitter login

  • Set twitterAuth to true in register module
AuthModule.register(UserModule, ConfigModule, ConfigService, {
    twitterAuth: true,
}),
  • Add configService configuration variables
export default (): any => ({
    server: {
        secretKey: process.env.APP_JWT_KEY,
        frontUrl: process.env.FRONT_URL,
        baseUrl: process.env.BASE_URL,
    },
    twitterAuth: {
        apiKey: process.env.TWITTER_API_KEY,
        apiKeySecret: process.env.TWITTER_API_KEY_SECRET,
    },
});
  • Implement AuthTwitterUserI for User entity
import { AuthUserI, AuthTwitterUserI, UserType } from "@peersyst/auth-module";

@Entity("user")
export class User implements AuthUserI, AuthTwitterUserI {...}
  • Implement ThirdPartyUserServiceI for UserService
import { AuthUserServiceI, ThirdPartyUserServiceI } from "@peersyst/auth-module";

@Injectable()
export class UserService implements AuthUserServiceI, ThirdPartyUserServiceI {...}

Add Validate email

  • Set validateEmail to true in register module
AuthModule.register(UserModule, ConfigModule, ConfigService, {
    validateEmail: true,
}),
  • Implement ValidateEmailUserServiceI for UserService
import { AuthUserServiceI, ValidateEmailUserServiceI } from "@peersyst/auth-module";

@Injectable()
export class UserService implements AuthUserServiceI, ValidateEmailUserServiceI {...}
  • When you either create or register a user an email verification token should be created and sent:
import { AuthUserServiceI, ValidateEmailUserServiceI, TokenService } from "@peersyst/auth-module";

@Injectable()
export class UserService implements AuthUserServiceI, ValidateEmailUserServiceI {
    constructor(
        @InjectRepository(User) private readonly userRepository: Repository<User>,
        @Inject(NotificationService) private readonly notificationService: NotificationService,
        @Inject(ValidateEmailService) private readonly validateEmailService: ValidateEmailService,
    ) {}
    
    async registerUser(registerUserRequest: RegisterUserRequest): Promise<PrivateUserDto> {
        const entity = await this.userRepository.save(registerUserRequest);
        const user = PrivateUserDto.fromEntity(entity);
        const token = await this.validateEmailService.createEmailVerificationToken(user.id);
        await this.notificationService.sendEmailVerificationMessage(createUserRequest.email, token);
    }
}
  • Create entity in your entities folder with name VerifyEmailToken
export { VerifyEmailToken } from "@peersyst/auth-module";

Add Recover Password

  • Set recoverPassword to true in register module and indicate NotificationModule.
AuthModule.register(UserModule, ConfigModule, ConfigService, {
    recoverPassword: true,
    NotificationModule,
}),

NotificationModule should export a provider named NotificationService (v8 onwards):

@Module({
    providers: [NotificationService, { provide: "NotificationService", useClass: NotificationService }],
    exports: [NotificationService, { provide: "NotificationService", useClass: NotificationService }],
})
export class NotificationModule {}
  • Implement RecoverNotificationServiceI for NotificationService
import { RecoverNotificationServiceI } from "@peersyst/auth-module";

@Injectable()
export class NotificationService implements RecoverNotificationServiceI {...}
  • Implement RecoverPasswordUserServiceI for UserService
import { AuthUserServiceI, RecoverPasswordUserServiceI } from "@peersyst/auth-module";

@Injectable()
export class UserService implements AuthUserServiceI, RecoverPasswordUserServiceI {...}
  • Create entity in your entities folder with name ResetToken
export { ResetToken } from "@peersyst/auth-module";

Add 2 Factor Authenticated (work in progress)

  • Set twoFA to true in register module
AuthModule.register(UserModule, ConfigModule, ConfigService, {
    twoFA: true,
}),
  • Implement Auth2FAUserI for User entity
import { AuthUserI, Auth2FAUserI, UserType } from "@peersyst/auth-module";

@Entity("user")
export class User implements AuthUserI, Auth2FAUserI {...}

License

Nest is MIT licensed.

0.13.2

8 months ago

0.13.3

7 months ago

0.14.0

5 months ago

0.14.1

5 months ago

0.14.2

5 months ago

0.14.3

5 months ago

0.13.1

11 months ago

0.13.0

1 year ago

0.12.76

1 year ago

0.12.75

1 year ago

0.12.74

1 year ago

0.12.73

1 year ago

0.12.72

1 year ago

0.12.71

1 year ago

0.12.70

1 year ago

0.12.69

1 year ago

0.12.68

1 year ago

0.12.67

2 years ago

0.12.65

2 years ago

0.12.64

2 years ago

0.12.61

2 years ago

0.12.55

2 years ago

0.12.50

2 years ago

0.12.49

2 years ago

0.12.40

2 years ago

0.12.15

2 years ago

0.12.0

2 years ago

0.11.36

2 years ago

0.11.35

2 years ago

0.11.34

2 years ago

0.11.33

2 years ago

0.11.32

2 years ago

0.11.31

2 years ago

0.11.30

2 years ago

0.11.29

2 years ago

0.11.28

2 years ago

0.11.20

2 years ago

0.11.19

2 years ago

0.11.13

2 years ago

0.11.12

2 years ago

0.11.11

2 years ago

0.11.10

2 years ago

0.11.9

2 years ago

0.11.8

2 years ago

0.11.7

2 years ago

0.11.6

2 years ago

0.11.5

2 years ago

0.11.4

2 years ago

0.11.3

2 years ago

0.11.2

2 years ago

0.11.1

2 years ago

0.11.0

2 years ago

0.10.0

2 years ago

0.9.2

2 years ago

0.9.1

2 years ago

0.9.0

2 years ago

0.8.8

2 years ago

0.8.7

2 years ago

0.8.6

2 years ago

0.8.5

2 years ago

0.8.4

2 years ago

0.8.3

2 years ago

0.8.2

2 years ago

0.8.1

2 years ago

0.8.0

2 years ago

0.7.0

2 years ago

0.1.0

2 years ago