0

I am trying to use blitz.js login API in a Flutter project. So I have created a /api/auth/login.ts file with the following code

import { getAntiCSRFToken, getSession, SecurePassword } from "@blitzjs/auth"
import { authenticateUser } from "app/auth/mutations/login"
import { AuthenticationError } from "blitz"
import db from "db"
import { Role } from "types"
const handler = async (req, res) => {
  const session = await getSession(req, res)
  const { email, password } = req.body
   if (req.method !== "POST" || !req.body.data || !session.userId) {
     res.status(401).json({ error: `Do not tamper with this route!` })
   } else {
     console.log("Create a new session for the user")
     // Create a new session for the user
     //login
   const user = await authenticateUser(email, password)
  const user = await db.user.findFirst({ where: { email } })
  if (!user) return res.json({ data: "Hello", email, password })
   const result = await SecurePassword.verify(user.hashedPassword, password)
  const { hashedPassword, ...rest } = user
  await req.session.$create({ userId: user.id, role: user.role as Role })
  res.json({ rest })
}
export default handler

I also tried to use their docs but it was not clear enough and understandable

Can I use ctx.session.$create and insert it to db using blitz.js api

1 Answers1

0

I have solved the problem using this code

import { Role } from "types"
import { authenticateUser } from "app/auth/mutations/login"
import { getSession } from "@blitzjs/auth"

export default async function customRoute(req, res) {
  const session = await getSession(req, res)
  const { email, password } = req.body

  console.log(email, password)
  console.log(session.$isAuthorized())
  const user = await authenticateUser(email, password)

  if (user.id === session.userId) {
    return res.status(409).json({ error: `Already exist` })
  }

  await session.$create({ userId: user.id, role: user.role as Role })
  // // res.setHeader("Content-Type", "application/json")
  res.end(JSON.stringify({ userId: session.userId }))
}

At first, I was getting a CSRF mismatch error and then a localStorage is undefined and now somehow everything is working with this code.