mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2026-01-05 12:34:26 +00:00
create use cases for auth
This commit is contained in:
@@ -13,10 +13,12 @@ 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'
|
||||
import { CommandBus } from '@nestjs/cqrs'
|
||||
import { CreateUserCommand } from '../../auth/use-cases'
|
||||
|
||||
@Controller('users')
|
||||
export class UsersController {
|
||||
constructor(private usersService: UsersService) {}
|
||||
constructor(private usersService: UsersService, private commandBus: CommandBus) {}
|
||||
|
||||
@Get()
|
||||
async findAll(@Query() query) {
|
||||
@@ -29,10 +31,12 @@ export class UsersController {
|
||||
//@UseGuards(BaseAuthGuard)
|
||||
@Post()
|
||||
async create(@Body() createUserDto: CreateUserDto) {
|
||||
return await this.usersService.createUser(
|
||||
createUserDto.login,
|
||||
createUserDto.password,
|
||||
createUserDto.email
|
||||
return await this.commandBus.execute(
|
||||
new CreateUserCommand({
|
||||
name: createUserDto.name,
|
||||
email: createUserDto.email,
|
||||
password: createUserDto.password,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Length, Matches } from 'class-validator'
|
||||
|
||||
export class CreateUserDto {
|
||||
@Length(3, 10)
|
||||
login: string
|
||||
name: string
|
||||
@Length(6, 20)
|
||||
password: string
|
||||
@Matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/)
|
||||
|
||||
@@ -7,13 +7,13 @@ import {
|
||||
} 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'
|
||||
import { pick } from 'remeda'
|
||||
import { Prisma } from '@prisma/client'
|
||||
|
||||
@Injectable()
|
||||
export class UsersRepository implements IUsersRepository {
|
||||
export class UsersRepository {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getUsers(
|
||||
@@ -123,13 +123,18 @@ export class UsersRepository implements IUsersRepository {
|
||||
return verification
|
||||
}
|
||||
|
||||
async updateConfirmation(id: string) {
|
||||
async updateEmailVerification(id: string) {
|
||||
const result = await this.prisma.verification.update({
|
||||
where: {
|
||||
userId: id,
|
||||
},
|
||||
data: {
|
||||
isEmailVerified: true,
|
||||
user: {
|
||||
update: {
|
||||
isEmailVerified: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return result.isEmailVerified
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
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'
|
||||
@@ -19,47 +17,6 @@ export class UsersService {
|
||||
return await this.usersRepository.findUserById(id)
|
||||
}
|
||||
|
||||
async createUser(name: string, password: string, email: string): Promise<UserViewType | null> {
|
||||
const passwordHash = await this._generateHash(password)
|
||||
const verificationToken = uuidv4()
|
||||
const newUser: CreateUserInput = {
|
||||
name: name || email.split('@')[0],
|
||||
email: email,
|
||||
password: passwordHash,
|
||||
verificationToken,
|
||||
verificationTokenExpiry: addHours(new Date(), 24),
|
||||
isEmailVerified: false,
|
||||
}
|
||||
const createdUser = await this.usersRepository.createUser(newUser)
|
||||
if (!createdUser) {
|
||||
return null
|
||||
}
|
||||
await this.sendConfirmationEmail({
|
||||
email: createdUser.email,
|
||||
name: createdUser.name,
|
||||
verificationToken: verificationToken,
|
||||
})
|
||||
return {
|
||||
id: createdUser.id,
|
||||
name: createdUser.name,
|
||||
email: createdUser.email,
|
||||
}
|
||||
}
|
||||
async resendConfirmationEmail(userId: string) {
|
||||
const user = await this.usersRepository.findUserById(userId, { verification: true })
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
if (user.isEmailVerified) {
|
||||
return null
|
||||
}
|
||||
await this.sendConfirmationEmail({
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
verificationToken: user.verification.verificationToken,
|
||||
})
|
||||
return true
|
||||
}
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
return await this.usersRepository.deleteUserById(id)
|
||||
}
|
||||
@@ -68,19 +25,7 @@ export class UsersService {
|
||||
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')
|
||||
|
||||
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 sendConfirmationEmail({
|
||||
public async sendConfirmationEmail({
|
||||
email,
|
||||
name,
|
||||
verificationToken,
|
||||
@@ -95,30 +40,14 @@ export class UsersService {
|
||||
to: email,
|
||||
text: 'hello and welcome, token is: ' + verificationToken,
|
||||
html: `<b>Hello ${name}!</b><br/>Please confirm your email by clicking on the link below:<br/><a href="http://localhost:3000/confirm-email/${verificationToken}">Confirm email</a>`,
|
||||
subject: 'E-mail confirmation ',
|
||||
subject: 'E-mail confirmation',
|
||||
})
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
}
|
||||
private async _generateHash(password: string) {
|
||||
|
||||
public async generateHash(password: string) {
|
||||
return await bcrypt.hash(password, 10)
|
||||
}
|
||||
}
|
||||
|
||||
export interface IUsersRepository {
|
||||
getUsers(
|
||||
page: number,
|
||||
pageSize: number,
|
||||
searchNameTerm: string,
|
||||
searchEmailTerm: 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>
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@ import { Module } from '@nestjs/common'
|
||||
import { UsersService } from './services/users.service'
|
||||
import { UsersController } from './api/users.controller'
|
||||
import { UsersRepository } from './infrastructure/users.repository'
|
||||
import { CqrsModule } from '@nestjs/cqrs'
|
||||
|
||||
@Module({
|
||||
imports: [CqrsModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService, UsersRepository],
|
||||
exports: [UsersRepository, UsersService],
|
||||
exports: [UsersRepository, UsersService, CqrsModule],
|
||||
})
|
||||
export class UsersModule {}
|
||||
|
||||
Reference in New Issue
Block a user