Skip to content

Commit

Permalink
Login update
Browse files Browse the repository at this point in the history
  • Loading branch information
Gessmass committed Nov 8, 2024
1 parent 8d638e0 commit 6d7b919
Show file tree
Hide file tree
Showing 10 changed files with 179 additions and 133 deletions.
17 changes: 9 additions & 8 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,16 +90,17 @@ const start = async () => {
const cookies = cookie.parse(req.headers.cookie ?? "");

if (cookies.token) {
const payload = jwt.verify(
cookies.token,
process.env.JWT_SECRET_KEY
) as jwt.JwtPayload;

if (payload) {
return {...payload, res: res};
try {
const payload = jwt.verify(cookies.token, process.env.JWT_SECRET_KEY) as jwt.JwtPayload;

if (payload) {
return {...payload, res};
}
} catch (err) {
console.error("Invalid token:", err.message);
}
}
return {res: res};
return {res};
},
})

Expand Down
12 changes: 5 additions & 7 deletions backend/src/resolvers/FileResolver.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { File } from "../entities/file";
import { Query, Resolver } from "type-graphql";
import { Arg, Mutation } from "type-graphql";
import {File, StatusOption} from "../entities/file";
import {Arg, Ctx, Mutation, Query, Resolver} from "type-graphql";
import axios from "axios";
import {User} from "../entities/user";
import {dataSource} from "../config/db";
import { StatusOption } from "../entities/file";

import {Context} from "../index";

