Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CatModule } from './cat/cat.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
url: process.env.DATABASE_URL,
synchronize: true,
entities: [__dirname + '/**/*.entity.{ts,js}'],
}),
GraphQLModule.forRoot({
debug: true,
playground: true,
typePaths: ['./**/*.graphql'],
installSubscriptionHandlers: true,
// context: ({req}) => {
// return {req};
// },
}),
CatModule,
],
})
export class AppModule {}
import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
import { join } from 'path';
const definitionsFactory = new GraphQLDefinitionsFactory();
// tslint:disable-next-line: no-floating-promises
definitionsFactory.generate({
typePaths: ['./src/**/*.graphql'],
path: join(process.cwd(), 'src/graphql/protocol.schema.ts'),
outputAs: 'class',
});
return await tradeToken(user)
}
if (info) {
// console.log(info)
const { code } = info
switch (code) {
case 'ETIMEDOUT':
throw new ApolloError('Failed to reach Google: Try Again')
default:
throw new ApolloError('Something went wrong')
}
}
}
@Mutation()
async oauthGoogle(
@Args('accessToken') accessToken: string,
@Context() context: any
): Promise {
const { req, res } = context
req.body = {
...req.body,
access_token: accessToken,
}
const { data, info } = await authenticateGoogle(req, res)
if (data) {
console.log(data.profile)
// return user
// }
@Subscription(() => Object, {
filter: (payload: any, variables: any) => {
// console.log('payload', payload)
// console.log('variables', variables)
// return payload.menuPublishByOrder.currentsite === variables.currentsite
return true
}
})
async newUser(@Context('pubsub') pubsub: any): Promise {
return pubsub.asyncIterator(USER_SUBSCRIPTION)
}
@ResolveProperty()
async fullName(@Parent() user: User): Promise {
const { firstName, lastName } = user
return `${firstName} ${lastName}`
}
// @ResolveProperty()
// async local(@Parent() user: User): Promise {
// const { local } = user
// local.password = ''
// return local
// }
@Mutation()
async validateUser(
@Args('text') text: string,
@Args('input') input: CreateUserInput
const rolePermissions: string[] =
this.reflector.get('roles', context.getHandler()) ||
this.reflector.get('roles', context.getClass());
const realmPermissions: string[] =
this.reflector.get('realm', context.getHandler()) ||
this.reflector.get('realm', context.getClass());
const isPublic =
!rolePermissions || rolePermissions.length === 0 || rolePermissions.indexOf(DefaultRoles.public) >= 0;
// Get request data
let request = context.switchToHttp().getRequest();
if (!request) {
const ctx = GqlExecutionContext.create(context);
request = ctx.getContext().req;
}
const headerRealm: string = request.headers.realm || request.query.realm;
if (!isPublic && !headerRealm) {
throw new HttpException('Resource is not public, you must provide "realm" in request headers', 400);
}
const headerAuth: string[] = request.headers.authorization
? request.headers.authorization.split(' ')
: [request.query.token];
if (headerAuth && headerAuth.length > 0 && headerRealm) {
const jwtToken = headerAuth[headerAuth.length - 1] || request.query.token;
if (realmPermissions && realmPermissions.length > 0 && realmPermissions.indexOf(headerRealm) === -1) {
public getHeros(@Args() args: QueryHerosDto, @Context('request') request: Request) {
const token = request.headers.authorization;
if (!token) {
args.state = 1;
}
return this.herosService.searchHero(args);
}
@Mutation()
@Permissions()
public async deleteHero(@Args('_id') _id: string) {
await this.herosService.deleteHero(_id);
return { message: 'success' };
}
@Mutation()
@Permissions()
public async createHero(@Args('heroInfo') info: HerosInfoDto, @Context('request') request: Request) {
// 获取ip地址以及物理地理地址
const ip = ((request.headers['x-forwarded-for'] ||
request.headers['x-real-ip'] ||
request.connection.remoteAddress ||
request.socket.remoteAddress ||
request.ip ||
request.ips[0]) as string).replace('::ffff:', '');
info.ip = ip;
info.agent = request.headers['user-agent'] || info.agent;
const result = await this.herosService.createHero({ ...info, ip });
this.emailService.sendEmail({
@Resolver(() => Role)
export class RolesResolver {
constructor(private readonly casbinService: NestCasbinService) {}
@Query(() => [Role])
async roles() {
throw new NotImplementedError('Not implemented');
}
@Query(() => Role)
async role(@Args('id') id: string) {
throw new NotImplementedError('Not implemented');
}
@Mutation(() => Role, { name: 'role'})
async roleMutation(@Args() cmds: RoleMutationArgs) {
// const actions = this.casbinService.addPolicy('juicycleff', 'tenantx', 'project/001', 'read');
throw new NotImplementedError('Not implemented');
}
}
}
// @UseGuards(PermissionsGuard)
// @Permissions('category.item-read')
// DO NOT CHECK PERMISSIONS
@Query(() => Category)
async category(
@Args({ name: 'id', type: () => Int }) id: number,
@Args() args?: CategoryArgs,
): Promise {
return this.categoryService.category(id, args);
}
@UseGuards(PermissionsGuard)
@Permissions('category.item-create')
@Mutation(() => Category)
async createCategory(@Args('category') args: CreateCategoryInput): Promise {
return this.categoryService.createCategory(args);
}
@UseGuards(PermissionsGuard)
@Permissions('category.item-update')
@Mutation(() => Category)
async updateCategory(
@Args({ name: 'id', type: () => Int }) id: number,
@Args('category') args: UpdateCategoryInput,
): Promise {
return this.categoryService.updateCategory(id, args);
}
@UseGuards(PermissionsGuard)
@Permissions('category.item-delete')
/* tslint:disable:max-classes-per-file */
import { INestApplicationContext, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import { Resolver } from '@nestjs/graphql';
import { GRAPHQL_MODULE_OPTIONS } from '@nestjs/graphql/dist/graphql.constants';
import { ResolveReference } from '../decorators';
import { ReferencesExplorerService } from './references-explorer.service';
@Resolver()
class AccountsResolver {
@Resolver('User')
@ResolveReference()
// tslint:disable-next-line
public user() {}
}
@Module({
providers: [
{
provide: GRAPHQL_MODULE_OPTIONS,
useValue: {},
},
AccountsResolver,
MetadataScanner,
ReferencesExplorerService,
],
})
} from '@leaa/common/src/dtos/user';
import { UserService } from '@leaa/api/src/modules/user/user.service';
import { UserProperty } from '@leaa/api/src/modules/user/user.property';
import { CurrentUser, Permissions } from '@leaa/api/src/decorators';
import { PermissionsGuard } from '@leaa/api/src/guards';
@Resolver(() => User)
export class UserResolver {
constructor(private readonly userService: UserService, private readonly userProperty: UserProperty) {}
@ResolveProperty(() => [String])
async flatPermissions(@Parent() user: User | undefined): Promise {
return this.userProperty.flatPermissions(user);
}
@ResolveProperty(() => [String])
async permissions(@Parent() user: User | undefined): Promise {
return this.userProperty.permissions(user);
}
//
// fot Test GraphQL
@Query(() => Float)
async ram(): Promise {
return Math.random();
}
@UseGuards(PermissionsGuard)
@Permissions('user.list-read')
@Query(() => UsersWithPaginationObject)
async users(@Args() args: UsersArgs, @CurrentUser() user?: User): Promise {