Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

auth #331

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

auth #331

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7,044 changes: 1,880 additions & 5,164 deletions client/package-lock.json

Large diffs are not rendered by default.

35 changes: 18 additions & 17 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,39 +15,40 @@
"@fortawesome/free-brands-svg-icons": "^6.5.2",
"@fortawesome/free-solid-svg-icons": "^6.5.2",
"@fortawesome/react-fontawesome": "^0.2.2",
"@headlessui/react": "^1.7.15",
"@mui/icons-material": "^5.15.18",
"@mui/material": "^5.15.18",
"@headlessui/react": "^1.7.19",
"@mui/icons-material": "^5.15.21",
"@mui/material": "^5.15.21",
"@mui/styled-engine-sc": "^6.0.0-alpha.18",
"@reduxjs/toolkit": "^1.9.5",
"axios": "^1.4.0",
"@reduxjs/toolkit": "^1.9.7",
"axios": "^1.7.2",
"firebase": "^10.12.3",
"html2canvas": "^1.4.1",
"html2pdf": "^0.0.11",
"html2pdf.js": "^0.10.1",
"html2pdf.js": "^0.10.2",
"jspdf": "^2.5.1",
"lottie-react": "^2.4.0",
"moment": "^2.29.4",
"moment": "^2.30.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.45.1",
"react-icons": "^4.10.1",
"react-redux": "^8.1.1",
"react-router-dom": "^6.14.1",
"react-hook-form": "^7.52.1",
"react-icons": "^4.12.0",
"react-redux": "^8.1.3",
"react-router-dom": "^6.24.1",
"styled-components": "^6.1.11",
"vite-plugin-commonjs": "^0.10.1"
},
"devDependencies": {
"@types/react": "^18.2.14",
"@types/react-dom": "^18.2.6",
"@vitejs/plugin-react": "^4.0.1",
"autoprefixer": "^10.4.14",
"eslint": "^8.44.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.19",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.1",
"postcss": "^8.4.26",
"tailwindcss": "^3.3.3",
"vite": "^4.4.0",
"postcss": "^8.4.39",
"tailwindcss": "^3.4.4",
"vite": "^4.5.3",
"vite-plugin-svgr": "^4.2.0"
}
}
3 changes: 2 additions & 1 deletion client/src/components/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { CiLocationOn } from "react-icons/ci";
import CustomButton from "./CustomButton";
import { popularSearch } from "../utils/data";
import { HeroImage } from "../assets";

