@appconda/nextjs 1.0.384 → 1.0.386

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
- import type { NextAuthOptions } from "next-auth";
1
+ import type { Account, NextAuthOptions } from "next-auth";
2
2
  import CredentialsProvider from "next-auth/providers/credentials";
3
3
  import { cookies } from "next/headers";
4
- import { getAppcondaClient } from "../getAppcondaClient";
5
- import { Account } from "../modules/account/service";
4
+ import { getAppcondaClient, getAppcondaClientSync } from "../getAppcondaClient";
5
+
6
6
  import { getEnv } from "../lib/env";
7
7
  import { getSDKForCurrentUser } from "../getSDKForCurrentUser";
8
8
  import { Query } from "../query";
9
+ import { AccountService, TUser } from "../modules";
9
10
 
10
11
  /* const getEnv = () => {
11
12
  return {
@@ -16,6 +17,10 @@ import { Query } from "../query";
16
17
  };
17
18
  }; */
18
19
 
20
+ const ENCRYPTION_KEY='51570cb4caa6c1f5f80e6e57a32efb397e9220434532697c94c8f821a7dd1951';
21
+ const ENTERPRISE_LICENSE_KEY = '';
22
+ const EMAIL_VERIFICATION_DISABLED = false;
23
+
19
24
  export async function signIn({ userName, password }: { userName: string, password: string }) {
20
25
  const adminClient = await getAppcondaClient();
21
26
 
@@ -36,8 +41,12 @@ export async function signIn({ userName, password }: { userName: string, passwor
36
41
 
37
42
  }
38
43
 
44
+
45
+
39
46
  export const authOptions = (() => {
40
47
  let options : any= null;
48
+ const adminClient = getAppcondaClientSync();
49
+ const accountService = new AccountService(adminClient);
41
50
 
42
51
  return () => {
43
52
  if (options == null) {
@@ -66,90 +75,9 @@ export const authOptions = (() => {
66
75
  backupCode: { label: "Backup Code", type: "input", placeholder: "Two-factor backup code" },
67
76
  },
68
77
  async authorize(credentials, _req) {
69
- debugger;
70
- let user;
71
- const appcondaSession = await signIn({ userName: credentials?.email as string, password: credentials?.password as string });
72
-
73
- console.log(credentials);
74
- /* try {
75
- user = await prisma.user.findUnique({
76
- where: {
77
- email: credentials?.email,
78
- },
79
- });
80
- } catch (e) {
81
- console.error(e);
82
- throw Error("Internal server error. Please try again later");
83
- }
84
- if (!user || !credentials) {
85
- throw new Error("Invalid credentials");
86
- }
87
- if (!user.password) {
88
- throw new Error("Invalid credentials");
89
- }
90
-
91
- const isValid = await verifyPassword(credentials.password, user.password);
92
-
93
- if (!isValid) {
94
- throw new Error("Invalid credentials");
95
- }
96
-
97
- if (user.twoFactorEnabled && credentials.backupCode) {
98
- if (!ENCRYPTION_KEY) {
99
- console.error("Missing encryption key; cannot proceed with backup code login.");
100
- throw new Error("Internal Server Error");
101
- }
102
-
103
- if (!user.backupCodes) throw new Error("No backup codes found");
104
-
105
- const backupCodes = JSON.parse(symmetricDecrypt(user.backupCodes, ENCRYPTION_KEY));
106
-
107
- // check if user-supplied code matches one
108
- const index = backupCodes.indexOf(credentials.backupCode.replaceAll("-", ""));
109
- if (index === -1) throw new Error("Invalid backup code");
110
-
111
- // delete verified backup code and re-encrypt remaining
112
- backupCodes[index] = null;
113
- await prisma.user.update({
114
- where: {
115
- id: user.id,
116
- },
117
- data: {
118
- backupCodes: symmetricEncrypt(JSON.stringify(backupCodes), ENCRYPTION_KEY),
119
- },
120
- });
121
- } else if (user.twoFactorEnabled) {
122
- if (!credentials.totpCode) {
123
- throw new Error("second factor required");
124
- }
125
-
126
- if (!user.twoFactorSecret) {
127
- throw new Error("Internal Server Error");
128
- }
129
-
130
- if (!ENCRYPTION_KEY) {
131
- throw new Error("Internal Server Error");
132
- }
133
-
134
- const secret = symmetricDecrypt(user.twoFactorSecret, ENCRYPTION_KEY);
135
- if (secret.length !== 32) {
136
- throw new Error("Internal Server Error");
137
- }
138
-
139
- const isValidToken = (await import("./totp")).totpAuthenticatorCheck(credentials.totpCode, secret);
140
- if (!isValidToken) {
141
- throw new Error("Invalid second factor code");
142
- }
143
- } */
144
-
145
- console.log("asafdf")
146
-
147
- return {
148
- id: appcondaSession.userId,
149
- email: appcondaSession.providerUid,
150
- emailVerified: true,
151
- imageUrl: "",
152
- };
78
+ const session = await accountService.CredentialLogin(credentials as any);
79
+
80
+ return session;
153
81
  },
154
82
  }),
155
83
  CredentialsProvider({
@@ -167,79 +95,48 @@ export const authOptions = (() => {
167
95
  },
168
96
  },
169
97
  async authorize(credentials, _req) {
170
-
171
- let user;
172
- /* try {
173
- if (!credentials?.token) {
174
- throw new Error("Token not found");
175
- }
176
- const { id } = await verifyToken(credentials?.token);
177
- user = await prisma.user.findUnique({
178
- where: {
179
- id: id,
180
- },
181
- });
182
- } catch (e) {
183
- console.error(e);
184
- throw new Error("Either a user does not match the provided token or the token is invalid");
185
- }
186
-
187
- if (!user) {
188
- throw new Error("Either a user does not match the provided token or the token is invalid");
189
- }
190
-
191
- if (user.emailVerified) {
192
- throw new Error("Email already verified");
193
- }
194
-
195
- user = await updateUser(user.id, { emailVerified: new Date() }); */
196
-
197
- return user || null;
98
+
99
+ const token = credentials?.token;
100
+ const user = await accountService.TokenLogin({token: token!});
101
+
102
+ return user;
198
103
  },
199
104
  }),
200
105
  // Conditionally add enterprise SSO providers
201
- ...(getEnv().ENTERPRISE_LICENSE_KEY ? [] : []),
106
+ // ...(ENTERPRISE_LICENSE_KEY ? getSSOProviders() : []),
202
107
  ],
203
108
  callbacks: {
204
109
  async jwt({ token }) {
205
-
206
- const { users } = await getSDKForCurrentUser();
207
- const userList = await users.list([Query.equal("email", token.email!)])
208
-
209
- const user = userList.users[0] ?? {};
210
-
211
- /* const existingUser = await getUserByEmail(token?.email!);
212
-
213
- if (!existingUser) {
214
- return token;
215
- } */
216
-
110
+ const existingUser = await accountService.GetUserByEmail({email: token?.email!});
111
+
112
+ if (!existingUser) {
113
+ return token;
114
+ }
115
+
217
116
  return {
218
117
  ...token,
219
- //@ts-ignore
220
- profile: { id: user.$id, ...user },
118
+ profile: { id: existingUser.id },
221
119
  };
222
120
  },
223
121
  async session({ session, token }) {
224
- //@ts-ignore
122
+ // @ts-expect-error
225
123
  session.user.id = token?.id;
226
- //@ts-ignore
124
+ // @ts-expect-error
227
125
  session.user = token.profile;
228
-
126
+
229
127
  return session;
230
128
  },
231
- //@ts-ignore
232
- async signIn({ user, account }: { user: any; account: Account | null }) {
233
- /* if (account?.provider === "credentials" || account?.provider === "token") {
234
- // check if user's email is verified or not
235
- if (!user.emailVerified && !EMAIL_VERIFICATION_DISABLED) {
236
- throw new Error("Email Verification is Pending");
237
- }
238
- return true;
129
+ async signIn({ user, account }: { user: TUser; account: Account }) {
130
+ if (account?.provider === "credentials" || account?.provider === "token") {
131
+ // check if user's email is verified or not
132
+ if (!user.emailVerified && !EMAIL_VERIFICATION_DISABLED) {
133
+ throw new Error("Email Verification is Pending");
239
134
  }
240
- if (ENTERPRISE_LICENSE_KEY) {
241
- return handleSSOCallback({ user, account });
242
- } */
135
+ return true;
136
+ }
137
+ /* if (ENTERPRISE_LICENSE_KEY) {
138
+ return handleSSOCallback({ user, account });
139
+ } */
243
140
  return true;
244
141
  },
245
142
  },
@@ -42,4 +42,33 @@ export async function getAppcondaClient() {
42
42
 
43
43
  return adminClient
44
44
 
45
+ }
46
+
47
+ export function getAppcondaClientSync() {
48
+
49
+ let url;
50
+ if (getEnv().APPCONDA_ENDPOINT) {
51
+ url = getEnv().APPCONDA_ENDPOINT;
52
+ } else if (typeof window !== 'undefined') {
53
+ const hostInfo = getPortAndHostname(window.location.href);
54
+ if (hostInfo.port) {
55
+ url = `${hostInfo.protocol}//${hostInfo.hostname}:${hostInfo.port}/v1`
56
+ } else {
57
+ url = `${hostInfo.protocol}//${hostInfo.hostname}/v1`
58
+ }
59
+ } else {
60
+ url = getEnv().APPCONDA_ENDPOINT || 'http://appconda/v1'
61
+ }
62
+
63
+ /* if (ApplicationConfig.Port == null) {
64
+ url = `${ApplicationConfig.Protocol}://${ApplicationConfig.Domain}:${ApplicationConfig.Port}/v1`
65
+ } else {
66
+ url = `${ApplicationConfig.Protocol}://${ApplicationConfig.Domain}/v1`
67
+ } */
68
+ const adminClient = new Client()
69
+ .setEndpoint(url) // Your API Endpoint
70
+ .setProject('console');
71
+
72
+ return adminClient
73
+
45
74
  }
@@ -2,10 +2,9 @@
2
2
 
3
3
  import { z } from 'zod';
4
4
  import { AppcondaException } from '../../client';
5
- import { getSDKForCurrentUser } from '../../getSDKForCurrentUser';
6
- import { _CreateUserSchema, GetUserByIdSchema, RegisterUserSchema, UpdateUserVerifyTokenSchema } from './schema';
7
- import { TUser } from './types';
8
5
  import { getSDKForService } from '../../getSDKForService';
6
+ import { _CreateUserSchema, CredentialLoginSchema, GetUserByIdSchema, RegisterUserSchema, TokenLoginSchema, UpdateUserVerifyTokenSchema } from './schema';
7
+ import { TUser } from './types';
9
8
 
10
9
  export async function CreateUser(parsedInput: z.infer<typeof _CreateUserSchema>): Promise<TUser> {
11
10
  try {
@@ -67,3 +66,32 @@ export async function UpdateUserVerifyToken(parsedInput: z.infer<typeof UpdateUs
67
66
  }
68
67
  }
69
68
 
69
+ export async function CredentialLogin(parsedInput: z.infer<typeof CredentialLoginSchema>): Promise<TUser> {
70
+ try {
71
+ const { accounts } = await getSDKForService();
72
+ //@ts-ignore
73
+ const app = await accounts.CredentialLogin(parsedInput);
74
+ return app;
75
+ } catch (error) {
76
+ if (error instanceof AppcondaException) {
77
+ throw new Error(error.message);
78
+ }
79
+
80
+ throw error;
81
+ }
82
+ }
83
+
84
+ export async function TokenLogin(parsedInput: z.infer<typeof TokenLoginSchema>): Promise<TUser> {
85
+ try {
86
+ const { accounts } = await getSDKForService();
87
+ //@ts-ignore
88
+ const app = await accounts.TokenLogin(parsedInput);
89
+ return app;
90
+ } catch (error) {
91
+ if (error instanceof AppcondaException) {
92
+ throw new Error(error.message);
93
+ }
94
+
95
+ throw error;
96
+ }
97
+ }
@@ -15,13 +15,14 @@ export const _CreateUserSchema = z.object({
15
15
  export const RegisterUserSchema = z.object({
16
16
  email: z.string(),
17
17
  password: z.string(),
18
- firstName: z.string(),
19
- lastName: z.string(),
20
- active: z.boolean().optional(),
21
- githubId: z.string().optional(),
22
- googleId: z.string().optional(),
23
- avatarURL: z.string().optional(),
24
- locale: z.string().optional()
18
+ name: z.string(),
19
+ inviteToken: z.string().optional(),
20
+ userLocale: z.string().optional(),
21
+ defaultOrganizationId: z.string().optional(),
22
+ defaultOrganizationRole: z.string().optional(),
23
+ emailVerificationDisabled: z.boolean().optional(),
24
+ emailContent: z.string().optional(),
25
+ turnstileToken: z.string().optional()
25
26
  });
26
27
 
27
28
  export const GetUserByIdSchema = z.object({
@@ -31,4 +32,19 @@ export const GetUserByIdSchema = z.object({
31
32
  export const UpdateUserVerifyTokenSchema = z.object({
32
33
  userId: z.string(),
33
34
  verifyToken: z.string()
34
- });
35
+ });
36
+
37
+ export const GetUserByEmailSchema = z.object({
38
+ email: z.string()
39
+ });
40
+
41
+ export const CredentialLoginSchema = z.object({
42
+ email: z.string(),
43
+ password: z.string(),
44
+ backupCode: z.string().optional(),
45
+ totpCode: z.string().optional()
46
+ });
47
+
48
+ export const TokenLoginSchema = z.object({
49
+ token: z.string()
50
+ });
@@ -1,7 +1,7 @@
1
1
 
2
2
  import z from "zod";
3
3
  import { ServiceClient } from "../../service-client";
4
- import { _CreateUserSchema, GetUserByIdSchema, RegisterUserSchema, UpdateUserVerifyTokenSchema } from "./schema";
4
+ import { _CreateUserSchema, CredentialLoginSchema, GetUserByEmailSchema, GetUserByIdSchema, RegisterUserSchema, TokenLoginSchema, UpdateUserVerifyTokenSchema } from "./schema";
5
5
  import { TUser } from "./types";
6
6
 
7
7
 
@@ -18,6 +18,10 @@ export class AccountService extends ServiceClient {
18
18
  return await this.actionCall('user', 'GetUserById', payload);
19
19
  }
20
20
 
21
+ public async GetUserByEmail(payload: z.infer<typeof GetUserByEmailSchema>): Promise<TUser> {
22
+ return await this.actionCall('user', 'GetUserByEmail', payload);
23
+ }
24
+
21
25
  public async UpdateUserVerifyToken(payload: z.infer<typeof UpdateUserVerifyTokenSchema>): Promise<TUser> {
22
26
  return await this.actionCall('user', 'UpdateUserVerifyToken', payload);
23
27
  }
@@ -26,6 +30,14 @@ export class AccountService extends ServiceClient {
26
30
  return await this.actionCall('user', 'RegisterUser', payload);
27
31
  }
28
32
 
33
+ public async CredentialLogin(payload: z.infer<typeof CredentialLoginSchema>): Promise<TUser> {
34
+ return await this.actionCall('user', 'CredentialLogin', payload);
35
+ }
36
+
37
+ public async TokenLogin(payload: z.infer<typeof TokenLoginSchema>): Promise<TUser> {
38
+ return await this.actionCall('user', 'TokenLogin', payload);
39
+ }
40
+
29
41
 
30
42
 
31
43
  }
@@ -12,4 +12,5 @@ export type TUser = {
12
12
  googleId: string;
13
13
  avatarURL: string;
14
14
  locale: string;
15
+ emailVerified: boolean;
15
16
  }