Commit bf28139e authored by Цой Кирилл's avatar Цой Кирилл

Initial commit

parents
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "auth-service",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/sequelize": "^10.0.1",
"bcryptjs": "^2.4.3",
"mysql2": "^3.11.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"sequelize": "^6.37.3",
"sequelize-typescript": "^2.1.6"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/sequelize": "^4.28.20",
"@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
import { Module } from "@nestjs/common"
import { DatabaseModule } from './database/database.module';
import { UsersModule } from './users/users.module';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [UsersModule, DatabaseModule, AuthModule]
})
export class AppModule {}
\ No newline at end of file
import { Body, Controller, Post } from '@nestjs/common';
import { UserDto } from '../users/models/user.dto';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post("/auth")
async auth(@Body() userDto: UserDto){
return await this.authService.auth(userDto)
}
@Post("/register")
async register(@Body() userDto: UserDto){
return await this.authService.register(userDto)
}
}
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UsersModule } from 'src/users/users.module';
@Module({
controllers: [AuthController],
providers: [AuthService],
imports: [
PassportModule,
UsersModule,
JwtModule.register({
secret: "secret",
signOptions: {
expiresIn: "12h"
}
})
],
exports: [
AuthService,
JwtModule
]
})
export class AuthModule {}
import { Body, HttpException, HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
import { UserDto } from '../users/models/user.dto';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from "bcryptjs"
import { User } from '../users/models/user.entity';
@Injectable()
export class AuthService {
constructor(
private readonly userService: UsersService,
private readonly jwtService: JwtService
) {}
async auth(userDto: UserDto){
const user = await this.validateUser(userDto)
return this.generateToken(user)
}
async register(userDto: UserDto){
const candidate = await this.userService.getUserByEmail(userDto.email)
if (candidate) throw new HttpException('User already exists', HttpStatus.BAD_REQUEST)
const hashPassword = await bcrypt.hash(candidate.password, 5)
const user = await this.userService.createUser({ ...userDto, password: hashPassword})
return this.generateToken(user)
}
async generateToken(user: User) {
const payload = {
email: user.email,
id: user.id,
name: user.name
}
return {
token: this.jwtService.sign(payload)
}
}
async validateUser(userDto: UserDto){
const user = await this.userService.getUserByEmail(userDto.email)
const passwordValid = await bcrypt.compare(userDto.password, user.password)
if (user && passwordValid) return user
throw new UnauthorizedException({ messaage: "Invalid password" })
}
}
import { CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { JwtService } from '@nestjs/jwt';
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
) {}
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
try {
const req = context.switchToHttp().getRequest()
const authHeader = req.headers.authorization
const bearer = authHeader.split(" ")[0]
const token = authHeader.split(" ")[1]
if (bearer !== 'bearer' || !token){
throw new UnauthorizedException({ message: "Unauth" })
}
const user = this.jwtService.verify(token)
return true
} catch (error){
throw new UnauthorizedException({ message: "Unauth" })
}
}
}
\ No newline at end of file
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from '../users/models/user.entity';
@Module({
imports: [
SequelizeModule.forRoot({
dialect: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '1111',
database: 'test_db',
models: [User],
autoLoadModels: true,
synchronize: true,
}),
],
})
export class DatabaseModule {}
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function start() {
const PORT = process.env.PORT || 5000
const app = await NestFactory.create(AppModule)
await app.listen(PORT, () => console.log(`Server is running on ${PORT}`))
}
start()
\ No newline at end of file
export interface UserDto {
name: string;
email: string;
password: string
}
\ No newline at end of file
import { Column, Model, Table, DataType } from 'sequelize-typescript';
import { UserDto } from './user.dto';
@Table
export class User extends Model<User, UserDto> {
@Column({type: DataType.INTEGER, unique: true, autoIncrement: true, primaryKey: true})
id: number
@Column({type: DataType.STRING, allowNull: false})
name: string;
@Column({type: DataType.STRING, unique: true, allowNull: false})
email: string
@Column({type: DataType.STRING, allowNull: false})
password: string;
}
\ No newline at end of file
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import { UserDto } from './models/user.dto';
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/guards/jwtAuthGuard';
@Controller('users')
export class UsersController {
constructor(
private usersService: UsersService
) {}
@UseGuards(JwtAuthGuard)
@Get('get-user/:id')
async getUser(@Param('id') id: string) {
return this.usersService.getUserById(id);
}
@Post("/add-user")
async createUser(@Body() userDto: UserDto) {
return await this.usersService.createUser(userDto)
}
}
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './models/user.entity';
@Module({
providers: [UsersService],
controllers: [UsersController],
imports: [
SequelizeModule.forFeature([User])
],
exports: [UsersService]
})
export class UsersModule {}
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { User } from './models/user.entity';
import { UserDto } from './models/user.dto';
@Injectable()
export class UsersService {
constructor(
@InjectModel(User) private readonly userRepository: typeof User
) {}
async createUser(userDto: UserDto): Promise<User> {
return await this.userRepository.create(userDto)
}
async getUserById(id: string): Promise<User> {
return await this.userRepository.findOne({ where: { id } });
}
async getUserByEmail(email: string) {
return await this.userRepository.findOne({ where: { email } })
}
}
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}
Markdown is supported
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