Skip to content

Commit

Permalink
feat: update
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangtao25 committed Sep 13, 2023
1 parent 62a4bad commit 5f20d7d
Show file tree
Hide file tree
Showing 14 changed files with 172 additions and 58 deletions.
17 changes: 17 additions & 0 deletions packages/app-backend/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,24 @@ type Repo {
reportTimes: Float!
}

type User {
id: ID!
username: String!
password: String!
nickname: String!
avatar: String!
thRefreshToken: String!
thAccessToken: String!
email: String!
thId: String!
role: [String!]!
createdAt: DateTime!
}

type Query {
"""提供执行此查询的用户的详细信息(通过授权 Bearer 标头)"""
me: User!

"""获取所有镜像列表"""
listClusters: [Cluster!]!

Expand Down
22 changes: 0 additions & 22 deletions packages/app-backend/src/app.controller.spec.ts

This file was deleted.

5 changes: 2 additions & 3 deletions packages/app-backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { GraphQLModule } from '@nestjs/graphql';
import { ConfigModule } from '@nestjs/config';
import { ImageModule } from './image/image.module';
// import { Coverage } from "./coverage/coverage.model";
import { CoverageModule } from './coverage/coverage.module';
import { AuthModule } from './auth/auth.module';
import { join } from 'path';
Expand All @@ -20,8 +19,10 @@ import { KubernetesModule } from './kubernetes/kubernetes.module';
import { GitlabModule } from './gitlab/gitlab.module';
import {CalendarModule} from "./calendar/calendar.module";
import {RepoModule} from "./repo/repo.module";
import {UserModule} from "./user/user.module";
@Module({
imports: [
UserModule,
ScheduleModule.forRoot(),
TasksModule,
AuthModule,
Expand All @@ -30,12 +31,10 @@ import {RepoModule} from "./repo/repo.module";
GitlabModule,
CalendarModule,
RepoModule,
// TeamModule,
ApplicationModule,
ImageModule,
PipelineModule,
KubernetesModule,
// UserModule,
CoverageModule,
ServeStaticModule.forRoot({
rootPath: join(__dirname, '../../app-ui', 'dist'),
Expand Down
6 changes: 0 additions & 6 deletions packages/app-backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,4 @@ export class AuthController {
async passwordLogin(@Body() reqBody: any) {
return this.authService.passwordLogin(reqBody);
}

@UseGuards(JwtAuthGuard)
@Get('/api/user')
async getUserinfo(@Request() request: { user: { id: number } }) {
return this.authService.getUserinfo({ userId: request.user.id });
}
}
25 changes: 2 additions & 23 deletions packages/app-backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
// import { Model } from 'mongoose';
// import { UserDocument } from './schemas/user.schema';
import axios from 'axios';
import { PrismaService } from '../prisma/prisma.service';
import * as process from 'process';
Expand All @@ -10,8 +8,6 @@ import * as process from 'process';
export class AuthService {
constructor(
private readonly jwtService: JwtService,
// @Inject('MONGODB_CONNECTION_UserRepository')
// private userModel: Model<UserDocument>,
private readonly prisma: PrismaService,
) {}
async validateUser(username: string, password: string): Promise<any> {
Expand All @@ -32,7 +28,7 @@ export class AuthService {
async login(user: any) {
const payload = {
username: user.username,
id: String(user.id),
id: user.id,
roles: user.role,
};
// AuthService.login 第三步:存储信息
Expand All @@ -42,20 +38,11 @@ export class AuthService {
}

async oauthToken(params) {
// 1.拿前端传来的code兑换access_token,refresh_token
// const redirect_uri = global.conf.gitlab.application.redirectUri;
// const ClientId = process.env.ClientId;
// const clientSecret = global.conf.gitlab.application.clientSecret;

const {
GITLAB_CLIENT_ID: ClientId,
GITLAB_CLIENT_SECRET: clientSecret,
GITLAB_URL: gitlabUrl,
} = process.env;
console.log(
params,
`${gitlabUrl}/oauth/token?client_id=${ClientId}&client_secret=${clientSecret}&code=${params.code}&grant_type=authorization_code&redirect_uri=${params.redirectUri}/login`,
);
const { refresh_token: thRefreshToken, access_token: thAccessToken } =
await axios
.post(
Expand All @@ -69,7 +56,6 @@ export class AuthService {
// 如果没兑换到就抛异常
throw new UnauthorizedException();
});

// 2.如果成功拿到token,先去gitlab那边校验一下,拿到用户信息
let {
// eslint-disable-next-line prefer-const
Expand Down Expand Up @@ -147,15 +133,8 @@ export class AuthService {
}
return this.login({
username: isHasUser.username,
id: String(isHasUser.id),
id: isHasUser.id,
role: isHasUser.role,
});
}
async getUserinfo({ userId }) {
return this.prisma.user.findFirst({
where: {
id: userId,
},
});
}
}
37 changes: 37 additions & 0 deletions packages/app-backend/src/user/user.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ObjectType, Field, ID } from '@nestjs/graphql';

@ObjectType()
export class User {
@Field(() => ID)
id: number;

@Field()
username: string;

@Field()
password: string;

@Field()
nickname: string;

@Field()
avatar: string;

@Field()
thRefreshToken: string;

@Field()
thAccessToken: string;

@Field()
email: string;

@Field()
thId: string;

@Field(() => [String])
role: string[];

@Field()
createdAt: Date;
}
12 changes: 12 additions & 0 deletions packages/app-backend/src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { UserResolver } from './user.resolver';
import { PubSubModule } from 'src/pubsub/pubsub.module';
import { UserService } from './user.service';
import { PrismaModule } from 'src/prisma/prisma.module';

@Module({
imports: [PubSubModule, PrismaModule],
providers: [UserResolver, UserService],
exports: [UserService],
})
export class UserModule {}
24 changes: 24 additions & 0 deletions packages/app-backend/src/user/user.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Resolver, Query, Mutation, Args, Subscription } from '@nestjs/graphql';
import { User } from './user.model';
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '../guards/gql-auth.guard';
import { GqlUser } from '../decorators/gql-user.decorator';
import { UserService } from './user.service';
import { PubSubService } from 'src/pubsub/pubsub.service';
import { AuthUser } from 'src/types/AuthUser';
@Resolver(() => User)
export class UserResolver {
constructor(
private readonly userService: UserService,
private readonly pubsub: PubSubService,
) {}

@Query(() => User, {
description:
"提供执行此查询的用户的详细信息(通过授权 Bearer 标头)",
})
@UseGuards(GqlAuthGuard)
me(@GqlUser() user: AuthUser) {
return this.userService.convertDbUserToUser(user);
}
}
26 changes: 26 additions & 0 deletions packages/app-backend/src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { User } from './user.model';
import { PubSubService } from 'src/pubsub/pubsub.service';
import { User as DbUser } from '@prisma/client';

@Injectable()
export class UserService {
constructor(
private prisma: PrismaService,
private readonly pubsub: PubSubService,
) {}
/**
* 将 prisma 用户对象转换为用户对象
*
* @param dbUser Prisma User object
* @returns User object
*/
convertDbUserToUser(dbUser: DbUser): Promise<User> {
return this.prisma.user.findFirst({
where:{
id:dbUser.id
}
})
}
}
5 changes: 5 additions & 0 deletions packages/app-ui/src/helpers/backend/gen/gql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const documents = {
"query GetTreeSummary($repoID: ID!, $commitSha: String!, $reportID: String!, $mode: String!) {\n treeSummary(\n repoID: $repoID\n commitSha: $commitSha\n reportID: $reportID\n mode: $mode\n )\n}": types.GetTreeSummaryDocument,
"query ListImages {\n listImages {\n id\n tag\n imageID\n size\n }\n}": types.ListImagesDocument,
"query ListPipelines {\n listPipelines {\n committedAt\n createdAt\n duration\n finishedAt\n id\n projectId\n ref\n sha\n startedAt\n status\n updatedAt\n webUrl\n commit {\n id\n title\n message\n web_url\n short_id\n created_at\n parent_ids\n author_name\n author_email\n authored_date\n committed_date\n committer_name\n committer_email\n }\n user {\n id\n bio\n bot\n name\n skype\n state\n discord\n twitter\n web_url\n linkedin\n location\n pronouns\n username\n followers\n following\n job_title\n avatar_url\n created_at\n local_time\n website_url\n organization\n public_email\n work_information\n }\n stages {\n id\n status\n stage\n name\n ref\n tag\n coverage\n allowFailure\n created_at\n started_at\n finished_at\n erased_at\n duration\n queued_duration\n failure_reason\n web_url\n }\n }\n}": types.ListPipelinesDocument,
"query Me {\n me {\n id\n username\n password\n nickname\n avatar\n thRefreshToken\n thAccessToken\n email\n thId\n role\n createdAt\n }\n}": types.MeDocument,
};

/**
Expand Down Expand Up @@ -119,6 +120,10 @@ export function graphql(source: "query ListImages {\n listImages {\n id\n
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function graphql(source: "query ListPipelines {\n listPipelines {\n committedAt\n createdAt\n duration\n finishedAt\n id\n projectId\n ref\n sha\n startedAt\n status\n updatedAt\n webUrl\n commit {\n id\n title\n message\n web_url\n short_id\n created_at\n parent_ids\n author_name\n author_email\n authored_date\n committed_date\n committer_name\n committer_email\n }\n user {\n id\n bio\n bot\n name\n skype\n state\n discord\n twitter\n web_url\n linkedin\n location\n pronouns\n username\n followers\n following\n job_title\n avatar_url\n created_at\n local_time\n website_url\n organization\n public_email\n work_information\n }\n stages {\n id\n status\n stage\n name\n ref\n tag\n coverage\n allowFailure\n created_at\n started_at\n finished_at\n erased_at\n duration\n queued_duration\n failure_reason\n web_url\n }\n }\n}"): (typeof documents)["query ListPipelines {\n listPipelines {\n committedAt\n createdAt\n duration\n finishedAt\n id\n projectId\n ref\n sha\n startedAt\n status\n updatedAt\n webUrl\n commit {\n id\n title\n message\n web_url\n short_id\n created_at\n parent_ids\n author_name\n author_email\n authored_date\n committed_date\n committer_name\n committer_email\n }\n user {\n id\n bio\n bot\n name\n skype\n state\n discord\n twitter\n web_url\n linkedin\n location\n pronouns\n username\n followers\n following\n job_title\n avatar_url\n created_at\n local_time\n website_url\n organization\n public_email\n work_information\n }\n stages {\n id\n status\n stage\n name\n ref\n tag\n coverage\n allowFailure\n created_at\n started_at\n finished_at\n erased_at\n duration\n queued_duration\n failure_reason\n web_url\n }\n }\n}"];
/**
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function graphql(source: "query Me {\n me {\n id\n username\n password\n nickname\n avatar\n thRefreshToken\n thAccessToken\n email\n thId\n role\n createdAt\n }\n}"): (typeof documents)["query Me {\n me {\n id\n username\n password\n nickname\n avatar\n thRefreshToken\n thAccessToken\n email\n thId\n role\n createdAt\n }\n}"];

export function graphql(source: string) {
return (documents as any)[source] ?? {};
Expand Down
Loading

0 comments on commit 5f20d7d

Please sign in to comment.