Skip to content

Commit e99e48b

Browse files
committed
fix: implementation smtp
1 parent ae441ea commit e99e48b

File tree

3 files changed

+75
-65
lines changed

3 files changed

+75
-65
lines changed

src/app/handler/auth.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,8 @@ route.post(
1818
'/sign-up',
1919
asyncHandler(async (req: Request, res: Response) => {
2020
const values = req.getBody()
21-
const record = await service.register(values)
22-
const httpResponse = HttpResponse.created({
23-
data: record,
24-
message: 'User registered successfully',
25-
})
21+
await service.register(values)
22+
const httpResponse = HttpResponse.created({ message: 'User registered successfully' })
2623
res.status(201).json(httpResponse)
2724
})
2825
)

src/app/service/auth.ts

Lines changed: 65 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ import _ from 'lodash'
22
import { Model, ModelStatic } from 'sequelize'
33
import { v4 as uuidv4 } from 'uuid'
44
import { env } from '~/config/env'
5-
import { logger } from '~/config/logger'
5+
import { mailExists } from '~/lib/boolean'
66
import { ConstRole } from '~/lib/constant/seed/role'
77
import ErrorResponse from '~/lib/http/errors'
8+
import { SendEmailRegistration } from '~/lib/smtp/template/auth'
89
import JwtToken from '~/lib/token/jwt'
910
import { validate } from '~/lib/validate'
1011
import { db } from '../database/connection'
@@ -48,6 +49,7 @@ export default class AuthService {
4849
*/
4950
async register(formData: any) {
5051
const uuid = uuidv4()
52+
const isMailEnabled = mailExists()
5153

5254
const payload = JSON.parse(JSON.stringify({ uid: uuid }))
5355
const { token } = jwt.generate(payload)
@@ -62,9 +64,18 @@ export default class AuthService {
6264
upload_id: null,
6365
})
6466

65-
const formRegister: any = { ...values, password: validate.empty(formData.new_password) }
67+
// @ts-expect-error
68+
const formRegister: User = { ...values, password: validate.empty(formData.new_password) }
6669
const data = await this._repository.user.create({ ...formRegister })
6770

71+
if (isMailEnabled) {
72+
await SendEmailRegistration({
73+
fullname: values.fullname,
74+
email: values.email,
75+
url_token: token,
76+
})
77+
}
78+
6879
return data
6980
}
7081

