@galaxy-stack/orbit-auth
Mô tả
Module xác thực cho Orbit với JWT support sử dụng thư viện jose và password hashing với Bun native API.
Tính năng chính
1. JWT Service
import { JwtService } from '@galaxy-stack/orbit-auth';
const jwt = new JwtService({
secret: 'your-secret-key',
expiresIn: '1h',
});
const token = await jwt.sign({ userId: 1, role: 'admin' });
const payload = await jwt.verify(token);
const decoded = jwt.decode(token);
2. Password Service
import { PasswordService } from '@galaxy-stack/orbit-auth';
const password = new PasswordService();
const hash = await password.hash('my-password');
const isValid = await password.verify('my-password', hash);
3. Auth Guard
import { AuthGuard, UseGuards } from '@galaxy-stack/orbit-auth';
@Controller('protected')
@UseGuards(AuthGuard)
class ProtectedController {
@Get()
getProtectedData() {
return { secret: 'data' };
}
}
Cấu hình Module
import { AuthModule } from '@galaxy-stack/orbit-auth';
@Module({
imports: [
AuthModule.forRoot({
jwt: {
secret: process.env.JWT_SECRET,
expiresIn: '7d',
},
password: {
algorithm: 'argon2id',
},
}),
],
})
class AppModule {}
Async Configuration
AuthModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
jwt: {
secret: config.get('JWT_SECRET'),
expiresIn: config.get('JWT_EXPIRES_IN'),
},
}),
})
JWT Options
interface JwtOptions {
secret: string;
publicKey?: string;
privateKey?: string;
algorithm?: string;
expiresIn?: string;
issuer?: string;
audience?: string;
}
Password Algorithms
argon2id (recommended)
argon2i
argon2d
bcrypt
Custom AuthGuard
import { AuthGuard as BaseAuthGuard, JwtService } from '@galaxy-stack/orbit-auth';
class CustomAuthGuard extends BaseAuthGuard {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = this.extractToken(request);
if (!token) return false;
try {
const payload = await this.jwtService.verify(token);
request.user = payload;
return true;
} catch {
return false;
}
}
}