Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: change login/auto_login to use UseQuery #3033

Merged
merged 21 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
3a8a3b5
✨ (App.tsx): Introduce framer-motion library for animations in the fr…
Cristhianzl Jul 29, 2024
9e90d47
πŸ“ (LoginPage/index.tsx): remove unnecessary console.log statement fro…
Cristhianzl Jul 29, 2024
8d47d07
♻️ (App.tsx): remove unused import statement for 'm' from 'framer-mot…
Cristhianzl Jul 29, 2024
95522b7
Merge branch 'main' into refactor/login
Cristhianzl Jul 29, 2024
2864aef
removing abort from request
Cristhianzl Jul 29, 2024
bc7f6cb
Merge branch 'main' into refactor/login
Cristhianzl Jul 29, 2024
04f263d
[autofix.ci] apply automated fixes
autofix-ci[bot] Jul 29, 2024
d82285b
Merge branch 'main' into refactor/login
anovazzi1 Jul 29, 2024
734ce24
Merge branch 'main' into refactor/login
Cristhianzl Jul 30, 2024
4fc914d
Merge branch 'main' into refactor/login
Cristhianzl Jul 30, 2024
f7a8f72
Merge branch 'main' into refactor/login
Cristhianzl Jul 30, 2024
602f744
Merge branch 'main' into refactor/login
Cristhianzl Jul 30, 2024
31843d5
Merge branch 'main' of github.com:langflow-ai/langflow into refactor/…
Cristhianzl Jul 31, 2024
871edf7
Merge branch 'main' into refactor/login
Cristhianzl Jul 31, 2024
dd7f4eb
Merge branch 'main' into refactor/login
Cristhianzl Jul 31, 2024
79e4d34
Merge branch 'refactor/login' of github.com:langflow-ai/langflow into…
Cristhianzl Jul 31, 2024
47cdfb9
✨ (App.tsx): Add support for auto login feature and improve error han…
Cristhianzl Jul 31, 2024
5d6a84b
Merge branch 'main' into refactor/login
Cristhianzl Jul 31, 2024
fa281fe
πŸ“ (API/index.ts): Remove getProfilePictures function as it is no long…
Cristhianzl Jul 31, 2024
4d36dbe
Merge branch 'main' of github.com:langflow-ai/langflow
Cristhianzl Jul 31, 2024
50fe608
merge fix
Cristhianzl Jul 31, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 33 additions & 29 deletions src/frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
LANGFLOW_AUTO_LOGIN_OPTION,
} from "./constants/constants";
import { AuthContext } from "./contexts/authContext";
import { autoLogin } from "./controllers/API";
import { useAutoLogin } from "./controllers/API/queries/auth";
import { useGetHealthQuery } from "./controllers/API/queries/health";
import { useGetVersionQuery } from "./controllers/API/queries/version";
import { setupAxiosDefaults } from "./controllers/API/utils";
Expand All @@ -36,6 +36,7 @@ export default function App() {
const refreshStars = useDarkStore((state) => state.refreshStars);
const dark = useDarkStore((state) => state.dark);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const { mutate: mutateAutoLogin } = useAutoLogin();

useGetVersionQuery();
const cookies = new Cookies();
Expand All @@ -61,37 +62,40 @@ export default function App() {
const abortController = new AbortController();
const isLoginPage = location.pathname.includes("login");

autoLogin(abortController.signal)
.then(async (user) => {
if (user && user["access_token"]) {
user["refresh_token"] = "auto";
login(user["access_token"], "auto");
setUserData(user);
setAutoLogin(true);
fetchAllData();
}
})
.catch(async (error) => {
if (error.name !== "CanceledError") {
setAutoLogin(false);
if (
cookies.get(LANGFLOW_AUTO_LOGIN_OPTION) === "auto" &&
isAuthenticated
) {
logout();
return;
}

if (isAuthenticated && !isLoginPage) {
getUser();
mutateAutoLogin(
{ abortSignal: abortController.signal },
{
onSuccess: (user) => {
if (user && user["access_token"]) {
user["refresh_token"] = "auto";
login(user["access_token"], "auto");
setUserData(user);
setAutoLogin(true);
fetchAllData();
} else {
setLoading(false);
useFlowsManagerStore.setState({ isLoading: false });
}
}
});
},
onError: (error) => {
if (error.name !== "CanceledError") {
setAutoLogin(false);
if (
cookies.get(LANGFLOW_AUTO_LOGIN_OPTION) === "auto" &&
isAuthenticated
) {
logout();
return;
}

if (isAuthenticated && !isLoginPage) {
getUser();
fetchAllData();
} else {
setLoading(false);
useFlowsManagerStore.setState({ isLoading: false });
}
}
},
},
);
/*
Abort the request as it isn't needed anymore, the component being
unmounted. It helps avoid, among other things, the well-known "can't
Expand Down
39 changes: 0 additions & 39 deletions src/frontend/src/controllers/API/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,45 +387,6 @@ export async function postCustomComponentUpdate(
});
}

export async function onLogin(user: LoginType) {
try {
const response = await api.post(
`${BASE_URL_API}login`,
new URLSearchParams({
username: user.username,
password: user.password,
}).toString(),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
);

if (response.status === 200) {
const data = response?.data;
return data;
}
} catch (error) {
throw error;
}
}

export async function autoLogin(abortSignal) {
try {
const response = await api.get(`${BASE_URL_API}auto_login`, {
signal: abortSignal,
});

if (response.status === 200) {
const data = response?.data;
return data;
}
} catch (error) {
throw error;
}
}

export async function renewAccessToken() {
try {
return await api.post(`${BASE_URL_API}refresh`);
Expand Down
34 changes: 23 additions & 11 deletions src/frontend/src/controllers/API/queries/auth/use-get-autologin.ts
Cristhianzl marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
import { keepPreviousData } from "@tanstack/react-query";
import { Users, useQueryFunctionType } from "../../../../types/api";
import { UseMutationResult } from "@tanstack/react-query";
import { useMutationFunctionType } from "../../../../types/api";
import { api } from "../../api";
import { getURL } from "../../helpers/constants";
import { UseRequestProcessor } from "../../services/request-processor";

export const useGetAutoLogin: useQueryFunctionType<undefined, Users> = () => {
const { query } = UseRequestProcessor();
interface AutoLoginParams {
abortSignal: AbortSignal;
}

const getIsAutoLogin = async () => {
const response = await api.get<Users>(`${getURL("AUTOLOGIN")}`);
return response["data"];
export const useAutoLogin: useMutationFunctionType<undefined, any> = (
options?,
) => {
const { mutate } = UseRequestProcessor();

const autoLoginFn = async ({
abortSignal,
}: AutoLoginParams): Promise<any> => {
const res = await api.get(`${getURL("AUTOLOGIN")}`, {
signal: abortSignal,
});
return res.data;
};

const queryResult = query(["useGetAutoLogin"], getIsAutoLogin, {
placeholderData: keepPreviousData,
});
const mutation: UseMutationResult = mutate(
["useAutoLogin"],
autoLoginFn,
options,
);

return queryResult;
return mutation;
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const useLoginUser: useMutationFunctionType<undefined, LoginType> = (
) => {
const { mutate } = UseRequestProcessor();

async function updateUser({ password, username }: LoginType): Promise<any> {
async function loginUserFn({ password, username }: LoginType): Promise<any> {
const res = await api.post(
`${getURL("LOGIN")}`,
new URLSearchParams({
Expand All @@ -27,7 +27,7 @@ export const useLoginUser: useMutationFunctionType<undefined, LoginType> = (

const mutation: UseMutationResult<LoginType, any, LoginType> = mutate(
["useLoginUser"],
updateUser,
loginUserFn,
options,
);

Expand Down
19 changes: 10 additions & 9 deletions src/frontend/src/pages/AdminPage/LoginPage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useLoginUser } from "@/controllers/API/queries/auth";
import { useContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { SIGNIN_ERROR_ALERT } from "../../../constants/alerts_constants";
import { CONTROL_LOGIN_STATE } from "../../../constants/constants";
import { AuthContext } from "../../../contexts/authContext";
import { onLogin } from "../../../controllers/API";
import useAlertStore from "../../../stores/alertStore";
import { LoginType } from "../../../types/api";
import {
Expand All @@ -29,26 +29,27 @@ export default function LoginAdminPage() {
setInputState((prev) => ({ ...prev, [name]: value }));
}

const { mutate } = useLoginUser();

function signIn() {
const user: LoginType = {
username: username,
password: password,
};
onLogin(user)
.then((user) => {
console.log("admin page");

mutate(user, {
onSuccess: (data) => {
setLoading(true);

login(user.access_token, "login");
login(data.access_token, "login");
navigate("/admin/");
})
.catch((error) => {
},
onError: (error) => {
setErrorData({
title: SIGNIN_ERROR_ALERT,
list: [error["response"]["data"]["detail"]],
});
});
},
});
}

return (
Expand Down
21 changes: 13 additions & 8 deletions src/frontend/src/pages/LoginPage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useLoginUser } from "@/controllers/API/queries/auth";
import * as Form from "@radix-ui/react-form";
import { useContext, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
Expand All @@ -7,7 +8,6 @@ import { Input } from "../../components/ui/input";
import { SIGNIN_ERROR_ALERT } from "../../constants/alerts_constants";
import { CONTROL_LOGIN_STATE } from "../../constants/constants";
import { AuthContext } from "../../contexts/authContext";
import { onLogin } from "../../controllers/API";
import useAlertStore from "../../stores/alertStore";
import useFlowsManagerStore from "../../stores/flowsManagerStore";
import { LoginType } from "../../types/api";
Expand All @@ -32,23 +32,28 @@ export default function LoginPage(): JSX.Element {
setInputState((prev) => ({ ...prev, [name]: value }));
}

const { mutate } = useLoginUser();

function signIn() {
const user: LoginType = {
username: username.trim(),
password: password.trim(),
};
onLogin(user)
.then((user) => {

mutate(user, {
onSuccess: (data) => {
console.log("admin page");
setLoading(true);
login(user.access_token, "login");
navigate("/");
})
.catch((error) => {
login(data.access_token, "login");
navigate("/admin/");
},
onError: (error) => {
setErrorData({
title: SIGNIN_ERROR_ALERT,
list: [error["response"]["data"]["detail"]],
});
});
},
});
}

return (
Expand Down
11 changes: 0 additions & 11 deletions src/frontend/src/stores/authStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,11 @@
import { LANGFLOW_ACCESS_TOKEN } from "@/constants/constants";
import useFlowsManagerStore from "@/stores/flowsManagerStore";
import { AuthStoreType } from "@/types/zustand/auth";
import { useNavigate } from "react-router-dom";
import Cookies from "universal-cookie";
import { create } from "zustand";
import {
getGlobalVariables,
getLoggedUser,
requestLogout,
} from "../controllers/API";
import useAlertStore from "../stores/alertStore";
import { useFolderStore } from "../stores/foldersStore";
import { useGlobalVariablesStore } from "../stores/globalVariablesStore/globalVariables";
import { useStoreStore } from "../stores/storeStore";
import { Users } from "../types/api";

const cookies = new Cookies();

const useAuthStore = create<AuthStoreType>((set, get) => ({
isAdmin: false,
isAuthenticated: !!cookies.get(LANGFLOW_ACCESS_TOKEN),
Expand Down
Loading