likes
comments
collection
share

「14」next-shopping:登录注册、用户相关api实现

作者站长头像
站长
· 阅读数 2

登录

修改app/api/auth/login/route.js

import z from 'zod'
import { userRepo } from '@/helpers'
import { apiHandler, setJson } from '@/helpers/api'

const login = apiHandler(
  async req => {
    const body = await req.json()
    const result = await userRepo.authenticate(body)
    return setJson({
      data: result,
    })
  },
  {
    schema: z.object({
      email: z.string(),
      password: z.string().min(6),
    }),
  }
)

export const POST = login

效果如下:

「14」next-shopping:登录注册、用户相关api实现

报错也有效果:

「14」next-shopping:登录注册、用户相关api实现

注册

然后我们来实现app/api/auth/register/route.js

import z from 'zod'

import { userRepo } from '@/helpers'
import { apiHandler, setJson } from '@/helpers/api'

const register = apiHandler(
  async req => {
    const body = await req.json()
    const newUser = await userRepo.create(body)
    const result = {
      name: newUser.name,
      email: newUser.email,
      mobile: newUser.mobile,
      address: newUser.address,
      role: newUser.role,
      root: newUser.root,
    }

    return setJson({
      data: result,
    })
  },
  {
    schema: z.object({
      name: z.string(),
      email: z.string(),
      password: z.string().min(6),
    }),
  }
)

export const POST = register

并修改一下helpers/api/validate-middleware.js的报错

export async function validateMiddleware(req, schema) {
  if (!schema) return

  const body = await req.json()
  const { error, data } = schema.safeParse(body)
  console.log('error', error.errors)
  if (error?.errors) {
    throw `Validation error: ${error?.errors?.map(x => `${x.path?.[0]}:${x.message}`).join(', ')}`
  }

  // update req.json() to return sanitized req body
  req.json = () => data
}

我们新建一个账号,可以看到如下效果:

「14」next-shopping:登录注册、用户相关api实现

可以看到通过了zod的校验过后是数据库的返回报错:

「14」next-shopping:登录注册、用户相关api实现

「14」next-shopping:登录注册、用户相关api实现

9@qq.com去登录试试:

「14」next-shopping:登录注册、用户相关api实现

获取用户信息

修改app/api/auth/user/route.js

import { userRepo } from '@/helpers'
import { apiHandler, setJson } from '@/helpers/api'

const getUserInfo = apiHandler(async req => {
  const userId = req.headers.get('userId')
  const user = await userRepo.getById(userId)

  return setJson({
    data: {
      name: user.name,
      email: user.email,
      role: user.role,
      root: user.root,
    },
  })
})

export const GET = getUserInfo

我们把登录拿到的token放到headers里面即可获取到用户信息

「14」next-shopping:登录注册、用户相关api实现

更新删除指定用户信息

修改app/api/user/[id]/route.js

import z from 'zod'

import { userRepo } from '@/helpers'
import { apiHandler, setJson } from '@/helpers/api'

const updateRole = apiHandler(
  async (req, { params }) => {
    const { id } = params
    const { role } = await req.json()
    await userRepo.updateRole(id, role)
    return setJson({
      message: '更新成功',
    })
  },
  {
    schema: z.object({
      role: z.enum(['user', 'admin']),
    }),
    identity: 'root',
  }
)

const deleteUser = apiHandler(
  async (req, { params }) => {
    const { id } = params

    await userRepo.delete(id)
    return setJson({
      message: '用户信息已经删除',
    })
  },
  {
    identity: 'root',
  }
)

export const PATCH = updateRole
export const DELETE = deleteUser

主要是角色修改,和删除角色,测一下是没有权限,

「14」next-shopping:登录注册、用户相关api实现

我们直接在数据库修改root字段:

「14」next-shopping:登录注册、用户相关api实现

zod的必填校验

「14」next-shopping:登录注册、用户相关api实现

zod的数据校验

「14」next-shopping:登录注册、用户相关api实现

最后更新成功:

「14」next-shopping:登录注册、用户相关api实现

「14」next-shopping:登录注册、用户相关api实现

修改密码

修改app/api/user/reset-password/route.js

import z from 'zod'

import { userRepo } from '@/helpers'
import { apiHandler, setJson } from '@/helpers/api'

const resetPassword = apiHandler(
  async (req, res) => {
    const userId = req.headers.get('userId')
    const { password } = await req.json()
    await userRepo.resetPassword(userId, password)

    return setJson({
      message: '密码更新成功',
    })
  },
  {
    schema: z.object({
      password: z.string().min(6),
    }),
  }
)

export const PATCH = resetPassword

效果如下:

「14」next-shopping:登录注册、用户相关api实现

批量获取用户+当前用户信息

修改app/api/user/route.js

import User from '@/models/User'
import db from '@/lib/db'

export async function identityMiddleware(req, identity) {
  if (!identity || identity === 'user') return

  const userId = req.headers.get('userId')
  db.connect()
  const user = await User.findOne({ _id: userId })
  db.disconnect()

  if (identity === 'admin' && user.role !== 'admin') {
    throw new Error('Unauthorized')
  }

  if (identity === 'root' && !user.root) {
    throw new Error('Unauthorized')
  }

  req.headers.set('userRole', user.role)
  req.headers.set('userRoot', user.root)
}

效果如下:

「14」next-shopping:登录注册、用户相关api实现

更新当前个人信息:

「14」next-shopping:登录注册、用户相关api实现

代码地址:github.com/liyunfu1998…