import OAuth from "./OAuth";
const SearchInput = ({ placeholder, icon, value, setValue, styles }) => {
const handleChange = (e) => {
setValue(e.target.value);
Expand Down Expand Up @@ -77,6 +77,7 @@ const Header = ({
}
/>
</div>

</div>

{type && (
Expand Down
2 changes: 2 additions & 0 deletions client/src/components/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Link } from "react-router-dom";
import CustomButton from "./CustomButton";
import { useSelector } from "react-redux";
import DarkMode from "./DarkMode/DarkMode.jsx";
import OAuth from "./OAuth.jsx";

function MenuList({ user, onClick }) {
const handleLogout = () => {};
Expand Down Expand Up @@ -145,6 +146,7 @@ const Navbar = () => {
)}
</div>
<DarkMode/>
<OAuth/>
<button
className="block lg:hidden text-slate-900"
onClick={() => setIsOpen((prev) => !prev)}
Expand Down
45 changes: 45 additions & 0 deletions client/src/components/OAuth.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { GoogleAuthProvider, getAuth, signInWithPopup } from 'firebase/auth';
import { app } from '../firebase';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { Login } from '../redux/userSlice';

export default function OAuth() {
const navigate = useNavigate();
const dispatch = useDispatch();
const handleGoogleClick = async () => {
try {
const provider = new GoogleAuthProvider();
const auth = getAuth(app);

const result = await signInWithPopup(auth, provider);

const res = await fetch('http://localhost:3000/api/auth/google', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: result.user.displayName,
email: result.user.email,
photo: result.user.photoURL,
}),
});
const data = await res.json();
dispatch(Login(data));
console.log(data);

} catch (error) {
console.log('could not sign in with google', error);
}
};
return (
<button
onClick={handleGoogleClick}
type='button'
className='bg-red-700 text-white p-3 rounded-lg uppercase hover:opacity-95'
>
Continue with google
</button>
);
}
2 changes: 2 additions & 0 deletions client/src/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import JobCard from "./JobCard";
import Loading from "./Loading";
import CompanyCard from "./CompanyCard";
import JobTypes from "./JobTypes";
import OAuth from "./OAuth";

export {
Navbar,
Footer,
CustomButton,
TextInput,
SignUp,
OAuth,
Header,
ListBox,
JobCard,
Expand Down
21 changes: 21 additions & 0 deletions client/src/firebase.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: import.meta.env.FIREBASE_KEY,
authDomain: "kamado-af94e.firebaseapp.com",
projectId: "kamado-af94e",
storageBucket: "kamado-af94e.appspot.com",
messagingSenderId: "543339757225",
appId: "1:543339757225:web:8bd4bc072448b6bbb9b3b8",
measurementId: "G-NYV8TJMJWN"
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
8 changes: 4 additions & 4 deletions client/src/pages/Auth.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ const Auth = () => {
const [open, setOpen] = useState(true);
const location = useLocation();

let from = location?.state?.from?.pathname || "/";
// let from = location?.state?.from?.pathname || "/";

if (user.token) {
return window.location.replace(from);
}
// if (user.token) {
// return window.location.replace(from);
// }
return (
<div className='w-full '>
<img src={Office} alt='Office' className='object-contain ' />
Expand Down
6 changes: 3 additions & 3 deletions client/src/redux/rootReducer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { combineReducers } from "@reduxjs/toolkit";
import userSlice from "./userSlice";
import userReducer from "./userSlice";

const rootReducer = combineReducers({
user: userSlice,
user: userReducer,
});

export { rootReducer };
export default rootReducer;
2 changes: 1 addition & 1 deletion client/src/redux/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
useDispatch as useAppDispatch,
useSelector as useAppSelector,
} from "react-redux";
import { rootReducer } from "./rootReducer";
import rootReducer from "./rootReducer";

const store = configureStore({
reducer: rootReducer,
Expand Down
19 changes: 8 additions & 11 deletions client/src/redux/userSlice.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createSlice } from "@reduxjs/toolkit";
import { dispatch } from "./store";
import { users } from "../utils/data";

const initialState = {
Expand All @@ -20,16 +19,14 @@ const userSlice = createSlice({
},
});

export const { login, logout } = userSlice.actions;

export default userSlice.reducer;

export function Login(user) {
return (dispatch, getState) => {
dispatch(userSlice.actions.login(user));
};
}
export const Login = (user) => (dispatch) => {
dispatch(login(user));
};

export function Logout() {
return (dispatch, getState) => {
dispatch(userSlice.actions.logout());
};
}
export const Logout = () => (dispatch) => {
dispatch(logout());
};
3 changes: 3 additions & 0 deletions client/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export default defineConfig({
plugins: [
react(),
],
define:{
'process.env.FIREBASE_KEY':JSON.stringify(process.env.FIREBASE_KEY)
},
build: {
chunkSizeWarningLimit: 1000, // Increase chunk size warning limit to 1000 kB
rollupOptions: {
Expand Down
33 changes: 33 additions & 0 deletions server/controller/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import User from '../models/userModel.js';
import bcryptjs from 'bcryptjs';
import jwt from 'jsonwebtoken';
export const google = async (req, res, next) => {
try {
const user = await User({ email: req.body.email });
if (user) {
const token = jwt.sign({ id: user._id }, "secret");
const { password: pass, ...rest } = user._doc;
res.status(200).json({ ...rest, token });
} else {
const generatedPassword =
Math.random().toString(36).slice(-8) +
Math.random().toString(36).slice(-8);
const hashedPassword = bcryptjs.hashSync(generatedPassword, 10);
const newUser = new User({
username:
req.body.name.split(' ').join('').toLowerCase() +
Math.random().toString(36).slice(-4),
email: req.body.email,
password: hashedPassword,
avatar: req.body.photo,
});
await newUser.save();
const token = jwt.sign({ id: newUser._id }, "secret");
const { password: pass, ...rest } = newUser._doc;
res.status(200).json({ ...rest, token });
}
} catch (error) {
next(error);
}
};

12 changes: 9 additions & 3 deletions server/dbConfig/dbConnection.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import mongoose from "mongoose";

import dotenv from "dotenv";
dotenv.config();
const dbConnection = async () => {
try {
const dbConnection = await mongoose.connect(process.env.MONGODB_URL);
const conn = await mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
serverSelectionTimeoutMS: 5000, // Timeout after 5s instead of 30s
});
console.log("Database connected successfully");


} catch (error) {
console.log('MongoConnection Failed !!' + error );
console.log('MongoConnection Failed !!' + error )
}
}

Expand Down
30 changes: 20 additions & 10 deletions server/models/userModel.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,42 @@
import mongoose from "mongoose";
import validator from "validator";
import bcrypt from "bcryptjs";
import JWT from "jsonwebtoken"
import mongoose, { mongo } from "mongoose";


const userSchema = new mongoose.Schema({
firstName:{
type:String,
required :[true, "First Name is required"]
// required :[true, "First Name is required"]
},
lastName:{
type:String,
required :[true, "Last Name is required"]
// required :[true, "Last Name is required"]
},
username:{
type: String,
require: true,
unique: true,
},
email:{
type:String,
required :[true, "Email Name is required"],
unique: true, //checks if the email already exists in database or not
validate: validator.isEmail
},
password:{
type:String,
required :[true, "Password is required"],
minlength: [6, "Password must be at least"],
select: true,
},

accountType:{
type: String,
default:"seeker"
}
});
},
avatar:{
type: String,
default: "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"
},
},
{ timestamps: true }
);
const User = mongoose.model('User', userSchema);

export default User;
Loading