feat: add auth, hosts, & keychains ownership

This commit is contained in:
2024-11-10 18:49:35 +07:00
parent b2cc6778a6
commit 38e81049a1
31 changed files with 579 additions and 92 deletions
+12 -3
View File
@@ -12,6 +12,7 @@ import { router, usePathname, useRootNavigationState } from "expo-router";
import { useAuthStore } from "@/stores/auth";
import { PortalProvider } from "tamagui";
import { queryClient } from "@/lib/api";
import { useAppStore } from "@/stores/app";
type Props = PropsWithChildren;
@@ -53,16 +54,24 @@ const AuthProvider = () => {
const pathname = usePathname();
const rootNavigationState = useRootNavigationState();
const { isLoggedIn } = useAuthStore();
const { curServer } = useAppStore();
useEffect(() => {
if (!rootNavigationState?.key) {
return;
}
if (!pathname.startsWith("/auth") && !isLoggedIn) {
if (!curServer && !pathname.startsWith("/server")) {
router.replace("/server");
return;
}
const isProtected = !["/auth", "/server"].find((path) =>
pathname.startsWith(path)
);
if (isProtected && !isLoggedIn) {
router.replace("/auth/login");
} else if (pathname.startsWith("/auth") && isLoggedIn) {
router.replace("/");
}
}, [pathname, rootNavigationState, isLoggedIn]);
+2 -13
View File
@@ -1,14 +1,3 @@
import { View, Text, Button } from "tamagui";
import React from "react";
import authStore from "@/stores/auth";
import LoginPage from "@/pages/auth/login";
export default function LoginPage() {
return (
<View>
<Text>LoginPage</Text>
<Button onPress={() => authStore.setState({ token: "123" })}>
Login
</Button>
</View>
);
}
export default LoginPage;
+6
View File
@@ -1,9 +1,15 @@
import React from "react";
import { Redirect } from "expo-router";
import { useTermSession } from "@/stores/terminal-sessions";
import { useAppStore } from "@/stores/app";
export default function index() {
const { sessions, curSession } = useTermSession();
const { servers, curServer } = useAppStore();
if (!servers.length || !curServer) {
return <Redirect href="/server" />;
}
return (
<Redirect
+3
View File
@@ -0,0 +1,3 @@
import ServerPage from "@/pages/server/page";
export default ServerPage;
@@ -2,6 +2,7 @@ import React from "react";
import Terminal from "./terminal";
import { BASE_WS_URL } from "@/lib/api";
import VNCViewer from "./vncviewer";
import { useAuthStore } from "@/stores/auth";
type SSHSessionProps = {
type: "ssh";
@@ -28,7 +29,8 @@ export type InteractiveSessionProps = {
} & (SSHSessionProps | PVESessionProps | IncusSessionProps);
const InteractiveSession = ({ type, params }: InteractiveSessionProps) => {
const query = new URLSearchParams(params);
const { token } = useAuthStore();
const query = new URLSearchParams({ ...params, sid: token || "" });
const url = `${BASE_WS_URL}/ws/term?${query}`;
switch (type) {
@@ -0,0 +1,29 @@
import React from "react";
import { Button, GetProps } from "tamagui";
import Icons from "../ui/icons";
import useThemeStore from "@/stores/theme";
type Props = GetProps<typeof Button> & {
iconSize?: number;
};
const ThemeSwitcher = ({ iconSize = 24, ...props }: Props) => {
const { theme, toggle } = useThemeStore();
return (
<Button
icon={
<Icons
name={
theme === "light" ? "white-balance-sunny" : "moon-waning-crescent"
}
size={iconSize}
/>
}
onPress={toggle}
{...props}
/>
);
};
export default ThemeSwitcher;
+12 -2
View File
@@ -4,11 +4,21 @@ import { Label, Text, View, XStack } from "tamagui";
type FormFieldProps = ComponentPropsWithoutRef<typeof XStack> & {
label?: string;
htmlFor?: string;
vertical?: boolean;
};
const FormField = ({ label, htmlFor, ...props }: FormFieldProps) => {
const FormField = ({
label,
htmlFor,
vertical = false,
...props
}: FormFieldProps) => {
return (
<XStack alignItems="flex-start" {...props}>
<XStack
flexDirection={vertical ? "column" : "row"}
alignItems={vertical ? "stretch" : "flex-start"}
{...props}
>
<Label htmlFor={htmlFor} w={120} $xs={{ w: 100 }}>
{label}
</Label>
+12
View File
@@ -1,3 +1,4 @@
import authStore from "@/stores/auth";
import { QueryClient } from "@tanstack/react-query";
import { ofetch } from "ofetch";
@@ -6,7 +7,18 @@ export const BASE_WS_URL = BASE_API_URL.replace("http", "ws");
const api = ofetch.create({
baseURL: BASE_API_URL,
onRequest: (config) => {
const authToken = authStore.getState().token;
if (authToken) {
config.options.headers.set("Authorization", `Bearer ${authToken}`);
}
},
onResponseError: (error) => {
if (error.response.status === 401 && !!authStore.getState().token) {
authStore.setState({ token: null });
throw new Error("Unauthorized");
}
if (error.response._data) {
const message = error.response._data.message;
throw new Error(message || "Something went wrong");
+92
View File
@@ -0,0 +1,92 @@
import { Text, ScrollView, Card, Separator } from "tamagui";
import React from "react";
import FormField from "@/components/ui/form";
import { InputField } from "@/components/ui/input";
import { useZForm } from "@/hooks/useZForm";
import { router, Stack } from "expo-router";
import Button from "@/components/ui/button";
import ThemeSwitcher from "@/components/containers/theme-switcher";
import { useMutation } from "@tanstack/react-query";
import { z } from "zod";
import { ErrorAlert } from "@/components/ui/alert";
import { loginResultSchema, loginSchema } from "./schema";
import api from "@/lib/api";
import Icons from "@/components/ui/icons";
import authStore from "@/stores/auth";
export default function LoginPage() {
const form = useZForm(loginSchema);
const login = useMutation({
mutationFn: async (body: z.infer<typeof loginSchema>) => {
const res = await api("/auth/login", { method: "POST", body });
const { data } = loginResultSchema.safeParse(res);
if (!data) {
throw new Error("Invalid response!");
}
return data;
},
onSuccess(data) {
authStore.setState({ token: data.sessionId });
router.replace("/");
},
});
const onSubmit = form.handleSubmit((values) => {
login.mutate(values);
});
return (
<>
<Stack.Screen
options={{
contentStyle: {
width: "100%",
maxWidth: 600,
marginHorizontal: "auto",
},
title: "Login",
headerRight: () => (
<ThemeSwitcher bg="$colorTransparent" $gtSm={{ mr: "$3" }} />
),
}}
/>
<ScrollView
contentContainerStyle={{
padding: "$4",
pb: "$12",
justifyContent: "center",
flexGrow: 1,
}}
>
<Card bordered p="$4" gap="$4">
<Text fontSize="$8">Login</Text>
<ErrorAlert error={login.error} />
<FormField vertical label="Username/Email">
<InputField form={form} name="username" />
</FormField>
<FormField vertical label="Password">
<InputField form={form} name="password" secureTextEntry />
</FormField>
<Separator />
<Button
icon={<Icons name="lock" size={16} />}
onPress={onSubmit}
isLoading={login.isPending}
>
Connect
</Button>
<Button onPress={() => router.push("/server")} bg="$colorTransparent">
Change Server
</Button>
</Card>
</ScrollView>
</>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { z } from "zod";
export const loginSchema = z.object({
username: z.string(),
password: z.string(),
});
export const loginResultSchema = z.object({
sessionId: z.string().min(40),
});
+78
View File
@@ -0,0 +1,78 @@
import { View, Text, ScrollView, Card } from "tamagui";
import React from "react";
import FormField from "@/components/ui/form";
import { InputField } from "@/components/ui/input";
import { useZForm } from "@/hooks/useZForm";
import { getServerResultSchema, serverSchema } from "./schema";
import { router, Stack } from "expo-router";
import Button from "@/components/ui/button";
import ThemeSwitcher from "@/components/containers/theme-switcher";
import { useMutation } from "@tanstack/react-query";
import { ofetch } from "ofetch";
import { z } from "zod";
import { ErrorAlert } from "@/components/ui/alert";
import { addServer } from "@/stores/app";
export default function ServerPage() {
const form = useZForm(serverSchema);
const serverConnect = useMutation({
mutationFn: async (body: z.infer<typeof serverSchema>) => {
const res = await ofetch(body.url + "/server");
const { data } = getServerResultSchema.safeParse(res);
if (!data) {
throw new Error("Invalid server");
}
return data;
},
onSuccess(data, payload) {
addServer({ url: payload.url, name: data.name }, true);
router.replace("/auth/login");
},
});
const onSubmit = form.handleSubmit((values) => {
serverConnect.mutate(values);
});
return (
<>
<Stack.Screen
options={{
contentStyle: {
width: "100%",
maxWidth: 600,
marginHorizontal: "auto",
},
title: "Vaulterm",
headerRight: () => (
<ThemeSwitcher bg="$colorTransparent" $gtSm={{ mr: "$3" }} />
),
}}
/>
<ScrollView
contentContainerStyle={{
padding: "$4",
pb: "$12",
justifyContent: "center",
flexGrow: 1,
}}
>
<Card bordered p="$4" gap="$4">
<Text fontSize="$8">Connect to Server</Text>
<ErrorAlert error={serverConnect.error} />
<FormField vertical label="URL">
<InputField form={form} name="url" placeholder="https://" />
</FormField>
<Button onPress={onSubmit} isLoading={serverConnect.isPending}>
Connect
</Button>
</Card>
</ScrollView>
</>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { z } from "zod";
export const serverSchema = z.object({
url: z.string().url("Invalid URL"),
});
export const getServerResultSchema = z.object({
name: z.string(),
version: z.string().min(1),
});
+62
View File
@@ -0,0 +1,62 @@
import { createStore, useStore } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";
type AppServer = {
name?: string;
url: string;
};
type AppStore = {
servers: AppServer[];
curServerIdx?: number | null;
};
const appStore = createStore(
persist<AppStore>(
() => ({
servers: [],
curServerIdx: null,
}),
{
name: "vaulterm:app",
storage: createJSONStorage(() => AsyncStorage),
}
)
);
export function addServer(srv: AppServer, setActive?: boolean) {
const curServers = appStore.getState().servers;
const isExist = curServers.findIndex((s) => s.url === srv.url);
if (isExist >= 0) {
setActiveServer(isExist);
return;
}
appStore.setState((state) => ({
servers: [...state.servers, srv],
curServerIdx: setActive ? state.servers.length : state.curServerIdx,
}));
}
export function removeServer(idx: number) {
appStore.setState((state) => ({
servers: state.servers.filter((_, i) => i !== idx),
curServerIdx: state.curServerIdx === idx ? null : state.curServerIdx,
}));
}
export function setActiveServer(idx: number) {
appStore.setState({ curServerIdx: idx });
}
export const useAppStore = () => {
const state = useStore(appStore);
const curServer =
state.curServerIdx != null ? state.servers[state.curServerIdx] : null;
return { ...state, curServer };
};
export default appStore;
+1 -1
View File
@@ -12,7 +12,7 @@ const authStore = createStore(
token: null,
}),
{
name: "auth",
name: "vaulterm:auth",
storage: createJSONStorage(() => AsyncStorage),
}
)
+4 -1
View File
@@ -38,6 +38,9 @@ export const useTermSession = create(
set({ curSession: idx });
},
}),
{ name: "term-sessions", storage: createJSONStorage(() => AsyncStorage) }
{
name: "vaulterm:term-sessions",
storage: createJSONStorage(() => AsyncStorage),
}
)
);
+1 -1
View File
@@ -20,7 +20,7 @@ const useThemeStore = create(
},
}),
{
name: "theme",
name: "vaulterm:theme",
storage: createJSONStorage(() => AsyncStorage),
}
)