Skip to content

Instantly share code, notes, and snippets.

@ospfranco
Last active April 20, 2018 08:19
Show Gist options
  • Save ospfranco/438efc8264722ae5950ffe1ee1034ef0 to your computer and use it in GitHub Desktop.
Save ospfranco/438efc8264722ae5950ffe1ee1034ef0 to your computer and use it in GitHub Desktop.
import { Module, MiddlewaresConsumer, NestModule, RequestMethod } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { GraphQLModule, GraphQLFactory } from '@nestjs/graphql';
import { ApiModule } from './module';
import ormConfig from './ormconfig';
import { AuthModule } from './module/auth/auth.module';
import { AuthMiddleware } from './module/auth/auth.middleware';
@Module({
imports: [
TypeOrmModule.forRoot(ormConfig as any),
GraphQLModule,
ApiModule,
AuthModule
]
})
export class ApplicationModule implements NestModule {
constructor(private readonly graphQLFactory: GraphQLFactory) {}
public configure(consumer: MiddlewaresConsumer) {
const typeDefs = this.graphQLFactory.mergeTypesByPaths('./**/*.graphql');
const schema = this.graphQLFactory.createSchema({ typeDefs });
consumer
.apply(graphqlExpress((req) => ({ schema, rootValue: req, pretty: true })))
.forRoutes({ path: '/graphql', method: RequestMethod.ALL })
.apply(AuthMiddleware).forRoutes({
path: '/graphql',
method: RequestMethod.ALL
})
.apply(graphiqlExpress({endpointURL: '/graphql'}))
.forRoutes({path: '/graphiql', method: RequestMethod. ALL});
}
}
import { Guard, CanActivate, ExecutionContext, ReflectMetadata, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
@Guard()
export class AuthGuard implements CanActivate {
public async canActivate(req: Request, context: ExecutionContext): Promise<boolean> {
const authToken = req.headers['x-auth-token'];
if (!authToken) {
return false;
}
const user = (req as any).user;
console.debug(user);
// const tokenObj = await this.authService.checkToken((authToken as string));
// if (!tokenObj || tokenObj!.user!.role !== 'SUPERADMIN') {
// return false;
// }
return true;
}
}
import {Middleware, NestMiddleware} from '@nestjs/common';
import { Request, Response } from 'express';
import { AuthService } from '../auth/auth.service';
// express converts headers to lowercase
const AUTH = 'x-auth-token';
// The middleware will set req.user if a valid token was found
// it won't block anything, this is up to the guards
@Middleware()
export class AuthMiddleware implements NestMiddleware {
constructor(private readonly authService: AuthService) { }
public resolve() {
return async (req: Request, res: Response, next) => {
const authToken: string = (req.headers[AUTH] as string);
if (authToken) {
const tokenObj = await this.authService.checkToken(authToken);
if (tokenObj != null) {
// set the user object on the request object
(req as any).user = tokenObj.user;
}
}
(req as any).somethingDumb = 'FOO'; // <- This also does not get inserted into the request once it reaches the guard
// call next function
next();
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment