@appconda/nextjs 1.0.385 → 1.0.387

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,10 +41,16 @@ 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;
41
48
 
49
+
42
50
  return () => {
51
+ const adminClient = getAppcondaClientSync();
52
+ const accountService = new AccountService(adminClient);
53
+
43
54
  if (options == null) {
44
55
  options = {
45
56
  providers: [
@@ -66,90 +77,9 @@ export const authOptions = (() => {
66
77
  backupCode: { label: "Backup Code", type: "input", placeholder: "Two-factor backup code" },
67
78
  },
68
79
  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
- };
80
+ const session = await accountService.CredentialLogin(credentials as any);
81
+
82
+ return session;
153
83
  },
154
84
  }),
155
85
  CredentialsProvider({
@@ -167,79 +97,48 @@ export const authOptions = (() => {
167
97
  },
168
98
  },
169
99
  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;
100
+
101
+ const token = credentials?.token;
102
+ const user = await accountService.TokenLogin({token: token!});
103
+
104
+ return user;
198
105
  },
199
106
  }),
200
107
  // Conditionally add enterprise SSO providers
201
- ...(getEnv().ENTERPRISE_LICENSE_KEY ? [] : []),
108
+ // ...(ENTERPRISE_LICENSE_KEY ? getSSOProviders() : []),
202
109
  ],
203
110
  callbacks: {
204
111
  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
-
112
+ const existingUser = await accountService.GetUserByEmail({email: token?.email!});
113
+
114
+ if (!existingUser) {
115
+ return token;
116
+ }
117
+
217
118
  return {
218
119
  ...token,
219
- //@ts-ignore
220
- profile: { id: user.$id, ...user },
120
+ profile: { id: existingUser.id },
221
121
  };
222
122
  },
223
123
  async session({ session, token }) {
224
- //@ts-ignore
124
+ // @ts-expect-error
225
125
  session.user.id = token?.id;
226
- //@ts-ignore
126
+ // @ts-expect-error
227
127
  session.user = token.profile;
228
-
128
+
229
129
  return session;
230
130
  },
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;
131
+ async signIn({ user, account }: { user: TUser; account: Account }) {
132
+ if (account?.provider === "credentials" || account?.provider === "token") {
133
+ // check if user's email is verified or not
134
+ if (!user.emailVerified && !EMAIL_VERIFICATION_DISABLED) {
135
+ throw new Error("Email Verification is Pending");
239
136
  }
240
- if (ENTERPRISE_LICENSE_KEY) {
241
- return handleSSOCallback({ user, account });
242
- } */
137
+ return true;
138
+ }
139
+ /* if (ENTERPRISE_LICENSE_KEY) {
140
+ return handleSSOCallback({ user, account });
141
+ } */
243
142
  return true;
244
143
  },
245
144
  },
@@ -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
+ }
@@ -32,4 +32,19 @@ export const GetUserByIdSchema = z.object({
32
32
  export const UpdateUserVerifyTokenSchema = z.object({
33
33
  userId: z.string(),
34
34
  verifyToken: z.string()
35
- });
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
  }