tsensei / nextjs-pocketbase-starter-template

22 stars 1 forks source link

Missing actions for login and signup #1

Open adamtretera opened 6 months ago

adamtretera commented 6 months ago

Hi, I dont know if its intentional but you are missing the acctions for login / signup ?

The demo also would be much better if there was some pocketbase call ?

tsensei commented 6 months ago

@adamtretera You can write your signup logic with the APIs that pocketbase provide, and login in the same way as demonstrated in the pocketbase docs. When you log in, all the necessary tokens will be saved in localStorage (how pocketbase does it) but also in cookies (we need it for nextjs server components and authenticated routes)

You can simply modify the middleware file to specify which route to check the authStore before returning a response

middleware.ts

const cookieStore = cookies();
const { authStore } = createServerClient(cookieStore);

  // 1. Check if the request is for the /login or /not-authorized route
  if (
    request.nextUrl.pathname === "/login" ||
    request.nextUrl.pathname === "/not-authorized"
  ) {
    if (authStore.isValid) {
      return NextResponse.redirect(basePath);
    }
    return;
  }

  // 2. Require authentication for all other routes (including root)
  if (!authStore.isValid) {
    // Redirect to login page if not authenticated
    const redirectPath = `${basePath}/login`;

    return NextResponse.redirect(redirectPath);
  }

This snippet I quickly copied from another of my project, this should make sense - the paths specified in the matcher will not be intercepted by our middleware, and for the intercepted paths, you have the authStore, and its upto you what you want to do as a response

adamtretera commented 6 months ago

@tsensei Thanks for quick reply, so you are sign-in for example in server action using thepb.authWithPassword() =>

and you can then display in client component pb.authStore.model

Because this doesnt work for me, I am actaully good with using the pb just on the server side, but when I sign-in.

My component

async function getUser() {
  const cookieStore = cookies();
  const pb = createServerClient(cookieStore);

  console.log("authMiddleware", pb.authStore.model);

  return pb.authStore.model;
}

My login action

export const loginAction = action(
  loginFormSchema,
  async ({ email, password }) => {
    try {
      const { token, record: model } = await loginUser({ email, password });

      return { success: model };
    } catch (error) {
      console.log("error", error);

      if (isErrorWithMessage(error)) {
        return { failure: error.message };
      }

      return { failure: "Auth Error" };
    }
  },
);

yeah and the pb function

export async function loginUser(user: LoginFormType) {
  return await pb
    .collection(Collections.Users)
    .authWithPassword<LoginFormType>(user.email, user.password);
}