Skip to content

Commit

Permalink
ids对接成功哦那个
Browse files Browse the repository at this point in the history
  • Loading branch information
Wolf-Tungsten committed Nov 27, 2019
1 parent 38ceaff commit 7952983
Show file tree
Hide file tree
Showing 16 changed files with 364 additions and 61 deletions.
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"dev":"nest start --watch",
"dev": "nest start --watch",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
Expand All @@ -24,10 +24,18 @@
"@hapi/joi": "^16.1.8",
"@nestjs/common": "^6.7.2",
"@nestjs/core": "^6.7.2",
"@nestjs/jwt": "^6.1.1",
"@nestjs/mongoose": "^6.1.2",
"@nestjs/passport": "^6.1.0",
"@nestjs/platform-express": "^6.7.2",
"@types/moment": "^2.13.0",
"axios": "^0.19.0",
"dotenv": "^8.2.0",
"fast-xml-parser": "^3.15.0",
"moment": "^2.24.0",
"mongoose": "^5.7.12",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"rxjs": "^6.5.3"
Expand All @@ -36,11 +44,13 @@
"@nestjs/cli": "^6.9.0",
"@nestjs/schematics": "^6.7.0",
"@nestjs/testing": "^6.7.1",
"@types/axios": "^0.14.0",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.1",
"@types/hapi__joi": "^16.0.3",
"@types/jest": "^24.0.18",
"@types/node": "^12.7.5",
"@types/passport-jwt": "^3.0.3",
"@types/supertest": "^2.0.8",
"jest": "^24.9.0",
"prettier": "^1.18.2",
Expand Down
22 changes: 0 additions & 22 deletions src/app.controller.spec.ts

This file was deleted.

3 changes: 2 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AppService } from './app.service';
import { ConfigModule } from './config/config.module';
import { ConfigService } from './config/config.service';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthModule } from './auth/auth.module';

