mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2026-01-05 12:34:26 +00:00
add email account validation
This commit is contained in:
@@ -8,11 +8,11 @@ import {
|
||||
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';
|
||||
} 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 {
|
||||
@@ -20,28 +20,31 @@ export class UsersController {
|
||||
|
||||
@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;
|
||||
const { page, pageSize, searchNameTerm, searchEmailTerm } = Pagination.getPaginationData(query)
|
||||
const users = await this.usersService.getUsers(page, pageSize, searchNameTerm, searchEmailTerm)
|
||||
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,
|
||||
);
|
||||
createUserDto.email
|
||||
)
|
||||
}
|
||||
|
||||
@UseGuards(BaseAuthGuard)
|
||||
@Delete(':id')
|
||||
async remove(@Param('id') id: string) {
|
||||
return await this.usersService.deleteUserById(id);
|
||||
return await this.usersService.deleteUserById(id)
|
||||
}
|
||||
|
||||
@UseGuards(BaseAuthGuard)
|
||||
@Delete()
|
||||
async removeAll() {
|
||||
return await this.usersService.deleteAllUsers()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Length, Matches } from 'class-validator';
|
||||
import { Length, Matches } from 'class-validator'
|
||||
|
||||
export class CreateUserDto {
|
||||
@Length(3, 10)
|
||||
login: string;
|
||||
login: string
|
||||
@Length(6, 20)
|
||||
password: string;
|
||||
password: string
|
||||
@Matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/)
|
||||
email: string;
|
||||
email: string
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateUserDto } from './create-user.dto';
|
||||
import { PartialType } from '@nestjs/mapped-types'
|
||||
import { CreateUserDto } from './create-user.dto'
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
||||
|
||||
@@ -4,12 +4,12 @@ import {
|
||||
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';
|
||||
} 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 {
|
||||
@@ -19,12 +19,16 @@ export class UsersRepository implements IUsersRepository {
|
||||
currentPage: number,
|
||||
itemsPerPage: number,
|
||||
searchNameTerm: string,
|
||||
searchEmailTerm: string
|
||||
): Promise<EntityWithPaginationType<UserViewType>> {
|
||||
const where = {
|
||||
name: {
|
||||
search: searchNameTerm,
|
||||
search: searchNameTerm || undefined,
|
||||
},
|
||||
};
|
||||
email: {
|
||||
search: searchEmailTerm || undefined,
|
||||
},
|
||||
}
|
||||
const [totalItems, users] = await this.prisma.$transaction([
|
||||
this.prisma.user.count({ where }),
|
||||
this.prisma.user.findMany({
|
||||
@@ -32,23 +36,23 @@ export class UsersRepository implements IUsersRepository {
|
||||
skip: (currentPage - 1) * itemsPerPage,
|
||||
take: itemsPerPage,
|
||||
}),
|
||||
]);
|
||||
])
|
||||
|
||||
console.log(users, 'usersFromBase');
|
||||
const totalPages = Math.ceil(totalItems / itemsPerPage);
|
||||
const usersView = users.map((u) => ({
|
||||
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---');
|
||||
}))
|
||||
console.log(usersView, 'users---')
|
||||
return {
|
||||
totalPages,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
totalItems,
|
||||
items: usersView,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createUser(newUser: CreateUserInput): Promise<User | null> {
|
||||
@@ -67,7 +71,7 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
verification: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
@@ -75,34 +79,37 @@ export class UsersRepository implements IUsersRepository {
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
return result.isDeleted;
|
||||
})
|
||||
return result.isDeleted
|
||||
}
|
||||
|
||||
async deleteAllUsers(): Promise<boolean> {
|
||||
const result = await this.prisma.user.deleteMany()
|
||||
return result.count > 0
|
||||
}
|
||||
|
||||
async findUserById(id: string): Promise<User | null> {
|
||||
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||
const user = await this.prisma.user.findUnique({ where: { id } })
|
||||
if (!user) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
return user;
|
||||
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 null
|
||||
}
|
||||
return user;
|
||||
return user
|
||||
}
|
||||
|
||||
async findUserByVerificationToken(
|
||||
token: string,
|
||||
): Promise<VerificationWithUser | null> {
|
||||
async findUserByVerificationToken(token: string): Promise<VerificationWithUser | null> {
|
||||
const verification = await this.prisma.verification.findUnique({
|
||||
where: {
|
||||
verificationToken: token,
|
||||
@@ -110,11 +117,11 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
if (!verification) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
return verification;
|
||||
return verification
|
||||
}
|
||||
|
||||
async updateConfirmation(id: string) {
|
||||
@@ -125,8 +132,8 @@ export class UsersRepository implements IUsersRepository {
|
||||
data: {
|
||||
isEmailVerified: true,
|
||||
},
|
||||
});
|
||||
return result.isEmailVerified;
|
||||
})
|
||||
return result.isEmailVerified
|
||||
}
|
||||
|
||||
async updateVerificationToken(id: string) {
|
||||
@@ -141,7 +148,7 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async revokeToken(id: string, token: string): Promise<User | null> {
|
||||
@@ -155,10 +162,10 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
if (!revokedToken.user) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
return revokedToken.user;
|
||||
return revokedToken.user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,26 @@
|
||||
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';
|
||||
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'
|
||||
import { MailerService } from '@nestjs-modules/mailer'
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private usersRepository: UsersRepository) {}
|
||||
constructor(private usersRepository: UsersRepository, private emailService: MailerService) {}
|
||||
|
||||
async getUsers(page: number, pageSize: number, searchNameTerm: string) {
|
||||
return await this.usersRepository.getUsers(page, pageSize, searchNameTerm);
|
||||
async getUsers(page: number, pageSize: number, searchNameTerm: string, searchEmailTerm: string) {
|
||||
return await this.usersRepository.getUsers(page, pageSize, searchNameTerm, searchEmailTerm)
|
||||
}
|
||||
|
||||
async getUserById(id: string) {
|
||||
return await this.usersRepository.findUserById(id);
|
||||
return await this.usersRepository.findUserById(id)
|
||||
}
|
||||
|
||||
async createUser(
|
||||
name: string,
|
||||
password: string,
|
||||
email: string,
|
||||
): Promise<UserViewType | null> {
|
||||
const passwordHash = await this._generateHash(password);
|
||||
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,
|
||||
@@ -36,37 +28,51 @@ export class UsersService {
|
||||
verificationToken: uuidv4(),
|
||||
verificationTokenExpiry: addHours(new Date(), 24),
|
||||
isEmailVerified: false,
|
||||
};
|
||||
const createdUser = await this.usersRepository.createUser(newUser);
|
||||
if (!createdUser) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const createdUser = await this.usersRepository.createUser(newUser)
|
||||
if (!createdUser) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
await this.emailService.sendMail({
|
||||
from: 'andrii <andrii@andrii.es>',
|
||||
to: createdUser.email,
|
||||
text: 'hello and welcome',
|
||||
subject: 'E-mail confirmation ',
|
||||
})
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
return {
|
||||
id: createdUser.id,
|
||||
name: createdUser.name,
|
||||
email: createdUser.email,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
return await this.usersRepository.deleteUserById(id);
|
||||
return await this.usersRepository.deleteUserById(id)
|
||||
}
|
||||
|
||||
async deleteAllUsers(): Promise<boolean> {
|
||||
return await this.usersRepository.deleteAllUsers()
|
||||
}
|
||||
|
||||
async addRevokedToken(token: string) {
|
||||
const secretKey = process.env.JWT_SECRET_KEY;
|
||||
if (!secretKey) throw new Error('JWT_SECRET_KEY is not defined');
|
||||
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);
|
||||
const decoded: any = jwt.verify(token, secretKey)
|
||||
return this.usersRepository.revokeToken(decoded.userId, token)
|
||||
} catch (e) {
|
||||
console.log('Decoding error: e');
|
||||
return null;
|
||||
console.log(`Decoding error: ${e}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private async _generateHash(password: string) {
|
||||
return await bcrypt.hash(password, 10);
|
||||
return await bcrypt.hash(password, 10)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +81,14 @@ export interface IUsersRepository {
|
||||
page: number,
|
||||
pageSize: number,
|
||||
searchNameTerm: string,
|
||||
): Promise<EntityWithPaginationType<UserViewType>>;
|
||||
searchEmailTerm: string
|
||||
): Promise<EntityWithPaginationType<UserViewType>>
|
||||
|
||||
createUser(newUser: CreateUserInput): Promise<User | null>;
|
||||
createUser(newUser: CreateUserInput): Promise<User | null>
|
||||
|
||||
deleteUserById(id: string): Promise<boolean>;
|
||||
deleteUserById(id: string): Promise<boolean>
|
||||
|
||||
findUserById(id: string): Promise<User | null>;
|
||||
findUserById(id: string): Promise<User | null>
|
||||
|
||||
revokeToken(id: string, token: string): Promise<User | null>;
|
||||
revokeToken(id: string, token: string): Promise<User | null>
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './services/users.service';
|
||||
import { UsersController } from './api/users.controller';
|
||||
import { UsersRepository } from './infrastructure/users.repository';
|
||||
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],
|
||||
|
||||
Reference in New Issue
Block a user