xiongzhu 2 years ago
parent
commit
b89af831db

+ 1 - 1
src/users/dto/user.dto.ts → src/users/dto/user-create.dto.ts

@@ -1,6 +1,6 @@
 import { MaxLength, IsNotEmpty, IsEmail, IsString, isString } from 'class-validator'
 
-export class UserDto {
+export class UserCreateDto {
     @IsString()
     @MaxLength(30)
     readonly name: string

+ 2 - 0
src/users/dto/user-profile.dto.ts

@@ -1,4 +1,6 @@
 export class UserProfileDto {
+    id: number
+    
     name: string
 
     avatar: string

+ 2 - 2
src/users/dto/user-update.dto.ts

@@ -1,4 +1,4 @@
 import { PartialType } from '@nestjs/swagger'
-import { UserDto } from './user.dto'
+import { UserCreateDto } from './user-create.dto'
 
-export class UserUpdateDto extends PartialType(UserDto) {}
+export class UserUpdateDto extends PartialType(UserCreateDto) {}

+ 2 - 0
src/users/entities/users.entity.ts

@@ -1,5 +1,6 @@
 import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm'
 import { Role } from '../../model/role.enum'
+import { Exclude } from 'class-transformer'
 
 
 
@@ -21,6 +22,7 @@ export class Users {
     email?: string
 
     @Column({ nullable: true })
+    @Exclude({ toPlainOnly: true })
     password?: string
 
     @Column({ nullable: true, unique: true })

+ 3 - 1
src/users/users.controller.ts

@@ -23,7 +23,9 @@ export class UsersController {
 
     @Get('/my')
     public async my(@Req() req) {
-        return this.usersService.findById(req.user.userId)
+        const user = await this.usersService.findById(req.user.userId)
+        console.log(user)
+        return user
     }
 
     @Post('/update')

+ 2 - 2
src/users/users.service.ts

@@ -10,7 +10,7 @@ import { Repository, UpdateResult } from 'typeorm'
 import { InjectRepository } from '@nestjs/typeorm'
 import { Users } from './entities/users.entity'
 import { IUsers } from './interfaces/users.interface'
-import { UserDto } from './dto/user.dto'
+import { UserCreateDto } from './dto/user-create.dto'
 import { UserProfileDto } from './dto/user-profile.dto'
 import { UserUpdateDto } from './dto/user-update.dto'
 import { HashingService } from '../shared/hashing/hashing.service'
@@ -78,7 +78,7 @@ export class UsersService {
         return user
     }
 
-    public async create(userDto: UserDto): Promise<IUsers> {
+    public async create(userDto: UserCreateDto): Promise<IUsers> {
         try {
             return await this.userRepository.save(userDto)
         } catch (err) {

+ 0 - 137
test/change-password/change-password.e2e-spec.ts

@@ -1,137 +0,0 @@
-import { Test, TestingModule } from '@nestjs/testing';
-import * as request from 'supertest';
-import { AppModule } from '../../src/app.module';
-import { MailerService } from '../../src/shared/mailer/mailer.service';
-import {
-  BadRequestException,
-  HttpStatus,
-  ValidationPipe,
-} from '@nestjs/common';
-
-const user = {
-  email: 'test@example.com',
-  password: 'pass123',
-};
-
-describe('App (e2e)', () => {
-  let app;
-  let accessTokenJwt: string;
-
-  beforeAll(async () => {
-    const moduleFixture: TestingModule = await Test.createTestingModule({
-      imports: [AppModule],
-    })
-      .overrideProvider(MailerService)
-      .useValue({
-        sendMail: jest.fn(() => true),
-      })
-      .compile();
-
-    app = moduleFixture.createNestApplication();
-    app.setGlobalPrefix('api');
-    app.useGlobalPipes(
-      new ValidationPipe({
-        whitelist: true,
-        transform: true,
-        forbidNonWhitelisted: true,
-        transformOptions: {
-          enableImplicitConversion: true,
-        },
-      }),
-    );
-
-    await app.init();
-  });
-
-  describe('should sign in and get a "live" JWT', () => {
-    it('should authenticates user with valid credentials and provides a jwt token', () => {
-      return request(app.getHttpServer())
-        .post('/api/auth/login')
-        .send({
-          email: 'test@example.com',
-          password: 'pass123',
-        })
-        .then(({ body }) => {
-          accessTokenJwt = body.accessToken;
-          expect(accessTokenJwt).toMatch(
-            /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/,
-          );
-
-          expect(body).toEqual({
-            sub: 1,
-            expiresIn: '3600',
-            audience: '127.0.0.1:3001',
-            issuer: '127.0.0.1:3001',
-            accessToken: accessTokenJwt,
-            user: { name: 'name #1', email: 'test@example.com', id: 1 },
-          });
-
-          expect(HttpStatus.OK);
-        });
-    });
-  });
-
-  describe('ChangePasswordController (e2e) - [POST /api/auth/change-password]', () => {
-    it('should change password an user', async () => {
-      return await request(app.getHttpServer())
-        .post('/api/auth/change-password')
-        .set('Authorization', `Bearer ${accessTokenJwt}`)
-        .send(user)
-        .then(({ body }) => {
-          expect(body).toEqual({
-            message: 'Request Change Password Successfully!',
-            status: 200,
-          });
-          expect(HttpStatus.OK);
-        });
-    });
-  });
-
-  it('should throw an error for a bad email', async () => {
-    return await request(app.getHttpServer())
-      .post('/api/auth/change-password')
-      .set('Authorization', `Bearer ${accessTokenJwt}`)
-      .send({
-        password: 'new123456',
-      })
-      .then(({ body }) => {
-        expect(body).toEqual({
-          error: 'Bad Request',
-          message: [
-            'email should not be empty',
-            'email must be a string',
-            'email must be an email',
-          ],
-          statusCode: 400,
-        });
-        expect(HttpStatus.BAD_REQUEST);
-        expect(new BadRequestException());
-      });
-  });
-
-  it('should throw an error for a bad password', async () => {
-    return await request(app.getHttpServer())
-      .post('/api/auth/change-password')
-      .set('Authorization', `Bearer ${accessTokenJwt}`)
-      .send({
-        email: 'test@example.it',
-      })
-      .then(({ body }) => {
-        expect(body).toEqual({
-          error: 'Bad Request',
-          message: [
-            'password must be shorter than or equal to 60 characters',
-            'password must be a string',
-            'password should not be empty',
-          ],
-          statusCode: 400,
-        });
-        expect(HttpStatus.BAD_REQUEST);
-        expect(new BadRequestException());
-      });
-  });
-
-  afterAll(async () => {
-    await app.close();
-  });
-});

+ 0 - 88
test/forgot-password/forgot-password.e2e-spec.ts

@@ -1,88 +0,0 @@
-import { Test, TestingModule } from '@nestjs/testing';
-import * as request from 'supertest';
-import { AppModule } from './../../src/app.module';
-import { MailerService } from '../../src/shared/mailer/mailer.service';
-import {
-  BadRequestException,
-  HttpStatus,
-  ValidationPipe,
-} from '@nestjs/common';
-import { UserDto } from '../../src/users/dto/user.dto';
-
-const user = {
-  email: 'test@example.com',
-};
-
-const createUser = {
-  name: 'name #1',
-  username: 'username #1',
-  email: 'test@example.com',
-  password: 'pass123',
-};
-
-describe('App (e2e)', () => {
-  let app;
-
-  beforeAll(async () => {
-    const moduleFixture: TestingModule = await Test.createTestingModule({
-      imports: [AppModule],
-    })
-      .overrideProvider(MailerService)
-      .useValue({
-        sendMail: jest.fn(() => true),
-      })
-      .compile();
-
-    app = moduleFixture.createNestApplication();
-    app.setGlobalPrefix('api');
-    app.useGlobalPipes(
-      new ValidationPipe({
-        whitelist: true,
-        transform: true,
-        forbidNonWhitelisted: true,
-        transformOptions: {
-          enableImplicitConversion: true,
-        },
-      }),
-    );
-
-    await app.init();
-  });
-
-  describe('ForgotPassowrdController (e2e) - [POST /api/auth/forgot-password]', () => {
-    it('should create user', async () => {
-      return await request(app.getHttpServer())
-        .post('/api/auth/register')
-        .send(createUser as UserDto)
-        .then(({ body }) => {
-          expect(body).toEqual({
-            message: 'User registration successfully!',
-            status: 201,
-          });
-          expect(HttpStatus.CREATED);
-        });
-    });
-
-  });
-
-  it('should throw an error for a bad email', () => {
-    return request(app.getHttpServer())
-      .post('/api/auth/forgot-password')
-      .send({
-        email: 'not correct',
-      })
-      .then(({ body }) => {
-        expect(body).toEqual({
-          error: 'Bad Request',
-          message: ['email must be an email'],
-          statusCode: 400,
-        });
-        expect(HttpStatus.BAD_REQUEST);
-        expect(new BadRequestException());
-      });
-  });
-
-  afterAll(async () => {
-    await app.close();
-  });
-});

+ 2 - 2
test/register/register.e2e-spec.ts

@@ -7,7 +7,7 @@ import {
   HttpStatus,
   ValidationPipe,
 } from '@nestjs/common';
-import { UserDto } from 'src/users/dto/user.dto';
+import { UserCreateDto } from 'src/users/dto/user-create.dto';
 import { HashingService } from '../../src/shared/hashing/hashing.service';
 
 const user = {
@@ -58,7 +58,7 @@ describe('App (e2e)', () => {
     it('should register user', async () => {
       return await request(app.getHttpServer())
         .post('/api/auth/register')
-        .send(user as UserDto)
+        .send(user as UserCreateDto)
         .then(({ body }) => {
           expect(body).toEqual({
             message: 'User registration successfully!',