const mongooseModule = MongooseModule.forRootAsync({
imports: [ConfigModule],
Expand All @@ -16,7 +17,7 @@ const mongooseModule = MongooseModule.forRootAsync({
});

@Module({
imports: [ConfigModule, mongooseModule],
imports: [ConfigModule, mongooseModule, AuthModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
18 changes: 18 additions & 0 deletions src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';

describe('Auth Controller', () => {
let controller: AuthController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();

controller = module.get<AuthController>(AuthController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
21 changes: 21 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Controller, Query, Get, Param } from '@nestjs/common';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService){}
@Get('/ids-auth')
async idsAuth(@Query('ticket') ticket: string){
return { access_token:(await this.authService.authWithIdsTicket(ticket)) };
}

@Get('/ids-auth/:wechatSession')
async idsAuthWithWechatSession(@Query('ticket') ticket: string, @Param('wechatSession') wechatSession: string){

}

@Get('/wechat-auth')
async wechatAuth(@Query('code') code: string){

}
}
8 changes: 8 additions & 0 deletions src/auth/auth.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Document } from 'mongoose';

export interface Auth extends Document {
readonly cardnum: string;
readonly name: string;
readonly openId: string;
readonly wechatSession: string,
}
26 changes: 26 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Module, Injectable } from '@nestjs/common';
import { AuthService } from './auth.service';
import { ConfigService } from '../config/config.service';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
import { AuthController } from './auth.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthSchema } from './auth.scheme';

const config = new ConfigService()

@Module({
imports: [
PassportModule,
JwtModule.register({
secret: config.jwtSecret,
signOptions: { expiresIn: '3h' },
}),
MongooseModule.forFeature([{ name: 'Auth', schema: AuthSchema }])
],
providers: [AuthService, JwtStrategy],
exports: [ AuthService ],
controllers: [AuthController]
})
export class AuthModule {}
9 changes: 9 additions & 0 deletions src/auth/auth.scheme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as mongoose from 'mongoose';

export const AuthSchema = new mongoose.Schema({
name: String, // 姓名
cardnum: String, // 一卡通号
openId: String, // 微信公众号 OpenId
wechatSession: String, // 微信绑定过程中会话标识符
lastAuthTime: Number, // 最近认证时间
});
18 changes: 18 additions & 0 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';

describe('AuthService', () => {
let service: AuthService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();

service = module.get<AuthService>(AuthService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
44 changes: 44 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '../config/config.service';
import axios from 'axios';
import { parse as xmlParser } from 'fast-xml-parser';
import { InjectModel } from '@nestjs/mongoose';
import { Auth } from './auth.interface';
import { Model } from 'mongoose';
import * as moment from 'moment';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
constructor(private readonly config: ConfigService,
@InjectModel('Auth') private readonly authModel:Model<Auth>,
private readonly jwtService:JwtService
) {}

async authWithIdsTicket(ticket: string): Promise<string>{
const validateUrl = `${this.config.idsValidatedUrl}?service=${this.config.idsAuthUrl}&ticket=${ticket}`;
const res = await axios.get(validateUrl);
const rawIdsData = xmlParser(res.data);
try {
let { "cas:uid":cardnum, "cas:cn":name } = rawIdsData["cas:serviceResponse"]["cas:authenticationSuccess"]["cas:attributes"];
let record = await this.authModel.findOne({ cardnum });
if(!record){
record = new this.authModel({ cardnum, name })
}
record.lastAuthTime = moment().unix();
await record.save();
return this.jwtService.sign({ cardnum, name });
} catch (e) {
console.log(e)
return null
}
}

async authWithWechatCode(code: string): Promise<string>{
return 'wechatSession'
}

async authWithIdsTicketAndWechatSession(ticket: string, wechatSession: string){

}
}
19 changes: 19 additions & 0 deletions src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '../config/config.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.jwtSecret,
});
}

async validate(payload: any) {
return { cardnum: payload.cardnum };
}
}
2 changes: 1 addition & 1 deletion src/config/config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ConfigService } from './config.service';
providers: [
{
provide: ConfigService,
useValue: new ConfigService(`${process.env.NODE_ENV || 'development'}.env`),
useValue: new ConfigService(),
},
],
exports: [ConfigService],
Expand Down
19 changes: 17 additions & 2 deletions src/config/config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type EnvConfig = Record<string, string>;
export class ConfigService {
private readonly envConfig: EnvConfig;

constructor(filePath: string) {
constructor(filePath: string = `${process.env.NODE_ENV || 'development'}.env`) {
const config = dotenv.parse(fs.readFileSync(filePath));
this.envConfig = this.validateInput(config);
}
Expand All @@ -22,7 +22,10 @@ export class ConfigService {
.valid('development', 'production', 'test', 'provision')
.default('development'),
PORT: Joi.number().default(3000),
MONGODB_URI: Joi.string().required()
MONGODB_URI: Joi.string().required(),
JWT_SECRET: Joi.string().required(),
IDS_AUTH_URL: Joi.string().required(),
IDS_VALIDATE_URL: Joi.string().required(),
});

const { error, value: validatedEnvConfig } = envVarsSchema.validate(
Expand All @@ -37,4 +40,16 @@ export class ConfigService {
get mongodbUri(): string {
return String(this.envConfig.MONGODB_URI);
}

get idsAuthUrl(): string {
return String(this.envConfig.IDS_AUTH_URL);
}

get idsValidatedUrl(): string {
return String(this.envConfig.IDS_VALIDATE_URL);
}

get jwtSecret(): string {
return String(this.envConfig.JWT_SECRET);
}
}
23 changes: 0 additions & 23 deletions test/app.e2e-spec.ts

This file was deleted.

9 changes: 0 additions & 9 deletions test/jest-e2e.json

This file was deleted.

Loading

0 comments on commit 7952983

Please sign in to comment.