1.3.14 • Published 1 year ago
@devts/nestjs-auth v1.3.14
nestjs-auth
- A way to apply Oauth2 Auth module to nestjs
more type-safe than passport
install only once
Installation
npm i @devts/nestjs-auth
Example
import { HttpException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Google, StrategyException } from '@devts/nestjs-auth';
interface GoogleProfile {
username: string;
email: string;
}
@Injectable()
export class GoogleStrategy extends Google.AbstractStrategy<
'user',
"emails" | "profile"
GoogleProfile
> {
constructor(configService: ConfigService) {
super({
client_id: configService.get('CLIENT_ID'),
client_secret: configService.get('CLIENT_SECRET'),
redirect_uri: configService.get('OAUTH_CALLBACK'),
access_type: "offline",
prompt: "consent",
scope: ['email', 'profile'],
key: 'user',
});
}
protected throw({
statusCode = 401,
message = ''
}:StrategyException): never {
throw new HttpException(statusCode, message);
}
validate(
identity: Google.IdToken<'email' | 'profile'>,
credentials: Google.Credentials,
): boolean {
return true;
}
transform(
identity: Google.IdToken<'email' | 'profile'>,
): GoogleProfile {
const { name, email } = identity;
return { username: name, emails };
}
}
// in module
@Module({
providers: [
{
provide: 'GoogleStrategy',
useClass: GoogleStrategy,
},
],
})
export class AppModule {}
import { AuthGuard } from '@devts/nestjs-auth';
import { Req } from '@nestjs/common';
import type { Request } from 'express';
@Controller('auth')
export class AuthController {
// Inject decorator get "GoogleStrategy" token
@Get('sign-in')
@UseGuards(AuthGuard('GoogleStrategy'))
signIn() {
return;
}
@Get('YOUR REDIRECT PATH')
@UseGuards(AuthGuard('GoogleStrategy'))
callback(@Req() req: Request) {
return (req as any).user; // you can get data from request[key]
}
}
1.3.14
1 year ago
1.3.10
1 year ago
1.3.13
1 year ago
1.3.11
1 year ago
1.3.12
1 year ago
1.3.9
1 year ago
1.3.8
1 year ago
1.3.7
1 year ago
1.3.6
1 year ago
1.3.5
1 year ago
1.3.4
1 year ago
1.3.3
1 year ago
1.3.2
1 year ago
1.3.1
1 year ago
1.3.0
1 year ago
1.2.4
1 year ago
1.2.3
1 year ago
1.2.2
1 year ago
1.2.1
1 year ago
1.2.0
1 year ago
1.1.0
1 year ago
1.0.5
1 year ago
1.0.4
1 year ago
1.0.3
1 year ago
1.0.2
1 year ago
1.0.1
1 year ago
1.0.0
1 year ago