Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
ndrwbv committed Jul 29, 2020
0 parents commit 609d1bf
Show file tree
Hide file tree
Showing 71 changed files with 20,687 additions and 0 deletions.
70 changes: 70 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@

node_modules/
dist/
coverage/
.DS_Store
pgdata

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file

.DS_Store
# next.js build output
.next

build
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# vk-auth-react-nestjs
26 changes: 26 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
POSTGRES_USER=root
POSTGRES_PASSWORD=root
POSTGRES_DB=test

DB_HOST=localhost
DB_PORT=5432
DB_USER=root
DB_PASSWORD=root
DB_DATABASE=test
DB_ENTITIES=src/entities/*.entity.ts
DB_SYNCRONIZE=true
DB_LOGGING=true
DB_MIGRATIONS_RUN=true
DB_MIGRATIONS_DIR=migrations


JWT_SECRET=OPrivet
JWT_EXPIRES=3600m

APP_HOST=https://site.com
APP_LOCAL=http://localhost:3000

CLIENT_ID=7552509
CLIENT_SECRET=NKzXhiDnRfSMN9McnePH

PORT=8888
21 changes: 21 additions & 0 deletions backend/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Aaryanna Simonelli

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
14 changes: 14 additions & 0 deletions backend/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
version: '3.4'
services:
db:
image: postgres
env_file: .env
volumes:
- ./pgdata:/var/lib/postgresql/data
ports:
- '5432:5432'
healthcheck:
test: "cat /proc/net/tcp /proc/net/tcp6 | grep ':0CEB'"
interval: 10s
timeout: 5s
retries: 5
13 changes: 13 additions & 0 deletions backend/ecosystem.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
apps: [
{
name: "nestjs-postgres-auth-roles",
script: "yarn",
args: "start:prod",
interpreter: "/bin/bash",
env: {
NODE_ENV: "development"
}
}
]
};
10 changes: 10 additions & 0 deletions backend/nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"watch": [
"src"
],
"ext": "ts",
"ignore": [
"src/**/*.spec.ts"
],
"exec": "ts-node -r tsconfig-paths/register src/main.ts"
}
86 changes: 86 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
{
"name": "nestjs-postgres-auth-roles",
"version": "1.0.0",
"description": "nestjs-postgres-auth-roles",
"author": "ndrwbv",
"license": "MIT",
"repository": "",
"scripts": {
"parse": "node -r dotenv/config parser/",
"format": "prettier --write \"**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"dev": "nodemon",
"prestart:prod": "rm -rf dist && tsc",
"start:prod": "nodemon dist/src/main.js",
"start:hmr": "node dist/server",
"test": "jest",
"test:cov": "jest --coverage",
"test:e2e": "jest --config ./test/jest-e2e.json",
"webpack": "webpack --config webpack.config.js",
"coveralls": "yarn run test:cov --coverageReporters=text-lcov | coveralls"
},
"dependencies": {
"@nestjs/common": "^6.11.11",
"@nestjs/core": "^6.11.11",
"@nestjs/jwt": "^6.1.2",
"@nestjs/microservices": "^6.11.11",
"@nestjs/passport": "^6.2.0",
"@nestjs/platform-express": "^6.11.11",
"@nestjs/schedule": "^0.2.0",
"@nestjs/testing": "^6.11.11",
"@nestjs/typeorm": "^6.3.3",
"@nestjs/websockets": "^6.11.11",
"@types/express": "^4.17.3",
"@types/jest": "^25.1.3",
"@types/node": "^13.7.7",
"@types/supertest": "^2.0.8",
"bcrypt": "^4.0.1",
"class-transformer": "^0.2.3",
"class-validator": "^0.11.0",
"coveralls": "^3.0.9",
"fastify-formbody": "^3.1.0",
"jest": "^25.1.0",
"minimist": "1.2.5",
"mysql": "^2.18.1",
"nestjs-config": "^1.4.5",
"nodemon": "^2.0.2",
"passport": "^0.4.1",
"passport-http-bearer": "^1.0.1",
"passport-jwt": "^4.0.0",
"pg": "^7.18.2",
"prettier": "^1.19.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^6.5.4",
"slugify": "^1.4.0",
"supertest": "^4.0.2",
"ts-jest": "^25.2.1",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"tslint": "^6.0.0",
"typeorm": "^0.2.24",
"typescript": "^3.8.3",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-node-externals": "^1.7.2"
},
"devDependencies": {},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"collectCoverageFrom": [
"!src/config/**",
"!src/models/**",
"!src/entities/**"
]
}
}
24 changes: 24 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as path from 'path';

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from 'nestjs-config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ScheduleModule } from '@nestjs/schedule';

import { AuthModule } from './auth';
import { UserModule } from './user';

@Module({
imports: [
ScheduleModule.forRoot(),
ConfigModule.load(path.resolve(__dirname, 'config', '*.{ts,js}')),
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('database'),
inject: [ConfigService],
}),

UserModule,
AuthModule,
],
})
export class AppModule {}
82 changes: 82 additions & 0 deletions backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {
Controller,
Post,
Body,
ValidationPipe,
UnprocessableEntityException,
} from "@nestjs/common";
import { AuthModel, UserModel, AuthVK, IGrant } from "./../models";
import { AuthService } from "./auth.service";
import { UserService } from "./../user";

@Controller("auth")
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly userService: UserService
) {}

@Post("/login/vk")
async vk(@Body(new ValidationPipe()) auth: AuthVK): Promise<any> {
let authData;

try {
authData = await this.authService.getVkToken(auth.code);
} catch (err) {
throw new UnprocessableEntityException("Wrong VK code");
}

if (!authData.data.hasOwnProperty("email")) {
throw new UnprocessableEntityException("Email should be provided");
}

const emailUser = await this.userService.findByEmail(authData.data.email);

if (emailUser) {
return this.authService.authenticate(emailUser, true);
}

try {
const { data } = await this.authService.getUserDataFromVk(
authData.data.user_id,
authData.data.access_token
);

const profile = data.response[0];

let user: UserModel = {
email: authData.data.email,
password: null,
name: `${profile.first_name} ${profile.last_name}`,
avatar_url: profile.photo_400,
grant: IGrant.USER,
};

await this.userService.create(user);

return this.authService.authenticate(user, true);
} catch (err) {
throw new UnprocessableEntityException(err);
}
}

@Post("/login")
async login(@Body(new ValidationPipe()) auth: AuthModel): Promise<string> {
return this.authService.authenticate(auth);
}

@Post("/register")
async register(
@Body(new ValidationPipe()) userModel: UserModel
): Promise<string> {
const emailExists = await this.userService.findByEmail(userModel.email);

if (emailExists) {
throw new UnprocessableEntityException();
}

await this.userService.create(userModel);

return this.authService.authenticate(userModel);
}
}
24 changes: 24 additions & 0 deletions backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Module, HttpModule } from "@nestjs/common";
import { UserModule } from "./../user";
import { AuthService } from "./auth.service";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { ConfigModule, ConfigService } from "nestjs-config";
import { AuthController } from "./auth.controller";
import { JwtStrategy } from "./jwt.strategy";

@Module({
imports: [
HttpModule,
UserModule,
ConfigModule,
PassportModule.register({ defaultStrategy: "jwt" }),
JwtModule.registerAsync({
useFactory: (config: ConfigService) => config.get("jwt"),
inject: [ConfigService],
}),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
})
export class AuthModule {}
Loading

0 comments on commit 609d1bf

Please sign in to comment.