@Resolver(File)
class FileResolver {
Expand All @@ -16,11 +14,11 @@ class FileResolver {


@Query(() => [File])
async getUserAccessSharedFiles(@Arg('userId') userId: number) {
async getUserAccessSharedFiles(@Ctx() context: Context) {

return await File.createQueryBuilder("file")
.leftJoin("file.users_with_access", "user")
.where("user.id = :userId", {userId})
.where("user.id = :userId", {userId: context.id})
.getMany()

}
Expand Down
17 changes: 10 additions & 7 deletions backend/src/resolvers/UserResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class UserResolver {
return "You have successfully signed up!"
}

@Mutation(() => String)
@Mutation(() => UserInfo)
async login(
@Arg("email") emailFromClient: string,
@Arg("password") passwordFromClient: string,
Expand Down Expand Up @@ -92,7 +92,14 @@ class UserResolver {
});

context.res.setHeader("Set-Cookie", serializedCookie);
return "Login accepted";

return {
email: userFromDB.email,
role: userFromDB.role,
firstname: userFromDB.firstname,
lastname: userFromDB.lastname,
isLoggedIn: true,
};

} catch (err) {
if (err instanceof EntityNotFoundError || err instanceof AuthenticationError) {
Expand All @@ -112,10 +119,8 @@ class UserResolver {

@Query(() => UserInfo)
async getConnectedUser(@Ctx() context: Context): Promise<UserInfo> {
console.log("=>>>>>>>>>>>> CHECKING CONNECTED USER")

const user: User | null = await User.findOneBy({id: context.id});
console.log("===========> user", user);
console.log("===========> context", context);

if (user) {
return {
Expand Down Expand Up @@ -143,8 +148,6 @@ class UserResolver {
throw new Error("User not authenticated");
}

console.log('======> USER FIES', context)

const user = await User.findOne({
where: {id: 3},
relations: ['uploads', 'uploads.files'],
Expand Down
128 changes: 58 additions & 70 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,86 +1,74 @@
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import {createBrowserRouter, Navigate, RouterProvider} from "react-router-dom";
import LandingPage from "./pages/LandingPage";
import AccessPage from "./pages/AccessPage.tsx";
import NotFoundPage from "./pages/NotFoundPage.tsx";
import Dashboard from "./pages/DashboardPage.tsx";
import SettingsPage from "./pages/SettingsPage.tsx";
import UserLayout, { UserContext } from "./components/user/UserLayout.tsx";
import UserLayout from "./components/user/UserLayout.tsx";
import VisitorLayout from "./components/visitor/VisitorLayout.tsx";
import { Container } from "./globalStyles.tsx";
import PricingPage from "./pages/PricingPage.tsx";
import BillingPage from "./pages/BillingPage.tsx";
import VisitorDownloadPage from "./pages/VisitorDownloadPage.tsx";
import { Navigate } from "react-router-dom";
import { useContext } from "react";
import { createContext } from "react";
import {FC} from "react";
import {UserProvider, useUserContext} from "./context/UserContext.tsx";

// Context setup
export const UserContext = createContext({
isLoggedIn: false,
email: "",
role: "",
firstname: "",
lastname: "",
refetch: () => {}
});
interface ProtectedRouteProps {
isLoggedIn: boolean;
children: React.ReactNode;
}

const App = () => {
const {data, error, loading, refetch} = useQuery(GET_CONNECTED_USER);

interface ProtectedRouteProps {
isLoggedIn: boolean;
children: React.ReactNode;
}
const { isLoggedIn } = useContext(UserContext);
const ProtectedRoute = ({isLoggedIn, children}: ProtectedRouteProps) => {
console.log("is logged in", isLoggedIn);
if (!isLoggedIn) {
return <Navigate to="/"/>;
}

const ProtectedRoute = ({ isLoggedIn, children }:ProtectedRouteProps) => {
console.log("is logged in", isLoggedIn);
if (!isLoggedIn) {
return <Navigate to="/" />;
}

return children;
}
return children;
}

const router = createBrowserRouter([
{ path: "/", element: <LandingPage /> },
{ path: "*", element: <NotFoundPage /> },
{
path: "/access",
element: <VisitorLayout />,
children: [
{ path: "login", element: <AccessPage /> },
{ path: "register", element: <AccessPage /> },
{ path: "pricing", element: <PricingPage /> },
{ path: "download", element: <VisitorDownloadPage /> },
],
},
{
path: "/dashboard",
element: <UserLayout />,
children: [
{ index: true, element: <ProtectedRoute isLoggedIn={isLoggedIn}><Dashboard /></ProtectedRoute>},
{ path: "settings", element: <SettingsPage /> },
{ path: "billing", element: <BillingPage /> },
],
},
]);

return (
<Container>
<UserContext.Provider
value={{
isLoggedIn: data.getConnectedUser.isLoggedIn ?? "",
email: data.getConnectedUser.email ?? "",
role: data.getConnectedUser.role ?? "",
firstname: data.getConnectedUser.firstname ?? "",
lastname: data.getConnectedUser.lastname ?? "",
refetch: refetch
}}>
<RouterProvider router={router} />
</UserContext.Provider>
</Container>
);
const App: FC = () => {
return (
<UserProvider>
<MainLayout/>
</UserProvider>
);
};

const MainLayout: FC = () => {
const {isLoggedIn} = useUserContext()

const router = createBrowserRouter([
{path: "/", element: <LandingPage/>},
{path: "*", element: <NotFoundPage/>},
{
path: "/access",
element: <VisitorLayout/>,
children: [
{path: "login", element: <AccessPage/>},
{path: "register", element: <AccessPage/>},
{path: "pricing", element: <PricingPage/>},
{path: "download", element: <VisitorDownloadPage/>},
],
},
{
path: "/dashboard",
element: <UserLayout/>,
children: [
{
index: true,
element: <ProtectedRoute isLoggedIn={isLoggedIn}><Dashboard/></ProtectedRoute>
},
{path: "settings", element: <SettingsPage/>},
{path: "billing", element: <BillingPage/>},
],
},
]);

return (
<>
<RouterProvider router={router}/>
</>
)
}

export default App;
15 changes: 7 additions & 8 deletions frontend/src/components/Signin/SignInForm.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import React, { useContext } from "react";
import React from "react";
import {colors} from "../../_colors.ts";
import {Button, Form, Input, notification} from 'antd'
import {LOGIN_MUTATION} from "../../graphql/mutations.ts";
import {useNavigate} from 'react-router-dom'
import {ApolloError, useMutation} from "@apollo/client";
import styled from "@emotion/styled";
import { UserContext } from "../user/UserLayout.tsx";
import {useUserContext} from "../../context/UserContext.tsx";

const {Item} = Form

const SignInForm: React.FC = () => {
const [notifApi, contextHolder] = notification.useNotification()
const navigate = useNavigate()
const userInfo = useContext(UserContext);
console.log("user info", userInfo)
const {setUser} = useUserContext()


const [login, {loading, error}] = useMutation(LOGIN_MUTATION, {
onCompleted: () => {
userInfo.refetch()
// console.log("Login successful", userInfo);
// console.log("login", login)
onCompleted: (data) => {
setUser(data.login)
navigate("/dashboard");
},
onError: (error: ApolloError) => {
Expand Down
38 changes: 24 additions & 14 deletions frontend/src/components/user/UserLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import {createContext, FC} from "react";
import {FC} from "react";
import {HeaderContainer, WildTransferLogo} from "../visitor/VisitorLayout.tsx";
import styled from "@emotion/styled";
import {Avatar, Dropdown, MenuProps} from "antd";
import {DashboardOutlined, DollarOutlined, LogoutOutlined, SettingOutlined} from "@ant-design/icons";
import {Link, Outlet, useNavigate} from "react-router-dom";
import {ApolloError, useMutation, useQuery} from '@apollo/client';
import {ApolloError, useMutation} from '@apollo/client';
import {LOGOUT} from "../../graphql/mutations.ts";
import {GET_CONNECTED_USER} from "../../graphql/queries.ts";
import {useUserContext} from "../../context/UserContext.tsx";

const UserLayout: FC = () => {
const navigate = useNavigate();
const {setUser} = useUserContext()

const [logout] = useMutation(LOGOUT, {
onCompleted: () => {
setUser({
isLoggedIn: false,
role: '',
firstname: '',
lastname: '',
email: '',
})
navigate('/');
},
onError: (err: ApolloError) => {
Expand All @@ -23,6 +32,7 @@ const UserLayout: FC = () => {
logout();
};


const items: MenuProps['items'] = [
{
label: <Link to='/dashboard'>Dashboard</Link>,
Expand All @@ -47,16 +57,16 @@ const UserLayout: FC = () => {
},
];

if (loading) {
return <p>Loading...</p>;
}

if (error || !data || !data.getConnectedUser) {
console.log(error)
return <p>Error loading user data.</p>;
}

console.log(data)
// if (loading) {
// return <p>Loading...</p>;
// }
//
// if (error || !data || !data.getConnectedUser) {
// console.log(error)
// return <p>Error loading user data.</p>;
// }
//
// console.log(data)

return (
<UserLayoutContainer>
Expand All @@ -67,7 +77,7 @@ const UserLayout: FC = () => {
backgroundColor: '#fde3cf',
color: '#f56a00',
cursor: 'pointer'
}}>{data.getConnectedUser.firstname.charAt(0).toUpperCase()}</Avatar>
}}>WWW</Avatar>
</Dropdown>
</HeaderContainer>
<Outlet/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ const {Column} = Table
const SharedFilesTable: FC = () => {
const [selectedFiles, setSelectedFiles] = useState<OwnTableDatasource[] | []>([])

const {data, loading, error} = useQuery(GET_USER_SHARED_FILES, {
variables: {
userId: 1,
},
});
const {data, loading, error} = useQuery(GET_USER_SHARED_FILES);

const handleRowSelection = (e): void => {
console.log(e)
Expand Down
Loading

0 comments on commit 6d7b919

Please sign in to comment.