From 9ef9f0d742f55f906820480bfc0ce153a55e6657 Mon Sep 17 00:00:00 2001 From: kyle hoell Date: Mon, 30 Nov 2020 05:25:02 -0500 Subject: [PATCH] fixed some search when using google drive items, made it so if loggout has error it will still send logout cookie token, made it so there is a user update check if the email is not verified --- backend/controllers/user.ts | 1 + backend/express-routers/user.ts | 5 +- backend/middleware/authLogout.ts | 180 ++++++++++++++++++ .../middleware/authNoEmailVerificication.ts | 8 +- backend/utils/userUpdateCheck.ts | 39 ++++ src/actions/auth.js | 7 +- src/actions/files.js | 49 +++-- src/components/Header/index.js | 2 +- src/components/LoginPage/index.js | 44 +++-- 9 files changed, 294 insertions(+), 41 deletions(-) create mode 100644 backend/middleware/authLogout.ts create mode 100644 backend/utils/userUpdateCheck.ts diff --git a/backend/controllers/user.ts b/backend/controllers/user.ts index 505e9dd..35d85d8 100644 --- a/backend/controllers/user.ts +++ b/backend/controllers/user.ts @@ -130,6 +130,7 @@ class UserController { console.log("\nLogout User Route Error:", e.message); const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500; + createLogoutCookie(res); res.status(code).send(); } } diff --git a/backend/express-routers/user.ts b/backend/express-routers/user.ts index d8fb1e2..e758b8d 100644 --- a/backend/express-routers/user.ts +++ b/backend/express-routers/user.ts @@ -3,6 +3,7 @@ import auth from "../middleware/auth"; import authNoEmailVerification from "../middleware/authNoEmailVerificication" import UserController from "../controllers/user"; import authRefresh from "../middleware/authRefresh"; +import authLogout from "../middleware/authLogout"; const userController = new UserController(); @@ -16,9 +17,9 @@ router.get("/user-service/user-detailed", auth, userController.getUserDetailed); router.post("/user-service/login", userController.login); -router.post("/user-service/logout", auth, userController.logout); +router.post("/user-service/logout", authLogout, userController.logout); -router.post("/user-service/logout-all", auth, userController.logoutAll); +router.post("/user-service/logout-all", authLogout, userController.logoutAll); router.post("/user-service/create", userController.createUser); diff --git a/backend/middleware/authLogout.ts b/backend/middleware/authLogout.ts new file mode 100644 index 0000000..e6e1218 --- /dev/null +++ b/backend/middleware/authLogout.ts @@ -0,0 +1,180 @@ +import jwt from "jsonwebtoken"; +import User, {UserInterface} from "../models/user"; +import env from "../enviroment/env"; +import {Request, Response, NextFunction} from "express"; +import { createLogoutCookie } from "../cookies/createCookies"; + +interface RequestType extends Request { + user?: userAccessType, + token?: string, + encryptedToken?: string, +} + +type jwtType = { + iv: Buffer, + user: userAccessType +} + +type userAccessType = { + _id: string, + emailVerified: boolean, + email: string, + botChecked: boolean, +} + +const auth = async(req: RequestType, res: Response, next: NextFunction) => { + + try { + + console.log("\nAUTH NO EMAIL"); + + const accessToken = req.cookies["access-token"]; + + if (!accessToken) throw new Error("No Access Token"); + + const decoded = jwt.verify(accessToken, env.passwordAccess!) as jwtType; + + const user = decoded.user; + + if (!user) throw new Error("No User"); + + req.user = user; + + next(); + + } catch (e) { + console.log("\nAuthorization Middleware No Email Verifiaction Error:", e.message); + createLogoutCookie(res); + return res.status(401).send("Error Authenticating"); + } +} + +export default auth; + + +// import jwt from "jsonwebtoken"; +// import User, {UserInterface} from "../models/user"; +// import env from "../enviroment/env"; +// import {Request, Response, NextFunction} from "express"; + +// interface RequestType extends Request { +// user?: UserInterface, +// token?: string, +// encryptedToken?: string, +// } + +// type jwtType = { +// iv: Buffer, +// _id: string, +// } + +// const auth = async(req: RequestType, res: Response, next: NextFunction) => { + +// try { + +// const token = req.header("Authorization")!.replace("Bearer ", ""); + +// const decoded = jwt.verify(token, env.passwordAccess!) as jwtType; + +// const iv = decoded.iv; + +// const user = await User.findOne({_id: decoded._id}) as UserInterface; +// const encrpytionKey = user.getEncryptionKey(); + +// const encryptedToken = user.encryptToken(token, encrpytionKey, iv); + +// let tokenFound = false; +// for (let i = 0; i < user.tokens.length; i++) { + +// const currentToken = user.tokens[i].token; + +// if (currentToken === encryptedToken) { +// tokenFound = true; +// break; +// } +// } + +// if (!user || !tokenFound) { + +// throw new Error("User not found") + +// } else { +// req.token = token; +// req.encryptedToken = encryptedToken +// req.user = user; +// next(); +// } + +// } catch (e) { +// console.log(e); +// res.status(401).send({error: "Error Authenticating"}) +// } +// } + +// export default auth; + + + + + + +// import jwt from "jsonwebtoken"; +// import User, {UserInterface} from "../models/user"; +// import env from "../enviroment/env"; +// import {Request, Response, NextFunction} from "express"; + +// interface RequestType extends Request { +// user?: UserInterface, +// token?: string, +// encryptedToken?: string, +// } + +// type jwtType = { +// iv: Buffer, +// _id: string, +// } + +// const auth = async(req: RequestType, res: Response, next: NextFunction) => { + +// try { + +// const token = req.header("Authorization")!.replace("Bearer ", ""); + +// const decoded = jwt.verify(token, env.passwordAccess!) as jwtType; + +// const iv = decoded.iv; + +// const user = await User.findOne({_id: decoded._id}) as UserInterface; +// const encrpytionKey = user.getEncryptionKey(); + +// const encryptedToken = user.encryptToken(token, encrpytionKey, iv); + +// let tokenFound = false; +// for (let i = 0; i < user.tokens.length; i++) { + +// const currentToken = user.tokens[i].token; + +// if (currentToken === encryptedToken) { +// tokenFound = true; +// break; +// } +// } + +// if (!user || !tokenFound) { + +// throw new Error("User not found") + +// } else { +// req.token = token; +// req.encryptedToken = encryptedToken +// req.user = user; +// next(); +// } + +// } catch (e) { +// console.log(e); +// res.status(401).send({error: "Error Authenticating"}) +// } +// } + +// export default auth; \ No newline at end of file diff --git a/backend/middleware/authNoEmailVerificication.ts b/backend/middleware/authNoEmailVerificication.ts index 953fed5..51eb961 100644 --- a/backend/middleware/authNoEmailVerificication.ts +++ b/backend/middleware/authNoEmailVerificication.ts @@ -2,6 +2,7 @@ import jwt from "jsonwebtoken"; import User, {UserInterface} from "../models/user"; import env from "../enviroment/env"; import {Request, Response, NextFunction} from "express"; +import userUpdateCheck from "../utils/userUpdateCheck"; interface RequestType extends Request { user?: userAccessType, @@ -33,10 +34,15 @@ const auth = async(req: RequestType, res: Response, next: NextFunction) => { const decoded = jwt.verify(accessToken, env.passwordAccess!) as jwtType; - const user = decoded.user; + let user = decoded.user; if (!user) throw new Error("No User"); + if (!user.emailVerified) { + const ipAddress = req.clientIp; + user = await userUpdateCheck(res, user._id, ipAddress); + } + req.user = user; next(); diff --git a/backend/utils/userUpdateCheck.ts b/backend/utils/userUpdateCheck.ts new file mode 100644 index 0000000..d55fd25 --- /dev/null +++ b/backend/utils/userUpdateCheck.ts @@ -0,0 +1,39 @@ +import User, {UserInterface} from "../models/user"; + +import {Request, Response, NextFunction} from "express"; +import NotFoundError from "./NotFoundError"; +import { createLoginCookie } from "../cookies/createCookies"; + +// interface RequestType extends Request { +// user?: userAccessType, +// token?: string, +// encryptedToken?: string, +// } + +type userAccessType = { + _id: string, + emailVerified: boolean, + email: string, + botChecked: boolean, +} + +const userUpdateCheck = async(res: Response, id: string, ipAddress: string | undefined) => { + + console.log("Loading full user for email verification check"); + + const updatedUser = await User.findById(id); + + if (!updatedUser) throw new NotFoundError("Cannot find updated user auth"); + + if (updatedUser.emailVerified) { + + const {accessToken, refreshToken} = await updatedUser.generateAuthToken(ipAddress); + createLoginCookie(res, accessToken, refreshToken); + } + + let strippedUser: userAccessType = {_id: updatedUser._id, emailVerified: updatedUser.emailVerified!, email: updatedUser.email, botChecked: false} + + return strippedUser; +} + +export default userUpdateCheck; \ No newline at end of file diff --git a/src/actions/auth.js b/src/actions/auth.js index c905b96..cc10751 100755 --- a/src/actions/auth.js +++ b/src/actions/auth.js @@ -22,9 +22,8 @@ export const startLogin = (email, password, currentRoute) => { axios.post("/user-service/login", dt).then((response) => { - console.log("USER SERVICE LOGIN RESPONSE") + // console.log("USER SERVICE LOGIN RESPONSE") - const token = response.data.token; const id = response.data.user._id; const emailVerified = response.data.user.emailVerified; @@ -34,7 +33,9 @@ export const startLogin = (email, password, currentRoute) => { env.emailAddress = response.data.user.email; env.name = response.data.user.name || "" - window.localStorage.setItem("token", token); + //window.localStorage.setItem("token", token); + + console.log("USER SERVICE LOGIN RESPONSE", response.data.user); if (emailVerified) { diff --git a/src/actions/files.js b/src/actions/files.js index 577425d..55ea36d 100644 --- a/src/actions/files.js +++ b/src/actions/files.js @@ -55,6 +55,8 @@ export const startSetFileAndFolderItems = (historyKey, parent="/", sortby="DEFAU return; } + + //isGoogle = env.googleDriveEnabled; let limit = window.localStorage.getItem("list-size") || 50 limit = parseInt(limit); @@ -67,30 +69,39 @@ export const startSetFileAndFolderItems = (historyKey, parent="/", sortby="DEFAU //fileURL = console.log("Searching"); - if (storageType === "stripe") { + // if (storageType === "stripe") { - console.log("Pied Search") + // console.log("Pied Search") - fileURL = `/file-service/list?search=${search}&storageType=${storageType}`; - folderURL = `/folder-service/list?search=${search}&storageType=${storageType}` - } else if (folderSearch) { + // fileURL = `/file-service/list?search=${search}&storageType=${storageType}`; + // folderURL = `/folder-service/list?search=${search}&storageType=${storageType}` + // if (folderSearch) { - console.log("Folder Search") + // console.log("Folder Search") - fileURL = `/file-service/list?search=${search}&folder_search=${true}&parent=${parent}` - folderURL = `/folder-service/list?search=${search}&folder_search=${true}&parent=${parent}` + // fileURL = `/file-service/list?search=${search}&folder_search=${true}&parent=${parent}` + // folderURL = `/folder-service/list?search=${search}&folder_search=${true}&parent=${parent}` - } else { + // } else { - console.log("Everywhere Search") + // console.log("Everywhere Search") - if (env.googleDriveEnabled) { - fileURL = `/file-service-google-mongo/list?search=${search}`; - folderURL = `/folder-service-google-mongo/list?search=${search}`; - } else { - fileURL = `/file-service/list?search=${search}`; - folderURL = `/folder-service/list?search=${search}`; - } + // if (env.googleDriveEnabled) { + // fileURL = `/file-service-google-mongo/list?search=${search}`; + // folderURL = `/folder-service-google-mongo/list?search=${search}`; + // } else { + // fileURL = `/file-service/list?search=${search}`; + // folderURL = `/folder-service/list?search=${search}`; + // } + // } + + + if (env.googleDriveEnabled) { + fileURL = `/file-service-google-mongo/list?search=${search}`; + folderURL = `/folder-service-google-mongo/list?search=${search}`; + } else { + fileURL = `/file-service/list?search=${search}`; + folderURL = `/folder-service/list?search=${search}`; } @@ -142,6 +153,8 @@ export const startSetAllItems = (clearCache, parent="/", sortby="DEFAULT", searc if (clearCache) cachedResults = {}; + //isGoogle = env.googleDriveEnabled; + if (cachedResults[parent]) { const {fileList, folderList, quickItemList} = cachedResults[parent]; @@ -224,7 +237,7 @@ export const startSetFiles = (parent="/", sortby="DEFAULT", search="", isGoogle= console.log("Fetching file list"); - if (isGoogle) { + if (env.googleDriveEnabled) { console.log("is google") diff --git a/src/components/Header/index.js b/src/components/Header/index.js index 7ad1ab6..f476b3f 100644 --- a/src/components/Header/index.js +++ b/src/components/Header/index.js @@ -146,7 +146,7 @@ class HeaderContainer extends React.Component { const parent = this.props.parent; - history.push(`/search/${this.searchValue}?parent=${parent}&folder_search=true&storageType=stripe`) + history.push(`/search/${this.searchValue}?parent=${parent}&folder_search=true`) this.searchValue = '' diff --git a/src/components/LoginPage/index.js b/src/components/LoginPage/index.js index b98dba9..768a3c9 100644 --- a/src/components/LoginPage/index.js +++ b/src/components/LoginPage/index.js @@ -61,7 +61,7 @@ class LoginPageContainer extends React.Component { Swal.fire( 'Check your email', - 'If the email address matches any in our database, we’ll send you an email with instructions on how to reset your password. \nIf you still have problems accessing your account, please send an email to support@piedpiperapp.com', + 'If the email address matches any in our database, we’ll send you an email with instructions on how to reset your password.', 'success' ) @@ -190,24 +190,36 @@ class LoginPageContainer extends React.Component { logout = () => { - window.localStorage.removeItem("token"); + // window.localStorage.removeItem("token"); - this.props.dispatch(setLoginFailed(false)) + axios.post("/user-service/logout").then((response) => { - this.setState(() => { - return { - ...this.state, - value: undefined, - loginMode: true, - email: "", - password: "", - verifyPassword: "", - resetPasswordMode: false, - verifyEmailResent: false, - verifyEmailResentTimer: 0, - verifyEmailResentTimerStarted: false - } + console.log("user logged out verify email"); + + //this.props.dispatch(setLoginFailed(false)) + + window.location.reload(); + + // this.setState(() => { + // return { + // ...this.state, + // value: undefined, + // loginMode: true, + // email: "", + // password: "", + // verifyPassword: "", + // resetPasswordMode: false, + // verifyEmailResent: false, + // verifyEmailResentTimer: 0, + // verifyEmailResentTimerStarted: false, + // } + // }) + + }).catch((e) => { + window.location.reload(); + console.log("Cannot logout user verify email"); }) + } componentDidMount = () => {