Skip to content

Commit

Permalink
User login
Browse files Browse the repository at this point in the history
  • Loading branch information
likui628 committed Sep 22, 2024
1 parent e8faa6a commit 6c92e42
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { Request, Response } from 'express'
import { asyncHandler, successResponse } from '../utils'
import { userService } from '../services'
import { userService, authService } from '../services'

export const register = asyncHandler(async (req: Request, res: Response) => {
const user = await userService.createUser(req.body)
successResponse(res, user, 201)
})

export const login = asyncHandler(async (req: Request, res: Response) => {
const { email, password } = req.body
const user = await authService.loginUserWithEmailAndPassword(email, password)
successResponse(res, user, 200)
})
6 changes: 6 additions & 0 deletions src/routes/v1/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,10 @@ router.post(
authController.register,
)

router.post(
'/login',
validate(authValidation.userLoginSchema),
authController.login,
)

export default router
12 changes: 12 additions & 0 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { userService } from '.'

export const loginUserWithEmailAndPassword = async (
email: string,
password: string,
) => {
const user = await userService.getUserByEmail(email)
if (!user || user.password !== password) {
throw new Error('password is incorrect')
}
return user
}
1 change: 1 addition & 0 deletions src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * as userService from './user'
export * as authService from './auth'
13 changes: 13 additions & 0 deletions src/services/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,16 @@ export const createUser = async (user: User) => {
throw new Error('create user failed')
}
}

export const getUserByEmail = async (email: string) => {
try {
const user = await prisma.user.findUnique({
where: {
email,
},
})
return user
} catch (_err: unknown) {
throw new Error('get user failed')
}
}
5 changes: 5 additions & 0 deletions src/validations/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,8 @@ export const userRegisterSchema = z.object({
password: z.string().min(6),
name: z.string(),
})

export const userLoginSchema = userRegisterSchema.pick({
email: true,
password: true,
})

0 comments on commit 6c92e42

Please sign in to comment.