fixing auth check and content type error
This commit is contained in:
@@ -22,7 +22,7 @@ export const authCheck = async (
|
|||||||
// verify jwt token with our api secret
|
// verify jwt token with our api secret
|
||||||
var decoded: JwtClaims = jwt.verify(authorization, config.JWT_TOKEN_SECRET);
|
var decoded: JwtClaims = jwt.verify(authorization, config.JWT_TOKEN_SECRET);
|
||||||
|
|
||||||
res.locals.jwtClaims = decoded;
|
res.locals.userInfo = decoded;
|
||||||
|
|
||||||
next();
|
next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
+28
-10
@@ -1,13 +1,14 @@
|
|||||||
import { GoogleUserInfo, User } from "@nirvana/core/models";
|
import { GoogleUserInfo, User } from "@nirvana/core/models";
|
||||||
|
import { JwtClaims, authCheck } from "../middleware/auth";
|
||||||
import express, { Application, Request, Response } from "express";
|
import express, { Application, Request, Response } from "express";
|
||||||
|
|
||||||
import LoginResponse from "../../core/responses/login.response";
|
import LoginResponse from "../../core/responses/login.response";
|
||||||
import { OAuth2Client } from "google-auth-library";
|
import { OAuth2Client } from "google-auth-library";
|
||||||
import { ObjectID } from "bson";
|
import { ObjectID } from "bson";
|
||||||
import { ObjectId } from "mongodb";
|
import { ObjectId } from "mongodb";
|
||||||
|
import UserDetailsResponse from "../../core/responses/userDetails.response";
|
||||||
import { UserService } from "../services/user.service";
|
import { UserService } from "../services/user.service";
|
||||||
import { UserStatus } from "../../core/models/user.model";
|
import { UserStatus } from "../../core/models/user.model";
|
||||||
import { authCheck } from "../middleware/auth";
|
|
||||||
import { collections } from "../services/database.service";
|
import { collections } from "../services/database.service";
|
||||||
import { loadConfig } from "../config";
|
import { loadConfig } from "../config";
|
||||||
|
|
||||||
@@ -23,7 +24,7 @@ export default function getUserRoutes() {
|
|||||||
router.use(express.json());
|
router.use(express.json());
|
||||||
|
|
||||||
// get user details based on id token
|
// get user details based on id token
|
||||||
// router.get("/", authCheck, getUserDetails);
|
router.get("/", authCheck, getUserDetails);
|
||||||
|
|
||||||
router.get("/login", login);
|
router.get("/login", login);
|
||||||
|
|
||||||
@@ -34,9 +35,26 @@ export default function getUserRoutes() {
|
|||||||
|
|
||||||
async function handleAuthCheck(req: Request, res: Response) {
|
async function handleAuthCheck(req: Request, res: Response) {
|
||||||
try {
|
try {
|
||||||
res.status(200).send();
|
res.status(200).json("You are good to go!");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(401).send();
|
res.status(401).json("Unauthorized");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getUserDetails(req: Request, res: Response) {
|
||||||
|
try {
|
||||||
|
console.log(res.locals.userInfo as JwtClaims);
|
||||||
|
|
||||||
|
const userInfo = res.locals.userInfo as JwtClaims;
|
||||||
|
|
||||||
|
const user = await UserService.getUserById(userInfo.userId);
|
||||||
|
|
||||||
|
user
|
||||||
|
? res.status(200).json(new UserDetailsResponse(user))
|
||||||
|
: res.status(404).json("No such user");
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
res.status(500).json(`Problem with signing user up or logging in`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +74,7 @@ async function login(req: Request, res: Response) {
|
|||||||
const email = ticket.getPayload()?.email as string;
|
const email = ticket.getPayload()?.email as string;
|
||||||
|
|
||||||
if (!googleUserId || !email) {
|
if (!googleUserId || !email) {
|
||||||
res.status(401).send("no google account found");
|
res.status(401).json("no google account found");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +84,7 @@ async function login(req: Request, res: Response) {
|
|||||||
// if no user found, then go ahead and create user
|
// if no user found, then go ahead and create user
|
||||||
if (!user) {
|
if (!user) {
|
||||||
if (!access_token) {
|
if (!access_token) {
|
||||||
res.status(400).send("No access token provided");
|
res.status(400).json("No access token provided");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,8 +127,8 @@ async function login(req: Request, res: Response) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
insertResult
|
insertResult
|
||||||
? res.status(200).send(new LoginResponse(jwtToken, newUser))
|
? res.status(200).json(new LoginResponse(jwtToken, newUser))
|
||||||
: res.status(500).send("Failed to create account, already exists");
|
: res.status(500).json("Failed to create account, already exists");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -127,9 +145,9 @@ async function login(req: Request, res: Response) {
|
|||||||
config.JWT_TOKEN_SECRET
|
config.JWT_TOKEN_SECRET
|
||||||
);
|
);
|
||||||
|
|
||||||
res.status(200).send(new LoginResponse(jwtToken, user));
|
res.status(200).json(new LoginResponse(jwtToken, user));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
res.status(500).send(`Problem with signing user up or logging in`);
|
res.status(500).json(`Problem with signing user up or logging in`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,21 @@ import axios from "axios";
|
|||||||
import { collections } from "./database.service";
|
import { collections } from "./database.service";
|
||||||
|
|
||||||
export class UserService {
|
export class UserService {
|
||||||
static async getUserByGoogleId(userId: string) {
|
static async getUserById(userId: string) {
|
||||||
const query = { googleId: userId };
|
const query = { _id: userId };
|
||||||
|
|
||||||
|
const res = await collections.users?.findOne(query);
|
||||||
|
|
||||||
|
// exists
|
||||||
|
if (res?._id) {
|
||||||
|
return res as User;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getUserByGoogleId(googleUserId: string) {
|
||||||
|
const query = { googleId: googleUserId };
|
||||||
|
|
||||||
const res = await collections.users?.findOne(query);
|
const res = await collections.users?.findOne(query);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { User } from "@nirvana/core/models";
|
||||||
|
|
||||||
|
export default class UserDetailsResponse {
|
||||||
|
constructor(public user: User) {}
|
||||||
|
}
|
||||||
@@ -1,32 +1,28 @@
|
|||||||
import NirvanaApi, { authCheck, login } from "./nirvanaApi";
|
import NirvanaApi, { ApiCalls } from "./nirvanaApi";
|
||||||
import { useMutation, useQuery } from "react-query";
|
import { useMutation, useQuery } from "react-query";
|
||||||
|
|
||||||
// ====== QUERIES
|
// ====== QUERIES
|
||||||
export function useAuthCheck() {
|
export function useAuthCheck() {
|
||||||
return useQuery("AUTH_CHECK", authCheck, {
|
return useQuery("AUTH_CHECK", ApiCalls.authCheck, {
|
||||||
retry: false,
|
retry: false,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
enabled: NirvanaApi._jwtToken ? true : false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useLogin() {
|
export function useLogin() {
|
||||||
return useMutation("LOGIN", login, {});
|
return useMutation("LOGIN", ApiCalls.login, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
// export function useGetUserDetails() {
|
export function useGetUserDetails() {
|
||||||
// const authTokens = useRecoilValue($authTokens);
|
return useQuery("USER_DETAILS", ApiCalls.getUserDetails, {
|
||||||
|
retry: false,
|
||||||
// return useQuery(
|
refetchOnWindowFocus: false,
|
||||||
// Querytypes.GET_USER_DETAILS,
|
onError: (err) => {
|
||||||
// () => getUserDetails(authTokens?.accessToken, authTokens?.idToken),
|
console.log(err);
|
||||||
// {
|
},
|
||||||
// retry: false,
|
});
|
||||||
// refetchOnWindowFocus: false,
|
}
|
||||||
// onError: (err) => {
|
|
||||||
// console.log(err);
|
|
||||||
// },
|
|
||||||
// }
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
|
|
||||||
// export function useSearch() {
|
// export function useSearch() {
|
||||||
// const authTokens = useRecoilValue($authTokens);
|
// const authTokens = useRecoilValue($authTokens);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import axios, { AxiosRequestConfig, AxiosResponse, Method } from "axios";
|
|||||||
|
|
||||||
import LoginResponse from "../../../core/responses/login.response";
|
import LoginResponse from "../../../core/responses/login.response";
|
||||||
import { User } from "@nirvana/core/models";
|
import { User } from "@nirvana/core/models";
|
||||||
|
import UserDetailsResponse from "../../../core/responses/userDetails.response";
|
||||||
|
|
||||||
// export const localHost = process.env.REACT_APP_API_DOMAIN;
|
// export const localHost = process.env.REACT_APP_API_DOMAIN;
|
||||||
|
|
||||||
@@ -16,9 +17,9 @@ export default class NirvanaApi {
|
|||||||
// error if no auth token and it's a private route
|
// error if no auth token and it's a private route
|
||||||
// throw error and show message on anything that is an error from the backend
|
// throw error and show message on anything that is an error from the backend
|
||||||
|
|
||||||
try {
|
const fullUrl = localHost + url;
|
||||||
const fullUrl = localHost + url;
|
|
||||||
|
|
||||||
|
try {
|
||||||
let res;
|
let res;
|
||||||
if (privateRoute && !this._jwtToken)
|
if (privateRoute && !this._jwtToken)
|
||||||
throw Error("No jwt token available!");
|
throw Error("No jwt token available!");
|
||||||
@@ -33,19 +34,20 @@ export default class NirvanaApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (res.status === 401) throw Error("You are not authorized here");
|
if (res.status === 401) throw new Error("You are not authorized here");
|
||||||
|
|
||||||
throw Error("Something went wrong");
|
throw new Error("Something went wrong");
|
||||||
}
|
}
|
||||||
|
|
||||||
return await res.json();
|
return await res.json();
|
||||||
} catch (error: any) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function login(reqLoginTokens: {
|
async function login(reqLoginTokens: {
|
||||||
accessToken: string;
|
accessToken: string;
|
||||||
idToken: string;
|
idToken: string;
|
||||||
}): Promise<LoginResponse> {
|
}): Promise<LoginResponse> {
|
||||||
@@ -56,6 +58,16 @@ export async function login(reqLoginTokens: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function authCheck(): Promise<void> {
|
async function authCheck(): Promise<void> {
|
||||||
return await NirvanaApi.fetch(`/user/authcheck`, "GET", true);
|
return await NirvanaApi.fetch(`/user/authcheck`, "GET", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function getUserDetails(): Promise<UserDetailsResponse> {
|
||||||
|
return await NirvanaApi.fetch(`/user`, "GET", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ApiCalls = {
|
||||||
|
login,
|
||||||
|
authCheck,
|
||||||
|
getUserDetails,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,100 +1,102 @@
|
|||||||
// import { $authTokens, $searchQuery } from "../../../controller/recoil";
|
import { $authTokens, $searchQuery } from "../../../controller/recoil";
|
||||||
// import { Dropdown, Menu } from "antd";
|
import { Dropdown, Menu } from "antd";
|
||||||
// import Logo, { LogoType } from "../../../components/Logo";
|
import Logo, { LogoType } from "../../../components/Logo";
|
||||||
// import { useRecoilState, useSetRecoilState } from "recoil";
|
import { useRecoilState, useSetRecoilState } from "recoil";
|
||||||
|
|
||||||
// import { GlobalHotKeys } from "react-hotkeys";
|
import { GlobalHotKeys } from "react-hotkeys";
|
||||||
// import { STORE_ITEMS } from "../../../electron/constants";
|
import { STORE_ITEMS } from "../../../electron/constants";
|
||||||
// import SocketChannels from "@nirvana/core/sockets/channels";
|
import SocketChannels from "@nirvana/core/sockets/channels";
|
||||||
// import UserAvatarWithStatus from "../../../components/User/userAvatarWithStatus";
|
import UserAvatarWithStatus from "../../../components/User/userAvatarWithStatus";
|
||||||
// import { UserStatus } from "@nirvana/core/models";
|
import { UserStatus } from "@nirvana/core/models";
|
||||||
// import { socket } from "../../../nirvanaApp";
|
import { socket } from "../../../nirvanaApp";
|
||||||
// // import { useGetUserDetails } from "../../../controller/index";
|
import { useGetUserDetails } from "../../../controller/index";
|
||||||
// import { useRef } from "react";
|
import { useRef } from "react";
|
||||||
|
|
||||||
// export default function Header() {
|
export default function Header() {
|
||||||
// // const { data: user, isLoading } = useGetUserDetails();
|
const { data: userDetailsResponse, isLoading } = useGetUserDetails();
|
||||||
// const [searchQuery, setSearchQuery] = useRecoilState($searchQuery);
|
const [searchQuery, setSearchQuery] = useRecoilState($searchQuery);
|
||||||
|
|
||||||
// const inputRef = useRef(null);
|
const inputRef = useRef(null);
|
||||||
|
|
||||||
// const setAuthTokens = useSetRecoilState($authTokens);
|
const setAuthTokens = useSetRecoilState($authTokens);
|
||||||
|
|
||||||
// if (isLoading) {
|
if (isLoading) {
|
||||||
// return <span>getting data</span>;
|
return <span>getting data</span>;
|
||||||
// }
|
}
|
||||||
|
|
||||||
// const logOut = () => {
|
const logOut = () => {
|
||||||
// window.electronAPI.store.set(STORE_ITEMS.GOOGLE_AUTH_TOKENS, null);
|
window.electronAPI.store.set(STORE_ITEMS.GOOGLE_AUTH_TOKENS, null);
|
||||||
// setAuthTokens(null);
|
setAuthTokens(null);
|
||||||
// };
|
};
|
||||||
|
|
||||||
// const updateStatus = (newStatus: UserStatus) => {
|
const updateStatus = (newStatus: UserStatus) => {
|
||||||
// // send update in socket
|
// send update in socket
|
||||||
// socket.emit(
|
socket.emit(
|
||||||
// SocketChannels.SEND_USER_STATUS_UPDATE,
|
SocketChannels.SEND_USER_STATUS_UPDATE,
|
||||||
// user.googleId,
|
userDetailsResponse.user.status,
|
||||||
// newStatus
|
newStatus
|
||||||
// );
|
);
|
||||||
// };
|
};
|
||||||
|
|
||||||
// const ProfileMenu = (
|
const ProfileMenu = (
|
||||||
// <Menu>
|
<Menu>
|
||||||
// <Menu.Item key="0">
|
<Menu.Item key="0">
|
||||||
// <button onClick={logOut}>Log Out</button>
|
<button onClick={logOut}>Log Out</button>
|
||||||
// </Menu.Item>
|
</Menu.Item>
|
||||||
// <Menu.Item key="1">
|
<Menu.Item key="1">
|
||||||
// {user.status === UserStatus.ONLINE ? (
|
{userDetailsResponse.user.status === UserStatus.ONLINE ? (
|
||||||
// <button onClick={() => updateStatus(UserStatus.OFFLINE)}>
|
<button onClick={() => updateStatus(UserStatus.OFFLINE)}>
|
||||||
// Set status as away
|
Set status as away
|
||||||
// </button>
|
</button>
|
||||||
// ) : (
|
) : (
|
||||||
// <button onClick={() => updateStatus(UserStatus.ONLINE)}>
|
<button onClick={() => updateStatus(UserStatus.ONLINE)}>
|
||||||
// Set status as online
|
Set status as online
|
||||||
// </button>
|
</button>
|
||||||
// )}
|
)}
|
||||||
// </Menu.Item>
|
</Menu.Item>
|
||||||
// </Menu>
|
</Menu>
|
||||||
// );
|
);
|
||||||
|
|
||||||
// // hot keys for selecting search
|
// hot keys for selecting search
|
||||||
// const handleSearch = () => {
|
const handleSearch = () => {
|
||||||
// if (inputRef?.current) {
|
if (inputRef?.current) {
|
||||||
// inputRef?.current?.focus();
|
inputRef?.current?.focus();
|
||||||
// setSearchQuery("");
|
setSearchQuery("");
|
||||||
// }
|
}
|
||||||
// };
|
};
|
||||||
|
|
||||||
// const keyMap = { START_SEARCH: "/" };
|
const keyMap = { START_SEARCH: "/" };
|
||||||
// const handlers = { START_SEARCH: handleSearch };
|
const handlers = { START_SEARCH: handleSearch };
|
||||||
|
|
||||||
// return (
|
return (
|
||||||
// <>
|
<>
|
||||||
// <GlobalHotKeys handlers={handlers} keyMap={keyMap}></GlobalHotKeys>
|
<GlobalHotKeys handlers={handlers} keyMap={keyMap}></GlobalHotKeys>
|
||||||
|
|
||||||
// <div className="flex flex-row items-center bg-zinc-800 h-20 px-5">
|
<div className="flex flex-row items-center bg-zinc-800 h-20 px-5">
|
||||||
// <Logo type={LogoType.small} className="scale-[0.4]" />
|
<Logo type={LogoType.small} className="scale-[0.4]" />
|
||||||
// <input
|
<input
|
||||||
// ref={inputRef}
|
ref={inputRef}
|
||||||
// placeholder="type / to search"
|
placeholder="type / to search"
|
||||||
// className="placeholder:text-zinc-400 bg-transparent outline-none text-zinc-100"
|
className="placeholder:text-zinc-400 bg-transparent outline-none text-zinc-100"
|
||||||
// value={searchQuery}
|
value={searchQuery}
|
||||||
// onChange={(e) => setSearchQuery(e.target.value)}
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
// />
|
/>
|
||||||
|
|
||||||
// <button
|
<button
|
||||||
// onClick={() => updateStatus(UserStatus.FLOW_STATE)}
|
onClick={() => updateStatus(UserStatus.FLOW_STATE)}
|
||||||
// className="ml-auto mr-2 hover:scale-110 bg-zinc-600 text-teal-500 py-1 px-2 rounded-lg text-sm"
|
className="ml-auto mr-2 hover:scale-110 bg-zinc-600 text-teal-500 py-1 px-2 rounded-lg text-sm"
|
||||||
// >
|
>
|
||||||
// flow state
|
flow state
|
||||||
// </button>
|
</button>
|
||||||
|
|
||||||
// <Dropdown overlay={ProfileMenu} trigger={["click"]}>
|
<Dropdown overlay={ProfileMenu} trigger={["click"]}>
|
||||||
// <span className="px-5">
|
<span className="px-5">
|
||||||
// <UserAvatarWithStatus user={user} />
|
{userDetailsResponse?.user && (
|
||||||
// </span>
|
<UserAvatarWithStatus user={userDetailsResponse?.user} />
|
||||||
// </Dropdown>
|
)}
|
||||||
// </div>
|
</span>
|
||||||
// </>
|
</Dropdown>
|
||||||
// );
|
</div>
|
||||||
// }
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import Logo, { LogoType } from "../../components/Logo";
|
|||||||
|
|
||||||
import { $searchQuery } from "../../controller/recoil";
|
import { $searchQuery } from "../../controller/recoil";
|
||||||
import Conversations from "./conversations";
|
import Conversations from "./conversations";
|
||||||
|
import Header from "./header";
|
||||||
// import Header from "./header";
|
// import Header from "./header";
|
||||||
import Search from "./search";
|
import Search from "./search";
|
||||||
// import SelectedConversation from "./selectedConversation";
|
// import SelectedConversation from "./selectedConversation";
|
||||||
|
|||||||
@@ -42,7 +42,9 @@ export default function Login() {
|
|||||||
|
|
||||||
window.electronAPI.store.set(STORE_ITEMS.AUTH_SESSION_JWT, jwtToken);
|
window.electronAPI.store.set(STORE_ITEMS.AUTH_SESSION_JWT, jwtToken);
|
||||||
|
|
||||||
window.location.reload();
|
console.log(loginResponse);
|
||||||
|
|
||||||
|
// window.location.reload();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user