Skip to content

Commit

Permalink
Merge pull request #26 from michacurri/updateProfileFeature
Browse files Browse the repository at this point in the history
Update profile feature
  • Loading branch information
michacurri authored Jan 5, 2021
2 parents 035d0d2 + 087fd98 commit 41f4820
Show file tree
Hide file tree
Showing 13 changed files with 148 additions and 146 deletions.
1 change: 0 additions & 1 deletion api/controllers/profileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ module.exports = {
const profileRes = await Profile.findOne({ email })
.populate("workorders")
.exec();
// console.log(`"profileRes.workorders": ${profileRes.workorders}`);
return profileRes;
} catch (err) {
throw err;
Expand Down
1 change: 1 addition & 0 deletions api/middleware/verifyToken.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { verifyToken } = require("../tokens/tokenService");

exports.verifyToken = async (req, res, next) => {
console.log(req.cookies);
const { cookies } = req;
try {
if (!cookies || !cookies.token) {
Expand Down
2 changes: 1 addition & 1 deletion api/routes/profileRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ router
.use(verifyToken)
.route("/this-profile")
.get(async (req, res) => {
console.log(`/this-profile: ${req.profile.id}`);
// console.log(`/this-profile: ${req.profile.id}`);
try {
const profile = await findProfileById(req.profile.id);
res.json({ data: profile });
Expand Down
2 changes: 1 addition & 1 deletion api/routes/workorderRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ router.get("/", async (req, res) => {
// router.post("/create/:userId", async (req, res) => {

router
// .use(verifyToken)
.use(verifyToken)
.route("/create/:userId")
.post(async (req, res) => {
const { brand, model, colour } = req.body;
Expand Down
4 changes: 1 addition & 3 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@ const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");

const DB_URI = process.env.DB_URI || "mongodb://localhost:27017/aero";
// const DB_URI = "mongodb://localhost:27017/aero";
const PORT = process.env.PORT || 5000;
// const PORT = 5000;

app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
cors({
// origin: `https://aero-workorder-management.herokuapp.com`,
origin: "http://localhost:3000/" || "https://aero-workorder-management.herokuapp.com",
credentials: true,
exposedHeaders: ["Set-Cookie"],
allowedHeaders: ["Content-Type", "Authorization"],
Expand Down
110 changes: 82 additions & 28 deletions src/backend/authorization/AuthContainer.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,95 @@
import React, { useContext, useCallback } from "react";
import { UserContext } from "./UserContext";
import { ImpersonatorContext } from "./ImpersonatorContext";
import AuthLoginSignup from "./AuthLoginSignup";
import React, { Fragment, useContext, useCallback, useState } from "react";
import { Link, Switch, Route, Redirect } from "react-router-dom";
import ProfileCreate from "../../components/root/ProfileCreate";
import Field from "../../components/root/Field";
// import { UserContext } from "./UserContext";
// import { ImpersonatorContext } from "./ImpersonatorContext";
// import AuthLoginSignup from "./AuthLoginSignup";

const AuthContainer = () => {
const [currentUser, setCurrentUser] = useContext(UserContext);
const [impersonator, setImpersonator] = useContext(ImpersonatorContext);
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
};

const AuthContainer = ({loadUserProfile}) => {
// const [currentUser, setCurrentUser] = useContext(UserContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [link, setLink] = useState("signup");
// const [impersonator, setImpersonator] = useContext(ImpersonatorContext);

//* const loadImpersonator = useCallback(() => {
// setTimeout(() => {
// setImpersonator(undefined);
// }, [3000]);
// }, [setImpersonator]);

const loadUserProfile = useCallback(
async function () {
try {
const response = await fetch("/api/profile/this-profile", {
headers: {
credentials: "include",
},
});
const json = await response.json();
if (!response.ok) {
throw new Error(json.message);
}
setCurrentUser(json.data);
} catch (err) {
console.log(err);
setCurrentUser(undefined);
const changeLink = () => {
if (link === "signup") {
setLink("login");
} else {
setLink("signup");
}
};


const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch("/api/profile/login", {
method: "POST",
headers: headers,
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message);
}
},
[setCurrentUser]
);
loadUserProfile();
} catch (err) {
setError(err.message);
}
};

return (
<AuthLoginSignup loadUserProfile={loadUserProfile}
/>
<Fragment>
<Redirect to="/login" />
<Switch>
<Route path="/login">
<div className="auth__loginForm">
<form onSubmit={handleSubmit} noValidate>
<Field
id="email"
label="Email Address"
name="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<Field
name="password"
label="Password"
id="password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<button type="submit">Login</button>
</form>
</div>
</Route>
<Route path="/signup">
<ProfileCreate changeLink={changeLink} />
</Route>
</Switch>
{/* prettier-ignore */}
<nav><ul>
<li><Link to={`${link}`} onClick={changeLink}>{`${link}`}</Link></li>
</ul></nav>
</Fragment>
);
};

Expand Down
84 changes: 0 additions & 84 deletions src/backend/authorization/AuthLoginSignup.js

This file was deleted.

5 changes: 2 additions & 3 deletions src/components/admin/WorkorderCreate.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { Fragment, useState } from "react";
import WorkorderEditor from "../root/WorkorderEditor";

const WorkorderAdd = ({ currentProfile }) => {
const WorkorderAdd = ({ currentProfile, loadUserProfile }) => {
const [workorder, setWorkorder] = useState();

const updateWorkorderField = (e) => {
Expand All @@ -21,8 +21,7 @@ const WorkorderAdd = ({ currentProfile }) => {
body: JSON.stringify({ brand, model, colour }),
});
if (response.ok) {
// props.onAdd();
console.log(response);
loadUserProfile()
} else {
console.log("Error saving record");
}
Expand Down
41 changes: 36 additions & 5 deletions src/components/root/MainContentSection.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useContext, Fragment } from "react";
import React, { useContext, Fragment, useCallback } from "react";
import { UserContext } from "../../backend/authorization/UserContext";
import { ImpersonatorContext } from "../../backend/authorization/ImpersonatorContext";
import { Redirect, Route, Switch } from "react-router-dom";
import Home from "./Home";
import SidebarNav from "./SidebarNav";
Expand All @@ -10,7 +11,37 @@ import AdvertHero from "./AdvertHero";
import AuthContainer from "../../backend/authorization/AuthContainer";

function MainContentSection({ loginClick }) {
const [currentProfile] = useContext(UserContext);
const [admin, setAdmin] = useContext(ImpersonatorContext);
const [currentProfile, setCurrentProfile] = useContext(UserContext);



const loadUserProfile = useCallback(
async function () {
try {
const response = await fetch("/api/profile/this-profile", {
headers: {
credentials: "include",
},
});
const json = await response.json();
if (!response.ok) {
throw new Error(json.message);
}
setCurrentProfile(json.data);
} catch (err) {
console.log(err);
setCurrentProfile(undefined);
}
},
[setCurrentProfile]
);

// function loadUserProfile() {

// const prevWorkorders = currentProfile.workorders;
// console.log(`prev: ${prevWorkorders} & new: ${workorders}`);
// }

let content;
if (loginClick) {
Expand All @@ -26,16 +57,16 @@ function MainContentSection({ loginClick }) {
{/* prettier-ignore */}
<Switch>
<Route path="/home" render={() => <Home />} />
<Route path="/profile" render={() => <Profile currentProfile={currentProfile} />} />
<Route path="/workorder" render={() => <Workorder />} />
<Route path="/profile" render={() => <Profile admin={admin} currentProfile={currentProfile} />} />
<Route path="/workorder" render={() => <Workorder currentProfile={currentProfile} loadUserProfile={loadUserProfile} />} />
<Route path="/settings" render={() => <Settings />} />
</Switch>
</div>
</section>
</div>
);
} else {
content = <AuthContainer />;
content = <AuthContainer loadUserProfile={loadUserProfile} />;
}
} else {
content = (
Expand Down
17 changes: 5 additions & 12 deletions src/components/root/Profile.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import React, { useContext, useState, Fragment } from "react";
import React, { useState, Fragment } from "react";
import ProfileDisplay from "./ProfileDisplay";
import ProfileCreate from './ProfileCreate';
import ProfileSearch from './ProfilesSearch'
import { ImpersonatorContext } from "../../backend/authorization/ImpersonatorContext";
import { UserContext } from "../../backend/authorization/UserContext";
import ProfileCreate from "./ProfileCreate";
import ProfileSearch from "./ProfilesSearch";

// _______ Profile
// Return two buttons that control whether to Sign In or Sign Up or add
// On Login check if currentProfile exists in DB
// TODO - IF user is ADMIN show everything

const Profile = () => {
const [admin] = useContext(ImpersonatorContext);
const [currentProfile, setCurrentProfile] = useContext(UserContext);
const Profile = ({ admin, currentProfile, setCurrentProfile }) => {
const [searchOrAdd, setSearchOrAdd] = useState(null);

const searchProfiles = () => {
Expand All @@ -38,10 +34,7 @@ const Profile = () => {
</div>
) : (
<div className="profile__addBox">
<ProfileCreate
currentProfile={currentProfile}
setCurrentProfile={setCurrentProfile}
/>
<ProfileCreate />
</div>
)}
</Fragment>
Expand Down
4 changes: 3 additions & 1 deletion src/components/root/ProfileCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { useState } from "react";
import ContactEditor from "./ContactEditor";
import { useHistory } from "react-router-dom";

const headers = { "Content-Type": "application/json" };

function ProfileCreate({ changeLink }) {
const [contact, setContact] = useState();
const history = useHistory();
Expand All @@ -22,7 +24,7 @@ function ProfileCreate({ changeLink }) {
try {
const response = await fetch("/api/profile/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: headers,
body: JSON.stringify(contact),
});
const data = await response.json();
Expand Down
Loading

0 comments on commit 41f4820

Please sign in to comment.