Skip to content

Commit

Permalink
Merge branch 'login-register' of github.com:Karol-2/Mercury-Project i…
Browse files Browse the repository at this point in the history
…nto login-register
  • Loading branch information
Piterson25 committed Nov 23, 2023
2 parents 89b8528 + d71d7da commit cef68f7
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 47 deletions.
15 changes: 3 additions & 12 deletions backend/src/routes/authRoute.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
import { Router, Request, Response } from "express";
import { Router, Request } from "express";

import driver from "../driver/driver";
import { generateAccessToken, generateRefreshToken } from "../misc/jwt";
import {
CustomResponse,
JWTResponse,
AuthResponse,
ErrorResponse,
OkResponse,
} from "../models/Response";

import jwt, { JwtPayload } from "jsonwebtoken";
import { TokenErrorResponse } from "../types/authResponse";
import { CustomResponse, OkResponse } from "../models/Response";

const authRouter = Router();

type TokenErrorResponse = CustomResponse<
JWTResponse | AuthResponse | ErrorResponse
>;

function generateTokens(res: TokenErrorResponse, userId: string) {
const token = generateAccessToken(userId);
const refreshToken = generateRefreshToken(userId);
Expand Down
24 changes: 7 additions & 17 deletions backend/src/routes/usersRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,17 @@ import { Session } from "neo4j-driver";

import chatRouter from "./chatsRoute";
import driver from "../driver/driver";
import {
CustomResponse,
ErrorResponse,
OkResponse,
UserResponse,
UsersResponse,
FriendsResponse,
UsersSearchResponse,
} from "../models/Response";

import wordToVec from "../misc/wordToVec";
import User from "../models/User";
import { JWTRequest, authenticateToken } from "../misc/jwt";
import {
FriendsErrorResponse,
OkErrorResponse,
UserErrorResponse,
UsersErrorResponse,
UsersSearchErrorResponse,
} from "../types/userResponse";

const usersRouter = Router();

Expand All @@ -39,14 +37,6 @@ async function userExists(
return userExistsResult.records[0].get("u").properties as User;
}

type UsersErrorResponse = CustomResponse<UsersResponse | ErrorResponse>;
type UserErrorResponse = CustomResponse<UserResponse | ErrorResponse>;
type OkErrorResponse = CustomResponse<OkResponse | ErrorResponse>;
type FriendsErrorResponse = CustomResponse<FriendsResponse | ErrorResponse>;
type UsersSearchErrorResponse = CustomResponse<
UsersSearchResponse | ErrorResponse
>;

usersRouter.get("/", async (_req: Request, res: UsersErrorResponse) => {
try {
const session = driver.session();
Expand Down
10 changes: 10 additions & 0 deletions backend/src/types/authResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {
CustomResponse,
JWTResponse,
AuthResponse,
ErrorResponse,
} from "../models/Response";

export type TokenErrorResponse = CustomResponse<
JWTResponse | AuthResponse | ErrorResponse
>;
19 changes: 19 additions & 0 deletions backend/src/types/userResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {
CustomResponse,
ErrorResponse,
OkResponse,
UserResponse,
UsersResponse,
FriendsResponse,
UsersSearchResponse,
} from "../models/Response";

export type UsersErrorResponse = CustomResponse<UsersResponse | ErrorResponse>;
export type UserErrorResponse = CustomResponse<UserResponse | ErrorResponse>;
export type OkErrorResponse = CustomResponse<OkResponse | ErrorResponse>;
export type FriendsErrorResponse = CustomResponse<
FriendsResponse | ErrorResponse
>;
export type UsersSearchErrorResponse = CustomResponse<
UsersSearchResponse | ErrorResponse
>;
6 changes: 3 additions & 3 deletions frontend/src/components/LoginBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ function LoginBox() {
};

useEffect(() => {
if (userId === null) return;
if (userId === undefined) return;

if (userId === "") {
if (userId === null) {
setLoginMsg("Bad credentials");
} else {
if (window.history.state && window.history.state.idx > 0) {
navigate(-1 as any, { replace: true });
} else {
navigate("/", { replace: true });
navigate("/messages", { replace: true });
}
setLoginMsg("Logging in...");
}
Expand Down
41 changes: 27 additions & 14 deletions frontend/src/helpers/UserProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { fetchData } from "../services/fetchData";
import User from "../models/user.model";

export interface UserContextValue {
userId: string | null;
user: User | null;
setUser: React.Dispatch<React.SetStateAction<User | null>>;
userId: string | null | undefined;
user: User | null | undefined;
setUser: React.Dispatch<React.SetStateAction<User | null | undefined>>;
login: (mail: string, password: string) => Promise<void>;
logout: () => Promise<boolean>;
updateUser: () => Promise<boolean>;
Expand All @@ -32,8 +32,12 @@ function useUser() {
}

function UserProvider({ children }: { children: React.ReactNode }) {
const [userId, setUserId] = useState<string | null>(null);
const [user, setUser] = useState<User | null>(null);
// userId:
// undefined -> user state is loading
// null -> user not logged in
// string -> user logged in, userID correct
const [userId, setUserId] = useState<string | null | undefined>(undefined);
const [user, setUser] = useState<User | null | undefined>(null);
const [token, setToken] = useState<object | null>(null);
const firstRefresh = useRef(true);

Expand All @@ -57,15 +61,19 @@ function UserProvider({ children }: { children: React.ReactNode }) {

// Try to use refresh token from cookies
const refreshTokenStr = Cookies.get("refreshToken");
if (!refreshTokenStr) return;
if (refreshTokenStr) {
const response = await fetchData("/auth/refresh", "POST", {
headers: {
"Content-Type": "application/json",
},
});

const response = await fetchData("/auth/refresh", "POST", {
headers: {
"Content-Type": "application/json",
},
});
if (trySetToken(response.token)) {
return;
}
}

trySetToken(response.token);
setUserId(null);
};

const login = async (mail: string, password: string) => {
Expand All @@ -82,7 +90,7 @@ function UserProvider({ children }: { children: React.ReactNode }) {
});

if (response.status != "ok") {
setUserId("");
setUserId(null);
return;
}

Expand Down Expand Up @@ -125,6 +133,7 @@ function UserProvider({ children }: { children: React.ReactNode }) {

const response = await fetchData(`/users/${user.id}`, "DELETE");
if (response.status === "ok") {
setUserId(null);
setUser(null);
return true;
}
Expand All @@ -137,8 +146,8 @@ function UserProvider({ children }: { children: React.ReactNode }) {
if (token) {
const newUserId = (token as any).userId;
fetchData(`/users/${newUserId}`, "GET").then((response) => {
setUser(response.user as any);
setUserId(newUserId);
setUser(response.user as any);
});
}
}, [token]);
Expand All @@ -148,6 +157,10 @@ function UserProvider({ children }: { children: React.ReactNode }) {
getAccessToken();
}

useEffect(() => {
console.log(userId);
}, [userId]);

return (
<UserContext.Provider
value={{ userId, user, setUser, login, logout, updateUser, deleteUser }}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/ProfilePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function ProfilePage() {
};

useEffect(() => {
if (!userId) navigate("/login");
if (userId === null) navigate("/login");
}, [userId]);

return (
Expand Down

0 comments on commit cef68f7

Please sign in to comment.