-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser.server.ts
117 lines (103 loc) · 2.43 KB
/
user.server.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import type { GitHubProfile } from 'remix-auth-github';
import argon2 from 'argon2';
import type { UserSession } from '@types';
import { prisma } from '~/utils/db.server';
export const createUser = async (email: string, password: string) => {
try {
const hashedPassword = await argon2.hash(password);
const user = await prisma.user.create({
data: {
email: email.toLowerCase(),
password: hashedPassword,
},
});
return user;
} catch (err) {
throw err;
}
};
export const findByCredentials = async (
email: string,
password: string,
): Promise<UserSession | null> => {
try {
const user = await prisma.user.findUnique({
where: {
email: email.toLowerCase(),
},
include: {
profile: true,
},
});
if (!user) {
return null;
}
const valid = await argon2.verify(user.password ?? '', password);
if (!valid) {
return null;
}
return {
id: user.id,
email: user.email,
displayName: user.profile?.displayName,
name: user.profile?.name,
avatar: user.profile?.avatar,
};
} catch (err) {
console.error(err);
return null;
}
};
export const findOrCreateByProfile = async (
profile: GitHubProfile,
): Promise<UserSession | null> => {
try {
const {
emails,
displayName,
name: { familyName },
photos,
} = profile;
const [email] = emails || [{ value: '' }];
const existingUser = await prisma.user.findUnique({
where: { email: email.value },
include: {
profile: true,
},
});
if (existingUser) {
return {
id: existingUser.id,
email: existingUser.email,
displayName: existingUser.profile?.displayName ?? null,
name: existingUser.profile?.name ?? null,
avatar: existingUser.profile?.avatar ?? null,
};
}
const newUser = await prisma.user.create({
data: {
email: email.value,
profile: {
create: {
displayName,
name: familyName,
avatar: photos[0].value,
},
},
},
include: {
profile: true,
},
});
return {
id: newUser.id,
email: newUser.email,
displayName: newUser.profile?.displayName,
name: newUser.profile?.name,
avatar: newUser.profile?.avatar,
};
} catch (error) {
console.error(error);
throw error;
}
};