@@ -74,64 +85,59 @@ export default class AuthService {
7485
async login(formData: LoginSchema) {
7586
const values = loginSchema.parse(formData)
7687

77-
try {
78-
let data: any
79-
80-
await db.sequelize!.transaction(async (transaction) => {
81-
const repo = {
82-
user: this._repository.user,
83-
role: this._repository.role,
84-
session: this._repository.session,
85-
}
86-
87-
const getUser = await repo.user.findOne({
88-
attributes: ['id', 'fullname', 'email', 'password', 'is_active', 'role_id'],
89-
where: { email: values.email },
90-
transaction,
91-
})
92-
93-
if (!getUser) {
94-
throw new ErrorResponse.NotFound('user not found')
95-
}
96-
97-
if (!getUser.is_active) {
98-
throw new ErrorResponse.BadRequest('user is not active, please verify your email')
99-
}
100-
101-
const isPasswordMatch = await getUser.comparePassword(values.password)
102-
if (!isPasswordMatch) {
103-
throw new ErrorResponse.BadRequest('current password is incorrect')
104-
}
105-
106-
const getRole = await repo.role.findOne({ where: { id: getUser.role_id }, transaction })
107-
if (!getRole) {
108-
throw new ErrorResponse.NotFound('role not found')
109-
}
110-
111-
const payload = JSON.parse(JSON.stringify({ uid: getUser.id }))
112-
const { token, expiresIn } = jwt.generate(payload)
113-
114-
const formSession = { ...formData, user_id: getUser.id, token }
115-
await repo.session.create({ ...formSession }, { transaction })
116-
117-
const is_admin = [ConstRole.ID_ADMIN, ConstRole.ID_SUPER_ADMIN].includes(getRole.id)
118-
119-
data = {
120-
fullname: getUser.fullname,
121-
email: getUser.email,
122-
uid: getUser.id,
123-
access_token: token,
124-
expires_at: new Date(Date.now() + expiresIn * 1000),
125-
expires_in: expiresIn,
126-
is_admin,
127-
}
88+
let data: any
89+
90+
await db.sequelize!.transaction(async (transaction) => {
91+
const repo = {
92+
user: this._repository.user,
93+
role: this._repository.role,
94+
session: this._repository.session,
95+
}
96+
97+
const getUser = await repo.user.findOne({
98+
attributes: ['id', 'fullname', 'email', 'password', 'is_active', 'role_id'],
99+
where: { email: values.email },
100+
transaction,
128101
})
129102

130-
return data
131-
} catch (error) {
132-
logger.error(error)
133-
throw new ErrorResponse.InternalServer('failed to login')
134-
}
103+
if (!getUser) {
104+
throw new ErrorResponse.NotFound('user not found')
105+
}
106+
107+
if (!getUser.is_active) {
108+
throw new ErrorResponse.BadRequest('user is not active, please verify your email')
109+
}
110+
111+
const isPasswordMatch = await getUser.comparePassword(values.password)
112+
if (!isPasswordMatch) {
113+
throw new ErrorResponse.BadRequest('current password is incorrect')
114+
}
115+
116+
const getRole = await repo.role.findOne({ where: { id: getUser.role_id }, transaction })
117+
if (!getRole) {
118+
throw new ErrorResponse.NotFound('role not found')
119+
}
120+
121+
const payload = JSON.parse(JSON.stringify({ uid: getUser.id }))
122+
const { token, expiresIn } = jwt.generate(payload)
123+
124+
const formSession = { ...formData, user_id: getUser.id, token }
125+
await repo.session.create({ ...formSession }, { transaction })
126+
127+
const is_admin = [ConstRole.ID_ADMIN, ConstRole.ID_SUPER_ADMIN].includes(getRole.id)
128+
129+
data = {
130+
fullname: getUser.fullname,
131+
email: getUser.email,
132+
uid: getUser.id,
133+
access_token: token,
134+
expires_at: new Date(Date.now() + expiresIn * 1000),
135+
expires_in: expiresIn,
136+
is_admin,
137+
}
138+
})
139+
140+
return data
135141
}
136142

137143
/**
@@ -152,7 +158,7 @@ export default class AuthService {
152158
throw new ErrorResponse.BadRequest('user id not match')
153159
}
154160

155-
return { ...user, session }
161+
return { ...user.toJSON(), session }
156162
}
157163

158164
/**

src/main.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,17 @@ import { initDatabase } from './app/database/connection'
33
import Job from './app/job'
44
import { App } from './config/app'
55
import { env } from './config/env'
6+
import { smtp } from './config/smtp'
67
import { storage } from './config/storage'
7-
import { storageExists } from './lib/boolean'
8+
import { mailExists, storageExists } from './lib/boolean'
89
import { httpHandle } from './lib/http/handle'
910

1011
function bootstrap() {
1112
const port = env.APP_PORT
1213
const app = new App().create
1314
const server = http.createServer(app)
1415
const isStorageEnabled = storageExists()
16+
const isMailEnabled = mailExists()
1517

1618
// initial database
1719
initDatabase()
@@ -21,6 +23,11 @@ function bootstrap() {
2123
storage.initialize()
2224
}
2325

26+
// initial smtp
27+
if (isMailEnabled) {
28+
smtp.initialize()
29+
}
30+
2431
// initial job
2532
Job.initialize()
2633

0 commit comments

Comments
 (0)