mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2026-01-05 12:34:26 +00:00
add auth
This commit is contained in:
47
src/modules/users/api/users.controller.ts
Normal file
47
src/modules/users/api/users.controller.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UsersService } from '../services/users.service';
|
||||
import { CreateUserDto } from '../dto/create-user.dto';
|
||||
import { Pagination } from '../../../infrastructure/common/pagination.service';
|
||||
import { BaseAuthGuard } from '../../auth/guards/base-auth.guard';
|
||||
|
||||
@Controller('users')
|
||||
export class UsersController {
|
||||
constructor(private usersService: UsersService) {}
|
||||
|
||||
@Get()
|
||||
async findAll(@Query() query) {
|
||||
const { page, pageSize, searchNameTerm } =
|
||||
Pagination.getPaginationData(query);
|
||||
const users = await this.usersService.getUsers(
|
||||
page,
|
||||
pageSize,
|
||||
searchNameTerm,
|
||||
);
|
||||
if (!users) throw new NotFoundException('Users not found');
|
||||
return users;
|
||||
}
|
||||
//@UseGuards(BaseAuthGuard)
|
||||
@Post()
|
||||
async create(@Body() createUserDto: CreateUserDto) {
|
||||
return await this.usersService.createUser(
|
||||
createUserDto.login,
|
||||
createUserDto.password,
|
||||
createUserDto.email,
|
||||
);
|
||||
}
|
||||
@UseGuards(BaseAuthGuard)
|
||||
@Delete(':id')
|
||||
async remove(@Param('id') id: string) {
|
||||
return await this.usersService.deleteUserById(id);
|
||||
}
|
||||
}
|
||||
10
src/modules/users/dto/create-user.dto.ts
Normal file
10
src/modules/users/dto/create-user.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Length, Matches } from 'class-validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@Length(3, 10)
|
||||
login: string;
|
||||
@Length(6, 20)
|
||||
password: string;
|
||||
@Matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/)
|
||||
email: string;
|
||||
}
|
||||
4
src/modules/users/dto/update-user.dto.ts
Normal file
4
src/modules/users/dto/update-user.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateUserDto } from './create-user.dto';
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
||||
164
src/modules/users/infrastructure/users.repository.ts
Normal file
164
src/modules/users/infrastructure/users.repository.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import {
|
||||
CreateUserInput,
|
||||
EntityWithPaginationType,
|
||||
User,
|
||||
UserViewType,
|
||||
VerificationWithUser,
|
||||
} from '../../../types/types';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { addHours } from 'date-fns';
|
||||
import { IUsersRepository } from '../services/users.service';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../../../prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class UsersRepository implements IUsersRepository {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getUsers(
|
||||
currentPage: number,
|
||||
itemsPerPage: number,
|
||||
searchNameTerm: string,
|
||||
): Promise<EntityWithPaginationType<UserViewType>> {
|
||||
const where = {
|
||||
name: {
|
||||
search: searchNameTerm,
|
||||
},
|
||||
};
|
||||
const [totalItems, users] = await this.prisma.$transaction([
|
||||
this.prisma.user.count({ where }),
|
||||
this.prisma.user.findMany({
|
||||
where,
|
||||
skip: (currentPage - 1) * itemsPerPage,
|
||||
take: itemsPerPage,
|
||||
}),
|
||||
]);
|
||||
|
||||
console.log(users, 'usersFromBase');
|
||||
const totalPages = Math.ceil(totalItems / itemsPerPage);
|
||||
const usersView = users.map((u) => ({
|
||||
id: u.id,
|
||||
name: u.name,
|
||||
email: u.email,
|
||||
}));
|
||||
console.log(usersView, 'users---');
|
||||
return {
|
||||
totalPages,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
totalItems,
|
||||
items: usersView,
|
||||
};
|
||||
}
|
||||
|
||||
async createUser(newUser: CreateUserInput): Promise<User | null> {
|
||||
return await this.prisma.user.create({
|
||||
data: {
|
||||
email: newUser.email,
|
||||
password: newUser.password,
|
||||
name: newUser.name,
|
||||
verification: {
|
||||
create: {
|
||||
verificationToken: newUser.verificationToken,
|
||||
verificationTokenExpiry: newUser.verificationTokenExpiry,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
verification: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
const result = await this.prisma.user.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
return result.isDeleted;
|
||||
}
|
||||
|
||||
async findUserById(id: string): Promise<User | null> {
|
||||
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async findUserByEmail(email: string): Promise<User | null> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { email },
|
||||
include: { verification: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async findUserByVerificationToken(
|
||||
token: string,
|
||||
): Promise<VerificationWithUser | null> {
|
||||
const verification = await this.prisma.verification.findUnique({
|
||||
where: {
|
||||
verificationToken: token,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
if (!verification) {
|
||||
return null;
|
||||
}
|
||||
return verification;
|
||||
}
|
||||
|
||||
async updateConfirmation(id: string) {
|
||||
const result = await this.prisma.verification.update({
|
||||
where: {
|
||||
userId: id,
|
||||
},
|
||||
data: {
|
||||
isEmailVerified: true,
|
||||
},
|
||||
});
|
||||
return result.isEmailVerified;
|
||||
}
|
||||
|
||||
async updateVerificationToken(id: string) {
|
||||
return await this.prisma.verification.update({
|
||||
where: {
|
||||
userId: id,
|
||||
},
|
||||
data: {
|
||||
verificationToken: uuidv4(),
|
||||
verificationTokenExpiry: addHours(new Date(), 24),
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async revokeToken(id: string, token: string): Promise<User | null> {
|
||||
const revokedToken = await this.prisma.accessToken.update({
|
||||
where: {
|
||||
token: token,
|
||||
},
|
||||
data: {
|
||||
isRevoked: true,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
if (!revokedToken.user) {
|
||||
return null;
|
||||
}
|
||||
return revokedToken.user;
|
||||
}
|
||||
}
|
||||
87
src/modules/users/services/users.service.ts
Normal file
87
src/modules/users/services/users.service.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import {
|
||||
CreateUserInput,
|
||||
EntityWithPaginationType,
|
||||
User,
|
||||
UserViewType,
|
||||
} from '../../../types/types';
|
||||
import { addHours } from 'date-fns';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { UsersRepository } from '../infrastructure/users.repository';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private usersRepository: UsersRepository) {}
|
||||
|
||||
async getUsers(page: number, pageSize: number, searchNameTerm: string) {
|
||||
return await this.usersRepository.getUsers(page, pageSize, searchNameTerm);
|
||||
}
|
||||
|
||||
async getUserById(id: string) {
|
||||
return await this.usersRepository.findUserById(id);
|
||||
}
|
||||
|
||||
async createUser(
|
||||
name: string,
|
||||
password: string,
|
||||
email: string,
|
||||
): Promise<UserViewType | null> {
|
||||
const passwordHash = await this._generateHash(password);
|
||||
const newUser: CreateUserInput = {
|
||||
name: name || email.split('@')[0],
|
||||
email: email,
|
||||
password: passwordHash,
|
||||
verificationToken: uuidv4(),
|
||||
verificationTokenExpiry: addHours(new Date(), 24),
|
||||
isEmailVerified: false,
|
||||
};
|
||||
const createdUser = await this.usersRepository.createUser(newUser);
|
||||
if (!createdUser) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: createdUser.id,
|
||||
name: createdUser.name,
|
||||
email: createdUser.email,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
return await this.usersRepository.deleteUserById(id);
|
||||
}
|
||||
|
||||
async addRevokedToken(token: string) {
|
||||
const secretKey = process.env.JWT_SECRET_KEY;
|
||||
if (!secretKey) throw new Error('JWT_SECRET_KEY is not defined');
|
||||
|
||||
try {
|
||||
const decoded: any = jwt.verify(token, secretKey);
|
||||
return this.usersRepository.revokeToken(decoded.userId, token);
|
||||
} catch (e) {
|
||||
console.log('Decoding error: e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private async _generateHash(password: string) {
|
||||
return await bcrypt.hash(password, 10);
|
||||
}
|
||||
}
|
||||
|
||||
export interface IUsersRepository {
|
||||
getUsers(
|
||||
page: number,
|
||||
pageSize: number,
|
||||
searchNameTerm: string,
|
||||
): Promise<EntityWithPaginationType<UserViewType>>;
|
||||
|
||||
createUser(newUser: CreateUserInput): Promise<User | null>;
|
||||
|
||||
deleteUserById(id: string): Promise<boolean>;
|
||||
|
||||
findUserById(id: string): Promise<User | null>;
|
||||
|
||||
revokeToken(id: string, token: string): Promise<User | null>;
|
||||
}
|
||||
11
src/modules/users/users.module.ts
Normal file
11
src/modules/users/users.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './services/users.service';
|
||||
import { UsersController } from './api/users.controller';
|
||||
import { UsersRepository } from './infrastructure/users.repository';
|
||||
|
||||
@Module({
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService, UsersRepository],
|
||||
exports: [UsersRepository, UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
Reference in New Issue
Block a user