Skip to content
Snippets Groups Projects
Commit d936324f authored by Nabilsenko's avatar Nabilsenko
Browse files

feat: added JWT to login controller

parent 0410d94f
No related branches found
No related tags found
1 merge request!6feat: added login to people
......@@ -3,8 +3,10 @@ import { MongooseModule } from '@nestjs/mongoose';
import { mongodb } from './config';
import { PeopleModule } from './people/people.module';
import { GroupsModule } from './groups/groups.module';
import { LoginModule } from './login/login.module';
@Module({
imports: [PeopleModule, GroupsModule, MongooseModule.forRoot(mongodb.uri)],
imports: [PeopleModule, GroupsModule, MongooseModule.forRoot(mongodb.uri), LoginModule],
})
export class AppModule {}
export const jwtConstants = {
secret: 'secretKey',
}
\ No newline at end of file
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { jwtConstants } from '../constants';
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret
})
}
async validate(payload: any) {
return {userId: payload.sub, email: payload.email}
}
}
\ No newline at end of file
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-local";
import { LoginService } from "./login.service";
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private loginService: LoginService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.loginService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
\ No newline at end of file
import { Controller, Post, Request, UseGuards } from '@nestjs/common';
import { Body } from '@nestjs/common/decorators/http/route-params.decorator';
import { AuthGuard } from '@nestjs/passport';
import { Login } from 'src/types/login';
import { LoginService } from './login.service';
@Controller('login')
export class LoginController {
constructor(private loginService: LoginService) {}
// @UseGuards(AuthGuard('local'))
@Post()
async login(@Body() req: Login) {
console.log('controller ' + req.email + req.passwordHash);
return this.loginService.login(req);
}
}
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { PeopleModule } from 'src/people/people.module';
import { LoginService } from './login.service';
import { LoginController } from './login.controller';
import { jwtConstants } from '../constants';
// import { PeopleService } from 'src/people/people.service';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
PeopleModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: '300s' },
}),
],
controllers: [LoginController],
providers: [LoginService, LocalStrategy, JwtStrategy],
exports: [LoginService],
})
export class LoginModule {}
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PeopleService } from 'src/people/people.service';
@Injectable()
export class LoginService {
constructor(
private peopleService: PeopleService,
private jwtService: JwtService,
) {}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.peopleService.login(username, pass);
if (user && user.passwordHash == pass) {
const { passwordHash, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const req = await this.validateUser(user.email, user.passwordHash);
if(req != null) {
const payload = { email: user.email, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
}
}
......@@ -7,6 +7,7 @@ import {
Param,
Body,
UseInterceptors,
UseGuards
} from '@nestjs/common';
import { CreatePeopleDto } from './dto/create-people.dto';
import { UpdatePeopleDto } from './dto/update-people.dto';
......@@ -15,6 +16,7 @@ import { HttpInterceptor } from '../interceptors/http.interceptor';
// import { UpdatePeopleDto } from './dto/update-people.dto';
import { PeopleEntity } from './entities/people.entity';
import { PeopleService } from './people.service';
import { AuthGuard } from '@nestjs/passport';
interface Login {
email: string;
......@@ -26,15 +28,14 @@ import { PeopleService } from './people.service';
export class PeopleController {
constructor(private readonly _peopleService: PeopleService) {}
@Post('/login')
login(@Body() login: Login): Promise<PeopleEntity | void> {
return this._peopleService.login(login.email, login.password);
}
@UseGuards(AuthGuard('jwt'))
@Get()
findAll(): Promise<PeopleEntity[] | void> {
return this._peopleService.findAll();
}
@UseGuards(AuthGuard('jwt'))
@Get(':id')
findOne(@Param() params: { id: string }): Promise<PeopleEntity | void> {
return this._peopleService.findOne(params.id);
......
......@@ -6,11 +6,11 @@ import { PeopleService } from './people.service';
import { People, PeopleSchema } from './schemas/people.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: People.name, schema: PeopleSchema }]),
],
controllers: [PeopleController],
providers: [PeopleService, PeopleDao, Logger],
})
export class PeopleModule {}
\ No newline at end of file
imports: [
MongooseModule.forFeature([{ name: People.name, schema: PeopleSchema }]),
],
controllers: [PeopleController],
providers: [PeopleService, PeopleDao, Logger],
exports: [PeopleService],
})
export class PeopleModule {}
......@@ -4,8 +4,11 @@ import { CreatePeopleDto } from './dto/create-people.dto';
import { UpdatePeopleDto } from './dto/update-people.dto';
import { PeopleEntity } from './entities/people.entity';
@Injectable()
export class PeopleService {
constructor(private readonly _peopleDao: PeopleDao) {}
login = (email: string, password: string): Promise<PeopleEntity | void> =>
......
export interface Login {
email: string;
passwordHash: string;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment