We use cookies to enhance your experience on the site
CodeWorlds

Security Best Practices - protection against barbarians

Tribute guardian! Consul Caesar.js knows that the frontier is full of hostile barbarians wanting to steal our tributes. It's time to learn the best methods of defense against attacks!

Authentication & Authorization

1// JWT Strategy
2@Injectable()
3export class JwtStrategy extends PassportStrategy(Strategy) {
4 constructor() {
5 super({
6 jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
7 ignoreExpiration: false,
8 secretOrKey: process.env.JWT_SECRET,
9 });
10 }
11
12 async validate(payload: any) {
13 return { userId: payload.sub, username: payload.username };
14 }
15}
16
17// Password hashing
18@Injectable()
19export class CryptoService {
20 async hashPassword(password: string): Promise<string> {
21 const saltRounds = 12;
22 return bcrypt.hash(password, saltRounds);
23 }
24
25 async validatePassword(password: string, hash: string): Promise<boolean> {
26 return bcrypt.compare(password, hash);
27 }
28}

Input Validation

1// DTO with validation
2export class CreateLegionaryDto {
3 @IsString()
4 @Length(2, 50)
5 @Matches(/^[a-zA-Z\s]+$/, { message: 'Name can only contain letters' })
6 name: string;
7
8 @IsEmail()
9 email: string;
10
11 @IsString()
12 @MinLength(8)
13 @Matches(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/, {
14 message: 'Password must contain uppercase, lowercase, number and special character'
15 })
16 password: string;
17}
Go to CodeWorlds