Commit 0249899c authored by abbasmortezavifar's avatar abbasmortezavifar
Browse files

JwtStrategy requires a secret or key

parents
Pipeline #368 failed with stages
import { BaceEntity } from './../bace.entity';
import { Column, Entity } from "typeorm";
@Entity()
export class User extends BaceEntity {
@Column({ unique: true })
email: string;
@Column()
password: string;
@Column()
fristname: string;
@Column()
lastname: string;
@Column()
address: string;
@Column()
emailactivcode: boolean;
@Column()
isactivated: boolean;
@Column()
userrole: string;
}
\ No newline at end of file
import { AuthCredentialsDto } from './dto/sing-in.dto';
import { UserModel } from './users.model';
import { User } from './user.entity';
import { CreateUserDto } from './dto/users.dto';
import { UsersService } from './users.service';
import { Body, Controller, Delete, Get, Param, Patch, Post, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('users')
export class UsersController {
constructor(private userService: UsersService) { }
@Post('/test')
@UseGuards(AuthGuard())
test(@Req() req) {
console.log(req);
}
@Get()
async getAllusers(): Promise<User[]> {
const user = await this.userService.getAllUsers();
return user;
}
@Get('/:id')
getByIDUser(@Param('id') id: string): Promise<User> {
return this.userService.getByIDUser(id);
}
@Post()
SingUp(@Body() user: CreateUserDto): Promise<void> {
return this.userService.SingUp(user);
}
@Post('/singin')
SingIn(@Body() auth: AuthCredentialsDto): Promise<{ accessToken: string }> {
return this.userService.SingIn(auth);
}
@Delete('/:id')
removeUser(@Param('id') id: string): Promise<void> {
return this.userService.removeUser(id);
}
@Patch('/:id/update')
UpdateUsers(@Param('id') id: string, @Body() user: CreateUserDto): Promise<User> {
return this.userService.UpdateUser(id, user);
}
}
export interface UserModel {
id: number;
isdelete: boolean;
createdate: Date;
lastupdatedate: Date;
email: string;
fristname: string;
lastname: string;
address: string;
emailactivcode: boolean;
isactivated: boolean;
}
import { ConfigModule } from '@nestjs/config';
import { JwtStrategy } from './jwt.strategy';
import { UsersRepository } from './users.repository';
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { RolesModule } from './roles/roles.module';
import { UserRolesModule } from './user-roles/user-roles.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import * as config from 'config';
const jwtConfig = config.get('jwt');
@Module({
imports: [RolesModule,
UserRolesModule,
ConfigModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.JWT_SECRET || jwtConfig.secret,
signOptions: { expiresIn: jwtConfig.expiresIn },
}),
TypeOrmModule.forFeature([UsersRepository]),
],
controllers: [UsersController],
providers: [UsersService, JwtStrategy],
exports: [JwtStrategy, PassportModule],
})
export class UsersModule { }
import { CreateUserDto } from './dto/users.dto';
import { EntityRepository, Repository } from "typeorm";
import { User } from "./user.entity";
import { ConflictException, InternalServerErrorException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
@EntityRepository(User)
export class UsersRepository extends Repository<User>{
async createUser(createUser: CreateUserDto): Promise<void> {
const { email, fristname, lastname, address, password } = createUser;
const salt = await bcrypt.genSalt();
const hashedPassword = await bcrypt.hash(password, salt);
const user = this.create({
email,
password: hashedPassword,
fristname,
lastname,
address,
userrole: '',
emailactivcode: false,
isactivated: false,
});
try {
await this.save(user);
} catch (error) {
if (error.code === '23505') { //duplicate Email
throw new ConflictException('Email alrady exists');
} else {
throw new InternalServerErrorException();
}
}
}
}
\ No newline at end of file
import { JwtPayload } from './jwt-payload.interface';
import { AuthCredentialsDto } from './dto/sing-in.dto';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';
import { CreateUserDto } from './dto/users.dto';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { NotFoundException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class UsersService {
constructor(@InjectRepository(UsersRepository)
private userRepository: UsersRepository,
private jwtService:JwtService,) { }
private date: Date = new Date();
async getAllUsers(): Promise<User[]> {
const query = await this.userRepository.createQueryBuilder('user');
const users = query.getMany();
return users;
}
async getByIDUser(id: string): Promise<User> {
const user = await this.userRepository.findOne(id);
if (!user) {
throw new NotFoundException(`User with ID "${id}" not found !`)
}
return user;
}
async SingUp(createUserDto: CreateUserDto): Promise<void> {
return this.userRepository.createUser(createUserDto)
}
async SingIn(authDto: AuthCredentialsDto): Promise<{accessToken:string}> {
const { email, password } = authDto;
const user = await this.userRepository.findOne({email})
if (user && (await bcrypt.compare(password, user.password))){
const payload:JwtPayload = {email};
const accessToken:string = await this.jwtService.sign(payload);
return { accessToken }
}else{
throw new UnauthorizedException('Plase check your login credentials');
}
}
async removeUser(id: string): Promise<void> {
const user = await this.getByIDUser(id);
user.isdelete = true;
await this.userRepository.save(user);
}
async UpdateUser(id: string, updateUser: CreateUserDto): Promise<User> {
const user = await this.getByIDUser(id);
const { email, fristname, lastname, address } = updateUser;
user.email = email;
user.fristname = fristname;
user.lastname = lastname;
user.lastupdatedate = this.date;
user.address = address;
await this.userRepository.save(user);
return user;
}
}
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment