Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/user-context.tsx
2498 views
1
/**
2
* Copyright (c) 2021 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { User } from "@gitpod/public-api/lib/gitpod/v1/user_pb";
8
import { useQueryClient } from "@tanstack/react-query";
9
import React, { createContext, useState, useContext, useMemo, useCallback } from "react";
10
import { updateCommonErrorDetails } from "./service/metrics";
11
import { updateUserForExperiments } from "./service/public-api";
12
import { getPrimaryEmail } from "@gitpod/public-api-common/lib/user-utils";
13
14
const UserContext = createContext<{
15
user?: User;
16
setUser: React.Dispatch<User>;
17
}>({
18
setUser: () => null,
19
});
20
21
const refetchCookie = async () => {
22
await fetch("/api/auth/jwt-cookie", {
23
credentials: "include",
24
})
25
.then((resp) => resp.text())
26
.then((text) => console.log(`Completed JWT Cookie refresh: ${text}`))
27
.catch((err) => {
28
console.log("Failed to update jwt-cookie", err);
29
});
30
};
31
32
const UserContextProvider: React.FC = ({ children }) => {
33
const [user, setUser] = useState<User>();
34
35
const updateServiceUser = (user?: User) => {
36
updateCommonErrorDetails({ userId: user?.id });
37
updateUserForExperiments(!!user ? { id: user.id, email: getPrimaryEmail(user) } : undefined);
38
};
39
updateServiceUser(user);
40
41
const client = useQueryClient();
42
43
const doSetUser = useCallback(
44
(updatedUser: User) => {
45
updateServiceUser(updatedUser);
46
// If user has changed clear cache
47
// Ignore the case where user hasn't been set yet - initial load
48
if (user && user?.id !== updatedUser.id) {
49
client.clear();
50
}
51
setUser(updatedUser);
52
53
// Schedule a periodic refresh of JWT cookie
54
const w = window as any;
55
const _gp = w._gp || (w._gp = {});
56
57
const frequencyMs = 1000 * 60 * 5; // 5 mins
58
if (!_gp.jwttimer) {
59
// Store the timer on the window, to avoid queuing up multiple
60
_gp.jwtTimer = setInterval(refetchCookie, frequencyMs);
61
62
setTimeout(refetchCookie, 20_000);
63
}
64
},
65
[user, client],
66
);
67
68
// Wrap value in useMemo to avoid unnecessary re-renders
69
const ctxValue = useMemo(() => ({ user, setUser: doSetUser }), [user, doSetUser]);
70
71
return <UserContext.Provider value={ctxValue}>{children}</UserContext.Provider>;
72
};
73
74
export { UserContext, UserContextProvider };
75
76
export const useCurrentUser = () => {
77
const { user } = useContext(UserContext);
78
return user;
79
};
80
81