-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathuser.server.ts
More file actions
141 lines (123 loc) · 3.31 KB
/
user.server.ts
File metadata and controls
141 lines (123 loc) · 3.31 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import type { Database } from "@webstudio-is/postrest/index.server";
import {
AuthorizationError,
type AppContext,
} from "@webstudio-is/trpc-interface/index.server";
import type { GitHubProfile } from "remix-auth-github";
import type { GoogleProfile } from "remix-auth-google";
import { z } from "zod";
export type User = Omit<
Database["public"]["Tables"]["User"]["Row"],
"projectsTags"
> & {
projectsTags: Array<ProjectTag>;
};
const formatUser = (user: Database["public"]["Tables"]["User"]["Row"]) => {
return {
...user,
projectsTags: (user.projectsTags || []) as User["projectsTags"],
};
};
export const getUserById = async (context: AppContext, id: User["id"]) => {
const dbUser = await context.postgrest.client
.from("User")
.select()
.eq("id", id)
.single();
if (dbUser.error) {
console.error(dbUser.error);
throw new Error("User not found");
}
return formatUser(dbUser.data);
};
const genericCreateAccount = async (
context: AppContext,
userData: {
email: string;
username: string;
image: string;
provider: string;
}
): Promise<User> => {
const dbUser = await context.postgrest.client
.from("User")
.select()
.eq("email", userData.email)
.single();
if (dbUser.error == null) {
return formatUser(dbUser.data);
}
// https://github.com/PostgREST/postgrest/blob/bfbd033c6e9f38cfbc8b1cfe19ee009a9379e3dd/docs/references/errors.rst#L234
if (dbUser.error.code !== "PGRST116") {
console.error(dbUser.error);
throw new Error("User not found");
}
const newUser = await context.postgrest.client
.from("User")
.insert({
id: crypto.randomUUID(),
...userData,
})
.select()
.single();
if (newUser.error) {
console.error(newUser.error);
throw new Error("Failed to create user");
}
return formatUser(newUser.data);
};
export const createOrLoginWithOAuth = async (
context: AppContext,
profile: GoogleProfile | GitHubProfile
): Promise<User> => {
const userData = {
email: (profile.emails ?? [])[0]?.value,
username: profile.displayName,
image: (profile.photos ?? [])[0]?.value,
provider: profile.provider,
};
const newUser = await genericCreateAccount(context, userData);
return newUser;
};
export const createOrLoginWithDev = async (
context: AppContext,
email: string
): Promise<User> => {
const userData = {
email,
username: "admin",
image: "",
provider: "dev",
};
const newUser = await genericCreateAccount(context, userData);
return newUser;
};
export const userProjectTagSchema = z.object({
id: z.string(),
label: z.string().min(1).max(100),
color: z
.string()
.regex(/^#[0-9a-f]{6}$/i, "Color must be a 6-digit hex value")
.optional(),
});
export type ProjectTag = z.infer<typeof userProjectTagSchema>;
export const updateUserProjectsTags = async (
{ tags }: { tags: ProjectTag[] },
context: AppContext
) => {
if (context.authorization.type !== "user") {
throw new AuthorizationError(
"Only logged in users can update project tags"
);
}
const result = await context.postgrest.client
.from("User")
.update({ projectsTags: tags })
.eq("id", context.authorization.userId)
.select()
.single();
if (result.error) {
throw result.error;
}
return result.data.projectsTags as ProjectTag[];
};