npm package: @nestjs-hybrid-auth/twitter
Description: NestJS twitter authentication using passport
Author: Manish Jangir
Latest version: 1.0.0

# NestJS Twitter Authentication

Implement twitter authentication in your NestJS application.

## Prerequisites

`@nestjs-hybrid-auth/twitter` requires `express-session` as a peer dependency and configure it your nest instance if you haven't.

```bash
npm install express-session --save
```

OR

```bash
yarn add express-session
```

### In your main.ts file

```typescript
import * as session from 'express-session';

app.use(
  session({
    secret: 'my-secret',
    resave: false,
    saveUninitialized: false,
  })
);
```

## Install Actual Package

```bash
npm install @nestjs-hybrid-auth/twitter --save
```

OR

```bash
yarn add @nestjs-hybrid-auth/twitter
```

## How To Use?

The package exports mainly a [dynamic module](https://docs.nestjs.com/fundamentals/dynamic-modules) and [guard](https://docs.nestjs.com/guards). The module should be imported in your app.module.ts and guards should be used on the route handlers of any controller.

## Example Code For app.module.ts

### Simple static configuration

Want to jump directly to the [available options](#twitterauthmoduleoptions)?

If you just want to provide the static values or have them handy, pass them as options to the `forRoot` static method like below. The options object is type of `TwitterAuthModuleOptions`.

```typescript
import { TwitterAuthModule } from '@nestjs-hybrid-auth/twitter';

@Module({
  imports: [
    TwitterAuthModule.forRoot({
      consumerKey: process.env.CONSUMER_KEY,
      consumerSecret: process.env.CONSUMER_SECRET,
      callbackURL: process.env.CALLBACK_URL,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
```

### `useFactory` to get the ConfigService injected.

If you want to make use of nest's [ConfigModule](https://docs.nestjs.com/techniques/configuration#installation) to get the auth configuration for a provider from `.env` config files, use `forRootAsync` static method. The options to this method are typeof `TwitterAuthModuleAsyncOptions` which accepts a `useFactory` property. `useFactory` is a function which gets the instances injected whatever has been provided in `inject` array. You can use those instances to prepare and return the actual `TwitterAuthModuleOptions` object. ConfigService can be one of them as per your choice.

```typescript
import { TwitterAuthModule } from '@nestjs-hybrid-auth/twitter';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      expandVariables: true,
    }),
    TwitterAuthModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        consumerKey: configService.get('TWITTER_CLIENT_ID'),
        consumerSecret: configService.get('TWITTER_CLIENT_SECRET'),
        callbackURL: configService.get('TWITTER_CALLBACK_URL'),
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
```

### Use `useClass` to get your auth config from a class

If the `useFactory` makes your app module bloated with a lot of boilerplate code, you can `useClass` to provide an existing config provider class. The class must implement `TwitterAuthModuleOptionsFactory` interface and `createModuleOptions` method. This method should return `TwitterAuthModuleOptions` object. Similar to `useFactory`, whatever you provide in `inject` array, it will get injected in the constructor of your class. Follow the example:

**hybrid-auth.config.ts**

```typescript
import { ConfigService } from '@nestjs/config';
import {
  TwitterAuthModuleOptions,
  TwitterAuthModuleOptionsFactory,
} from '@nestjs-hybrid-auth/twitter';

@Injectable()
class HybridAuthConfig implements TwitterAuthModuleOptionsFactory {
  constructor(private configService: ConfigService) {}

  createModuleOptions(): TwitterAuthModuleOptions {
    return {
      consumerKey: this.configService.get('TWITTER_CLIENT_ID'),
      consumerSecret: this.configService.get('TWITTER_CLIENT_SECRET'),
      callbackURL: this.configService.get('TWITTER_CALLBACK_URL'),
    };
  }
}
```

**app.module.ts**

```typescript
import { TwitterAuthModule } from '@nestjs-hybrid-auth/twitter';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      expandVariables: true,
    }),
    TwitterAuthModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useClass: HybridAuthConfig,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
```

## Example Code For Controller

Once you have setup the module properly in module file, its time to configure your route handlers to make the user properly redirected to appropriate identity provider's login page. `@nestjs-hybrid-auth/twitter` provides a guard and result interface to make it enabled.

Each route will have two variants. One is to redirect to social login page and the other is to collect the response such as access/refresh tokens and user profile etc. The result will be attached to `Request` object's `hybridAuthResult` property as shown in the example below.

### app.controller.ts

```typescript
import { UseTwitterAuth, TwitterAuthResult } from '@nestjs-hybrid-auth/twitter';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @UseTwitterAuth()
  @Get('auth/twitter')
  loginWithTwitter() {
    return 'Login with Twitter';
  }

  @UseTwitterAuth()
  @Get('auth/twitter-login/callback')
  twitterCallback(@Request() req): Partial<TwitterAuthResult> {
    const result: TwitterAuthResult = req.hybridAuthResult;
    return {
      accessToken: result.accessToken,
      refreshToken: result.refreshToken,
      profile: result.profile,
    };
  }
}
```

## Exports

`@nestjs-hybrid-auth/twitter` exports various decorators, interfaces and methods.

### UseTwitterAuth

`UseTwitterAuth` is NestJS `Guard` which hijacks your nest request and redirects users to the appropriate login page of your configured identity provider (twitter in this case). The same guard can be used on `callback` route also as shown in the example above. In the callback route handler, the `req: Request` object will have a property `hybridAuthResult` which is an object of type `TwitterAuthResult`.

```typescript
@UseTwitterAuth(options: TwitterAuthGuardOptions)
@Get('auth/twitter')
loginWithTwitter() {
  return 'Login with Twitter';
}
```

### TwitterAuthGuardOptions

This is a simple object to be passed into `UseTwitterAuth` guard as shown in example above if you want to pass some extra parameters to query the twitter result. It can be left empty for default result.

### TwitterAuthModule

This is the dynamic module which must be imported in your app's main module with `forRoot` or `forRootAsync` static methods whichever suits your need. Both will return a [NestJS dynamic module](https://docs.nestjs.com/fundamentals/dynamic-modules).

```typescript
interface TwitterAuthModule {
  forRoot(options: TwitterAuthModuleOptions): DynamicModule;
  forRootAsync(options: TwitterAuthModuleAsyncOptions): DynamicModule;
}
```

### TwitterAuthModuleOptions

If you are configuring your module with `forRoot` static method, pass in the module options given below. They can be called the twitter passport strategy options also.

```typescript
interface TwitterAuthModuleOptions {
  consumerKey: string;
  consumerSecret: string;
  callbackURL: string;

  includeEmail?: boolean | undefined;
  includeStatus?: boolean | undefined;
  includeEntities?: boolean | undefined;

  requestTokenURL?: string | undefined;
  accessTokenURL?: string | undefined;
  userAuthorizationURL?: string | undefined;
  sessionKey?: string | undefined;

  forceLogin?: boolean | undefined;
  screenName?: string | undefined;

  userProfileURL?: string | undefined;
  skipExtendedUserProfile?: boolean | undefined;
}
```

### TwitterAuthModuleAsyncOptions

If you want to configure the `TwitterAuthModule` dynamically having the config or other services injected, pass in async options in the `forRootAsync` static method. Please refer to the example above for `useFactory` and `useClass` properties.

```typescript
interface TwitterAuthModuleAsyncOptions {
  useExisting?: Type<TwitterAuthModuleOptionsFactory>;
  useClass?: Type<TwitterAuthModuleOptionsFactory>;
  useFactory?: (
    ...args: any[]
  ) => Promise<TwitterAuthModuleOptions> | TwitterAuthModuleOptions;
  inject?: any[];
}
```

### TwitterAuthModuleOptionsFactory

```typescript
interface TwitterAuthModuleOptionsFactory {
  createModuleOptions():
    | Promise<TwitterAuthModuleOptions>
    | TwitterAuthModuleOptions;
}
```

## Have Issues?

If you still have trouble setting up the workflow properly, please file an issue at [Issues](https://github.com/mjangir/nestjs-hybrid-auth/issues) page.

## Maintainers

[Manish Jangir](https://github.com/mjangir)