chore: migrate get current user

pull/2545/head
Steven 2 years ago
parent c3db4ee236
commit 45d7d0d5f6

@ -62,7 +62,7 @@ func JWTMiddleware(server *APIV1Service, next echo.HandlerFunc, secret string) e
} }
// Skip validation for server status endpoints. // Skip validation for server status endpoints.
if util.HasPrefixes(path, "/api/v1/ping", "/api/v1/idp", "/api/v1/status", "/api/v1/user") && path != "/api/v1/user/me" && path != "/api/v1/user" && method == http.MethodGet { if util.HasPrefixes(path, "/api/v1/ping", "/api/v1/idp", "/api/v1/status") && method == http.MethodGet {
return next(c) return next(c)
} }
@ -73,7 +73,7 @@ func JWTMiddleware(server *APIV1Service, next echo.HandlerFunc, secret string) e
return next(c) return next(c)
} }
// When the request is not authenticated, we allow the user to access the memo endpoints for those public memos. // When the request is not authenticated, we allow the user to access the memo endpoints for those public memos.
if util.HasPrefixes(path, "/api/v1/memo") && method == http.MethodGet { if util.HasPrefixes(path, "/api/v1/memo", "/api/v1/user") && path != "/api/v1/user" && method == http.MethodGet {
return next(c) return next(c)
} }
return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token") return echo.NewHTTPError(http.StatusUnauthorized, "Missing access token")

@ -281,8 +281,12 @@ func (s *APIV1Service) GetUserByID(c echo.Context) error {
} }
userMessage := convertUserFromStore(user) userMessage := convertUserFromStore(user)
// data desensitize userID, ok := c.Get(userIDContextKey).(int32)
userMessage.Email = "" if !ok || userID != user.ID {
// Data desensitize.
userMessage.Email = ""
}
return c.JSON(http.StatusOK, userMessage) return c.JSON(http.StatusOK, userMessage)
} }

