all repos — caroster @ 10a07970b5248d04d0fd9b35ef06d24997a0c928

[Octree] Group carpool to your event https://caroster.io

backend/src/extensions/users-permissions/routes/user.ts (view raw)

 1export default [
 2  {
 3    method: "POST",
 4    path: "/auth/magic-link",
 5    handler: async (ctx) => {
 6      const { token } = ctx.request.body;
 7
 8      try {
 9        const payload = await strapi.services[
10          "plugin::users-permissions.user"
11        ].magicLink.verifyMagicToken(token);
12        const email = payload.email;
13        if (!email) throw new Error("No email in token");
14        const existingUser = await strapi.db
15          .query("plugin::users-permissions.user")
16          .findOne({
17            where: { email },
18          });
19        if (existingUser) {
20          const jwt = strapi
21            .plugin("users-permissions")
22            .service("jwt")
23            .issue({ id: existingUser.id });
24          return {
25            jwt,
26            user: {
27              id: existingUser.id,
28              email: existingUser.email,
29              firstname: existingUser.firstname,
30              lang: existingUser.lang,
31            },
32          };
33        }
34        const user = await strapi
35          .plugin("users-permissions")
36          .service("user")
37          .add({
38            email,
39            username: email,
40            provider: "local",
41            confirmed: true,
42          });
43        const jwt = strapi
44          .plugin("users-permissions")
45          .service("jwt")
46          .issue({ id: user.id });
47        return {
48          jwt,
49          user: {
50            id: user.id,
51            email: user.email,
52            firstname: user.firstname,
53            lang: user.lang,
54          },
55        };
56      } catch (error) {
57        strapi.log.warn(error);
58        return ctx.unauthorized("Invalid magic link token");
59      }
60    },
61    config: {
62      prefix: "",
63      auth: false,
64    },
65  },
66];