Skip to content

Commit

Permalink
authenticate user with a token
Browse files Browse the repository at this point in the history
  • Loading branch information
bhaidar committed Apr 13, 2019
1 parent 979c3ae commit dfb0fdd
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 8 deletions.
6 changes: 6 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,17 @@
"@nestjs/common": "6.1.0",
"@nestjs/core": "6.1.0",
"@nestjs/jwt": "^6.0.0",
"@nestjs/passport": "^6.0.0",
"@nestjs/platform-express": "6.1.0",
"@nestjs/typeorm": "6.0.0",
"bcrypt": "^3.0.5",
"class-transformer": "0.2.0",
"class-validator": "0.9.1",
"dotenv": "7.0.0",
"global": "^4.3.2",
"passport": "^0.4.0",
"passport-http-bearer": "^1.0.1",
"passport-jwt": "^4.0.0",
"pg": "7.9.0",
"reflect-metadata": "0.1.12",
"rxjs": "6.4.0",
Expand All @@ -48,6 +52,8 @@
"@types/express": "4.16.1",
"@types/jest": "24.0.11",
"@types/node": "10.14.4",
"@types/passport": "^1.0.0",
"@types/passport-jwt": "^3.0.1",
"@types/supertest": "2.0.7",
"@types/uuid": "3.4.4",
"jest": "^23.5.0",
Expand Down
5 changes: 2 additions & 3 deletions server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ import { UsersModule } from './users/users.module';
import { CoreModule } from './core/core.module';
import { AuthModule } from './auth/auth.module';

@Module({
imports: [AuthModule]
})
@Module({})
export class AppModule {
static forRoot(connOptions: ConnectionOptions): DynamicModule {
return {
module: AppModule,
controllers: [AppController],
imports: [
AuthModule,
TodoModule,
UsersModule,
CoreModule,
Expand Down
14 changes: 14 additions & 0 deletions server/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@ import {
HttpStatus,
UsePipes,
ValidationPipe,
Get,
Req,
UseGuards,
} from '@nestjs/common';
import { UserDto } from '@user/dto/user.dto';
import { UserCreateDto } from '@user/dto/user.create.dto';
import { RegistrationStatus } from './interfaces/regisration-status.interface';
import { AuthService } from './auth.service';
import { LoginStatus } from './interfaces/login-status.interface';
import { UserLoginDto } from '../users/dto/user-login.dto';
import { JwtPayload } from './interfaces/payload.interface';
import { get } from 'http';
import { AuthGuard } from '@nestjs/passport';
import { AdvancedConsoleLogger } from 'typeorm';

@Controller('auth')
export class AuthController {
Expand All @@ -39,4 +46,11 @@ export class AuthController {
public async login(@Body() userLoginDto: UserLoginDto): Promise<LoginStatus> {
return await this.authService.login(userLoginDto);
}

@Get('whoami')
@UseGuards(AuthGuard())
public async testAuth(@Req() req: any): Promise<JwtPayload> {
console.log(req.user);
return req.user;
}
}
7 changes: 5 additions & 2 deletions server/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@ import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UsersModule } from '@user/users.module';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
imports: [
UsersModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: process.env.EXPIRESIN,
expiresIn: '12h',
},
}),
],
controllers: [AuthController],
providers: [AuthService],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
8 changes: 8 additions & 0 deletions server/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ export class AuthService {
};
}

async validateUser(payload: JwtPayload): Promise<UserDto> {
const user = await this.usersService.findByPayload(payload);
if (!user) {
throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
}
return user;
}

private _sanitizeUser(user: UserEntity) {
delete user.password;
return user;
Expand Down
24 changes: 24 additions & 0 deletions server/src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { JwtPayload } from './interfaces/payload.interface';
import { UserDto } from '@user/dto/user.dto';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}

async validate(payload: JwtPayload): Promise<UserDto> {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
}
return user;
}
}
4 changes: 4 additions & 0 deletions server/src/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export class UsersService {
return toUserDto(user);
}

async findByPayload({ username }: any): Promise<UserDto> {
return await this.findOne({ where: { username } });
}

