Skip to content

Commit

Permalink
Merge pull request #17 from SLIIT-Y4S2/oauth
Browse files Browse the repository at this point in the history
Implemented OAuth
  • Loading branch information
it21109126 committed Sep 26, 2024
2 parents 922780f + adb3854 commit 37572cb
Show file tree
Hide file tree
Showing 13 changed files with 460 additions and 1,553 deletions.
121 changes: 84 additions & 37 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 13 additions & 3 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,25 @@
"react-apexcharts": "^1.4.1",
"react-bootstrap": "^2.10.5",
"react-chartjs-2": "^5.2.0",
"js-cookie": "^3.0.5",
"jspdf": "^2.5.1",
"jspdf-autotable": "^3.5.25",
"moment": "^2.29.4",
"react": "^18.2.0",
"react-apexcharts": "^1.4.0",
"react-bootstrap": "^2.5.0",
"react-chartjs-2": "^4.3.1",
"react-confirm-alert": "^3.0.6",
"react-credit-cards": "^0.8.3",
"react-dom": "^18.3.1",
"react-icons": "^5.3.0",
"react-router-dom": "^6.26.2",
"react-scripts": "^5.0.1",
"react-toastify": "^10.0.5",
"recharts": "^2.12.7",
"web-vitals": "^4.2.3"
"react-toastify": "^9.1.1",
"recharts": "^2.1.16",
"validator": "^13.7.0",
"web-vitals": "^2.1.4",
"xss": "^1.0.15"
},
"scripts": {
"start": "react-scripts start",
Expand Down
Binary file added client/public/assets/dashboard/img/google.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 13 additions & 1 deletion client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,18 @@ import ProductStatsPage from "./pages/dashboard/machineManagement/ProductStatsPa
import ReportsPage from "./pages/dashboard/machineManagement/ReportsPage";
import MachineReportPage from "./pages/dashboard/machineManagement/MachineReportPage";
import FactoryOverviewPage from "./pages/dashboard/factoryManagement/OverviewFactoryPage";

import GoogleOAuth from './pages/auth/GoogleOAuth.js';
import Cookies from 'js-cookie';

function App() {
if(Cookies.get("cookie-session-user")){
localStorage.setItem('user', Cookies.get("cookie-session-user"));
Cookies.remove("cookie-session-user");
}
if(!Cookies.get("cookie-session") && JSON.parse(localStorage.getItem('user'))?.hasOwnProperty('authType')){
localStorage.removeItem('user');
}

return(
<BrowserRouter basename={process.env.PUBLIC_URL}>
<ToastContainer/>
Expand All @@ -130,6 +139,9 @@ function App() {
<Route path="/emp-login-redirect" element={<EmpLoginRedirect />}/>
<Route path="/emp-account-redirect" element={<EmpAccountRedirect />}/>

{/* Google OAuth Routes */}
<Route path="/auth/google" element={<GoogleOAuth />} />

<Route path="/login" element={!localStorage.getItem('user')? <LoginPage />:<Navigate to='/account-redirect'/>}/>
<Route path="/signup" element={!localStorage.getItem('user')? <RegisterPage />:<Navigate to='/account-redirect'/>}/>
<Route path="/account" element={localStorage.getItem('user')? <AccountPage />:<Navigate to='/login-redirect'/>}/>
Expand Down
7 changes: 7 additions & 0 deletions client/src/components/auth/LoginComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ function LoginComponent() {
value={password} onChange={(e)=>setPassword(e.target.value)}/>
<div className="btn-wrapper mt-0">
<button disabled={isLoading} className="theme-btn-1 btn btn-block" type="submit">SIGN IN</button>
<br/><br/>
<center><p>OR</p></center>
<Link to="/auth/google" className="google-signin-btn">
<button disabled={isLoading} className="btn btn-block" type="button" style={{ border: '1px solid #ccc', boxShadow: '2px 2px 5px rgba(0, 0, 0, 0.1)' }}>
<img height={50} width={150} src={`../../assets/dashboard/img/google.png`} alt="Google" className="google-icon" />
</button>
</Link>
</div>
<div className="go-to-btn mt-20">

Expand Down
6 changes: 6 additions & 0 deletions client/src/hooks/useLogout.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useAuthContext } from "./useAuthContext"
import Cookies from 'js-cookie'

export const useLogout = () => {
const {dispatch} = useAuthContext()
Expand All @@ -7,6 +8,11 @@ export const useLogout = () => {
// remove user from storage
localStorage.removeItem('user')

// remove user-session cookie
if (Cookies.get("cookie-session")) {
Cookies.remove("cookie-session");
}

// dispatch logout action
dispatch({type: 'LOGOUT'})
}
Expand Down
6 changes: 6 additions & 0 deletions client/src/pages/auth/GoogleOAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
function GoogleOAuth() {
window.location.href = 'http://localhost:5000/auth/google';
return null;
}

export default GoogleOAuth;
62 changes: 58 additions & 4 deletions server/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,41 @@ const createUser = async (req, res) => {

}

// create new user for google oauth process
let plainPassword;
const createGoogleUser = async (user) => {
let returnedUser;

const existingUsers = await User.find();
const existingUser = (await Promise.all(existingUsers.map(async (existingUser) => {
const isExists = await bcrypt.compare(user.password, existingUser.password);
return isExists ? existingUser : null;
}))).find(user => user !== null);

if (!existingUser) {
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(user.password, salt)
const newUser = await new User({...user, password: hash}).save();
returnedUser = newUser;
console.info("User saved");
} else {
returnedUser = existingUser;
console.info("User already exists");
}

// Add plainPassword property to returnedUser
returnedUser = returnedUser.toObject();
plainPassword = user.password;
return {...returnedUser, plainPassword};
};


const getGoogleUserById = async (id) => {
let user = (await User.findById(id));
user = user.toObject();
return {...user, plainPassword};
};

// delete a user
const deleteUser = async (req, res) => {
const { id } = req.params
Expand Down Expand Up @@ -240,16 +275,33 @@ const updateUser = async (req, res) => {

// login
const loginUser = async (req, res) => {
const { email, password } = req.body
let email = null;
let password = null;
let plainPassword = null;
let user = null;

try {
const user = await User.login(email, password)
if(req.user){
email = req.user.email;
plainPassword = req.user.plainPassword;
user = await User.login(email, plainPassword)
} else {
email = req.body.email;
password = req.body.password;

user = await User.login(email, password)
}

// create a token
const token = createToken(user._id)
const id = user._id

res.status(200).json({ id, email, token })
if(req.user){
res.cookie('cookie-session-user', JSON.stringify({ id, email, token, authType: "google" }));
res.redirect("http://localhost:3000/account");
}else{
res.status(200).json({ id, email, token })
}
} catch (error) {
res.status(400).json({ error: error.message })
}
Expand Down Expand Up @@ -365,5 +417,7 @@ module.exports = {
signupUser,
resetPassword,
adminResetPassword,
getAccountUsage
getAccountUsage,
createGoogleUser,
getGoogleUserById
}
Loading

0 comments on commit 37572cb

Please sign in to comment.