Cleaning up the username api route and ensuring the users name is fresh

This commit is contained in:
Keith Stevens
2023-01-18 14:41:29 +09:00
parent 527e1513b1
commit a15481b03d
2 changed files with 14 additions and 13 deletions
+3 -2
View File
@@ -88,16 +88,17 @@ export const authOptions: AuthOptions = {
* Ensure we propagate the user's role when creating the session from the
* token.
*/
async session({ session, token }) {
async session({ session, user, token }) {
session.user.role = token.role;
session.user.isNew = token.isNew;
session.user.name = token.name;
return session;
},
/**
* When creating a token, fetch the user's role and inject it in the token.
* This let's use forward the role to the session object.
*/
async jwt({ token }) {
async jwt({ token, user, account }) {
const { isNew, name, role } = await prisma.user.findUnique({
where: { id: token.sub },
select: { name: true, role: true, isNew: true },
+11 -11
View File
@@ -1,20 +1,20 @@
import { getSession } from "next-auth/react";
import { withoutRole } from "src/lib/auth";
import prisma from "src/lib/prismadb";
// POST /api/post
// Required fields in body: title
// Optional fields in body: content
export default async function handle(req, res) {
/**
* Updates the user's `name` field in the `User` table.
*/
const handler = withoutRole("banned", async (req, res, token) => {
const { username } = req.body;
const session = await getSession({ req });
const result = await prisma.user.update({
const { name } = await prisma.user.update({
where: {
email: session.user.email,
id: token.sub,
},
data: {
name: username,
},
});
res.json({ name: result.name });
}
res.json({ name });
});
export default handler;