@ -18,7 +18,7 @@ export function vacuumDatabase() {
} }
export function signin(username: string, password: string, remember: boolean) { export function signin(username: string, password: string, remember: boolean) {
return axios.post("/api/v1/auth/signin", { return axios.post<User>("/api/v1/auth/signin", {
username, username,
password, password,
remember, remember,
@ -26,7 +26,7 @@ export function signin(username: string, password: string, remember: boolean) {
} }
export function signinWithSSO(identityProviderId: IdentityProviderId, code: string, redirectUri: string) { export function signinWithSSO(identityProviderId: IdentityProviderId, code: string, redirectUri: string) {
return axios.post("/api/v1/auth/signin/sso", { return axios.post<User>("/api/v1/auth/signin/sso", {
identityProviderId, identityProviderId,
code, code,
redirectUri, redirectUri,
@ -34,7 +34,7 @@ export function signinWithSSO(identityProviderId: IdentityProviderId, code: stri
} }
export function signup(username: string, password: string) { export function signup(username: string, password: string) {
return axios.post("/api/v1/auth/signup", { return axios.post<User>("/api/v1/auth/signup", {
username, username,
password, password,
}); });
@ -44,14 +44,14 @@ export function signout() {
return axios.post("/api/v1/auth/signout"); return axios.post("/api/v1/auth/signout");
} }
export function getMyselfUser() {
return axios.get<User>("/api/v1/user/me");
}
export function getUserList() { export function getUserList() {
return axios.get<User[]>("/api/v1/user"); return axios.get<User[]>("/api/v1/user");
} }
export function getUserById(id: number) {
return axios.get<User>(`/api/v1/user/${id}`);
}
export function upsertUserSetting(upsert: UserSettingUpsert) { export function upsertUserSetting(upsert: UserSettingUpsert) {
return axios.post<UserSetting>(`/api/v1/user/setting`, upsert); return axios.post<UserSetting>(`/api/v1/user/setting`, upsert);
} }

@ -5,6 +5,7 @@ import { useSearchParams } from "react-router-dom";
import Icon from "@/components/Icon"; import Icon from "@/components/Icon";
import * as api from "@/helpers/api"; import * as api from "@/helpers/api";
import { absolutifyLink } from "@/helpers/utils"; import { absolutifyLink } from "@/helpers/utils";
import useNavigateTo from "@/hooks/useNavigateTo";
import { useUserStore } from "@/store/module"; import { useUserStore } from "@/store/module";
import { useTranslate } from "@/utils/i18n"; import { useTranslate } from "@/utils/i18n";
@ -15,6 +16,7 @@ interface State {
const AuthCallback = () => { const AuthCallback = () => {
const t = useTranslate(); const t = useTranslate();
const navigateTo = useNavigateTo();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const userStore = useUserStore(); const userStore = useUserStore();
const [state, setState] = useState<State>({ const [state, setState] = useState<State>({
@ -32,14 +34,15 @@ const AuthCallback = () => {
if (identityProviderId) { if (identityProviderId) {
api api
.signinWithSSO(identityProviderId, code, redirectUri) .signinWithSSO(identityProviderId, code, redirectUri)
.then(async () => { .then(async ({ data: user }) => {
setState({ setState({
loading: false, loading: false,
errorMessage: "", errorMessage: "",
}); });
const user = await userStore.doSignIn();
if (user) { if (user) {
window.location.href = "/"; userStore.setCurrentUser(user);
await userStore.fetchCurrentUser();
navigateTo("/");
} else { } else {
toast.error(t("message.login-failed")); toast.error(t("message.login-failed"));
} }

@ -7,11 +7,13 @@ import LocaleSelect from "@/components/LocaleSelect";
import * as api from "@/helpers/api"; import * as api from "@/helpers/api";
import { absolutifyLink } from "@/helpers/utils"; import { absolutifyLink } from "@/helpers/utils";
import useLoading from "@/hooks/useLoading"; import useLoading from "@/hooks/useLoading";
import useNavigateTo from "@/hooks/useNavigateTo";
import { useGlobalStore, useUserStore } from "@/store/module"; import { useGlobalStore, useUserStore } from "@/store/module";
import { useTranslate } from "@/utils/i18n"; import { useTranslate } from "@/utils/i18n";
const SignIn = () => { const SignIn = () => {
const t = useTranslate(); const t = useTranslate();
const navigateTo = useNavigateTo();
const globalStore = useGlobalStore(); const globalStore = useGlobalStore();
const userStore = useUserStore(); const userStore = useUserStore();
const actionBtnLoadingState = useLoading(false); const actionBtnLoadingState = useLoading(false);
@ -72,10 +74,11 @@ const SignIn = () => {
try { try {
actionBtnLoadingState.setLoading(); actionBtnLoadingState.setLoading();
await api.signin(username, password, remember); const { data: user } = await api.signin(username, password, remember);
const user = await userStore.doSignIn();
if (user) { if (user) {
window.location.href = "/"; userStore.setCurrentUser(user);
await userStore.fetchCurrentUser();
navigateTo("/");
} else { } else {
toast.error(t("message.login-failed")); toast.error(t("message.login-failed"));
} }

@ -6,11 +6,13 @@ import AppearanceSelect from "@/components/AppearanceSelect";
import LocaleSelect from "@/components/LocaleSelect"; import LocaleSelect from "@/components/LocaleSelect";
import * as api from "@/helpers/api"; import * as api from "@/helpers/api";
import useLoading from "@/hooks/useLoading"; import useLoading from "@/hooks/useLoading";
import useNavigateTo from "@/hooks/useNavigateTo";
import { useGlobalStore, useUserStore } from "@/store/module"; import { useGlobalStore, useUserStore } from "@/store/module";
import { useTranslate } from "@/utils/i18n"; import { useTranslate } from "@/utils/i18n";
const SignUp = () => { const SignUp = () => {
const t = useTranslate(); const t = useTranslate();
const navigateTo = useNavigateTo();
const globalStore = useGlobalStore(); const globalStore = useGlobalStore();
const userStore = useUserStore(); const userStore = useUserStore();
const actionBtnLoadingState = useLoading(false); const actionBtnLoadingState = useLoading(false);
@ -52,10 +54,11 @@ const SignUp = () => {
try { try {
actionBtnLoadingState.setLoading(); actionBtnLoadingState.setLoading();
await api.signup(username, password); const { data: user } = await api.signup(username, password);
const user = await userStore.doSignIn();
if (user) { if (user) {
window.location.href = "/"; userStore.setCurrentUser(user);
await userStore.fetchCurrentUser();
navigateTo("/");
} else { } else {
toast.error(t("message.signup-failed")); toast.error(t("message.signup-failed"));
} }

@ -58,10 +58,8 @@ export const initialUserState = async () => {
store.dispatch(setHost(convertResponseModelUser(systemStatus.host))); store.dispatch(setHost(convertResponseModelUser(systemStatus.host)));
} }
const { data } = await api.getMyselfUser(); const user = await fetchCurrentUser();
if (data) { if (user) {
const user = convertResponseModelUser(data);
store.dispatch(setUser(user));
if (user.setting.locale) { if (user.setting.locale) {
store.dispatch(setLocale(user.setting.locale)); store.dispatch(setLocale(user.setting.locale));
} }
@ -72,18 +70,21 @@ export const initialUserState = async () => {
} }
}; };
const doSignIn = async () => {
const { data: user } = await api.getMyselfUser();
if (user) {
store.dispatch(setUser(convertResponseModelUser(user)));
} else {
doSignOut();
}
return user;
};
const doSignOut = async () => { const doSignOut = async () => {
await api.signout(); await api.signout();
localStorage.removeItem("userId");
};
const fetchCurrentUser = async () => {
const userId = localStorage.getItem("userId");
if (userId) {
const { data } = await api.getUserById(Number(userId));
const user = convertResponseModelUser(data);
if (user) {
store.dispatch(setUser(user));
return user;
}
}
}; };
export const useUserStore = () => { export const useUserStore = () => {
@ -94,14 +95,17 @@ export const useUserStore = () => {
getState: () => { getState: () => {
return store.getState().user; return store.getState().user;
}, },
doSignIn,
doSignOut, doSignOut,
fetchCurrentUser,
setCurrentUser: async (user: User) => {
localStorage.setItem("userId", String(user.id));
},
upsertUserSetting: async (key: string, value: any) => { upsertUserSetting: async (key: string, value: any) => {
await api.upsertUserSetting({ await api.upsertUserSetting({
key: key as any, key: key as any,
value: JSON.stringify(value), value: JSON.stringify(value),
}); });
await doSignIn(); await fetchCurrentUser();
}, },
upsertLocalSetting: async (localSetting: LocalSetting) => { upsertLocalSetting: async (localSetting: LocalSetting) => {
storage.set({ localSetting }); storage.set({ localSetting });

Loading…
Cancel
Save