-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathcredentials.ts
74 lines (65 loc) · 1.72 KB
/
credentials.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import type { CredentialsConfig } from 'next-auth/providers';
import Credentials from 'next-auth/providers/credentials';
import type { SanityClient } from '@sanity/client';
import { getUserByEmailQuery } from './queries';
import { uuid } from '@sanity/uuid';
import argon2 from 'argon2';
export const signUpHandler =
(client: SanityClient, userSchema: string = 'user') =>
async (req: any, res: any) => {
const { email, password, name, image, ...userData } = req.body;
const user = await client.fetch(getUserByEmailQuery, {
userSchema,
email
});
if (user) {
res.json({ error: 'User already exist' });
return;
}
const { password: _, ...newUser } = await client.create({
_id: `user.${uuid()}`,
_type: userSchema,
email,
password: await argon2.hash(password),
name,
image,
...userData
});
res.json({
id: newUser._id,
...newUser
});
};
export const SanityCredentials = (
client: SanityClient,
userSchema = 'user'
): CredentialsConfig =>
Credentials({
name: 'Credentials',
id: 'sanity-login',
type: 'credentials',
credentials: {
email: {
label: 'Email',
type: 'text'
},
password: {
label: 'Password',
type: 'password'
}
},
async authorize(credentials) {
const { _id, ...user } = await client.fetch(getUserByEmailQuery, {
userSchema,
email: credentials?.email
});
if (!user) throw new Error('Email does not exist');
if (await argon2.verify(user.password, credentials?.password!)) {
return {
id: _id,
...user
};
}
throw new Error('Password Invalid');
}
});