async create(userDto: UserCreateDto): Promise<UserDto> {
const { username, password, email } = userDto;

Expand Down
2 changes: 1 addition & 1 deletion server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es5",
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./dist",
Expand Down
94 changes: 92 additions & 2 deletions server/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@
"@types/jsonwebtoken" "7.2.8"
jsonwebtoken "8.4.0"

"@nestjs/passport@^6.0.0":
version "6.0.0"
resolved "https://registry.yarnpkg.com/@nestjs/passport/-/passport-6.0.0.tgz#b92fdf90e055eece02c0378fce98e6f60a864c54"
integrity sha512-+82YJTQpmDrcqS65Jgtdv6+n5lWCZtANw7Cy3KWdSKPBbNheIYBWtKMV2uXZXXtVqxgGaCnrJ03XpHc22RX4xA==

"@nestjs/platform-express@6.1.0":
version "6.1.0"
resolved "https://registry.yarnpkg.com/@nestjs/platform-express/-/platform-express-6.1.0.tgz#4058d5d62433fa0eef91a3383c0ce54e0c9d4da7"
Expand Down Expand Up @@ -120,7 +125,7 @@
"@types/node" "*"
"@types/range-parser" "*"

"@types/express@4.16.1":
"@types/express@*", "@types/express@4.16.1":
version "4.16.1"
resolved "https://registry.yarnpkg.com/@types/express/-/express-4.16.1.tgz#d756bd1a85c34d87eaf44c888bad27ba8a4b7cf0"
integrity sha512-V0clmJow23WeyblmACoxbHBu2JKlE5TiIme6Lem14FnPW9gsttyHtk6wq7njcdIWH1njAaFgR8gW09lgY98gQg==
Expand All @@ -146,6 +151,13 @@
resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee"
integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4=

"@types/jsonwebtoken@*":
version "8.3.2"
resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-8.3.2.tgz#e3d5245197152346fae7ee87d5541aa5a92d0362"
integrity sha512-Mkjljd9DTpkPlrmGfTJvcP4aBU7yO2QmW7wNVhV4/6AEUxYoacqU7FJU/N0yFEHTsIrE4da3rUrjrR5ejicFmA==
dependencies:
"@types/node" "*"

"@types/jsonwebtoken@7.2.8":
version "7.2.8"
resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-7.2.8.tgz#8d199dab4ddb5bba3234f8311b804d2027af2b3a"
Expand All @@ -168,6 +180,30 @@
resolved "https://registry.yarnpkg.com/@types/node/-/node-10.14.4.tgz#1c586b991457cbb58fef51bc4e0cfcfa347714b5"
integrity sha512-DT25xX/YgyPKiHFOpNuANIQIVvYEwCWXgK2jYYwqgaMrYE6+tq+DtmMwlD3drl6DJbUwtlIDnn0d7tIn/EbXBg==

"@types/passport-jwt@^3.0.1":
version "3.0.1"
resolved "https://registry.yarnpkg.com/@types/passport-jwt/-/passport-jwt-3.0.1.tgz#bc4c2610815565de977ea1a580c047d71c646084"
integrity sha512-JwF9U/Rmr6YicHSu/MITmHNDy2KeiedxKW2bhz6wZts3y4cq48NiN0UD98zO56TyM5Vm6BpyjFxcs6jh68ni/A==
dependencies:
"@types/express" "*"
"@types/jsonwebtoken" "*"
"@types/passport-strategy" "*"

"@types/passport-strategy@*":
version "0.2.35"
resolved "https://registry.yarnpkg.com/@types/passport-strategy/-/passport-strategy-0.2.35.tgz#e52f5212279ea73f02d9b06af67efe9cefce2d0c"
integrity sha512-o5D19Jy2XPFoX2rKApykY15et3Apgax00RRLf0RUotPDUsYrQa7x4howLYr9El2mlUApHmCMv5CZ1IXqKFQ2+g==
dependencies:
"@types/express" "*"
"@types/passport" "*"

"@types/passport@*", "@types/passport@^1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@types/passport/-/passport-1.0.0.tgz#747fa127a747a145ff279f3df3e07c425e5ff297"
integrity sha512-R2FXqM+AgsMIym0PuKj08Ybx+GR6d2rU3b1/8OcHolJ+4ga2pRPX105wboV6hq1AJvMo2frQzYKdqXS5+4cyMw==
dependencies:
"@types/express" "*"

"@types/range-parser@*":
version "1.2.3"
resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.3.tgz#7ee330ba7caafb98090bece86a5ee44115904c2c"
Expand Down Expand Up @@ -3036,6 +3072,22 @@ jsonwebtoken@8.4.0:
lodash.once "^4.0.0"
ms "^2.1.1"

jsonwebtoken@^8.2.0:
version "8.5.1"
resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz#00e71e0b8df54c2121a1f26137df2280673bcc0d"
integrity sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==
dependencies:
jws "^3.2.2"
lodash.includes "^4.3.0"
lodash.isboolean "^3.0.3"
lodash.isinteger "^4.0.4"
lodash.isnumber "^3.0.3"
lodash.isplainobject "^4.0.6"
lodash.isstring "^4.0.1"
lodash.once "^4.0.0"
ms "^2.1.1"
semver "^5.6.0"

jsprim@^1.2.2:
version "1.4.1"
resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2"
Expand All @@ -3055,7 +3107,7 @@ jwa@^1.4.1:
ecdsa-sig-formatter "1.0.11"
safe-buffer "^5.0.1"

jws@^3.1.5:
jws@^3.1.5, jws@^3.2.2:
version "3.2.2"
resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304"
integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==
Expand Down Expand Up @@ -3945,6 +3997,34 @@ pascalcase@^0.1.1:
resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14"
integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=

passport-http-bearer@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/passport-http-bearer/-/passport-http-bearer-1.0.1.tgz#147469ea3669e2a84c6167ef99dbb77e1f0098a8"
integrity sha1-FHRp6jZp4qhMYWfvmdu3fh8AmKg=
dependencies:
passport-strategy "1.x.x"

passport-jwt@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/passport-jwt/-/passport-jwt-4.0.0.tgz#7f0be7ba942e28b9f5d22c2ebbb8ce96ef7cf065"
integrity sha512-BwC0n2GP/1hMVjR4QpnvqA61TxenUMlmfNjYNgK0ZAs0HK4SOQkHcSv4L328blNTLtHq7DbmvyNJiH+bn6C5Mg==
dependencies:
jsonwebtoken "^8.2.0"
passport-strategy "^1.0.0"

passport-strategy@1.x.x, passport-strategy@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/passport-strategy/-/passport-strategy-1.0.0.tgz#b5539aa8fc225a3d1ad179476ddf236b440f52e4"
integrity sha1-tVOaqPwiWj0a0XlHbd8ja0QPUuQ=

passport@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/passport/-/passport-0.4.0.tgz#c5095691347bd5ad3b5e180238c3914d16f05811"
integrity sha1-xQlWkTR71a07XhgCOMORTRbwWBE=
dependencies:
passport-strategy "1.x.x"
pause "0.0.1"

path-dirname@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0"
Expand Down Expand Up @@ -3996,6 +4076,11 @@ path-type@^1.0.0:
pify "^2.0.0"
pinkie-promise "^2.0.0"

pause@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d"
integrity sha1-HUCLP9t2kjuVQ9lvtMnf1TXZy10=

performance-now@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
Expand Down Expand Up @@ -4537,6 +4622,11 @@ semver@4.3.2:
resolved "https://registry.yarnpkg.com/semver/-/semver-4.3.2.tgz#c7a07158a80bedd052355b770d82d6640f803be7"
integrity sha1-x6BxWKgL7dBSNVt3DYLWZA+AO+c=

semver@^5.6.0:
version "5.7.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b"
integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==

send@0.16.2:
version "0.16.2"
resolved "https://registry.yarnpkg.com/send/-/send-0.16.2.tgz#6ecca1e0f8c156d141597559848df64730a6bbc1"
Expand Down

0 comments on commit dfb0fdd

Please sign in to comment.