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

added Auth react context #91

Merged
merged 11 commits into from
Jul 13, 2024
Merged
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
14 changes: 0 additions & 14 deletions Tajpuriya quotes.txt

This file was deleted.

2 changes: 2 additions & 0 deletions nepalingo-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"react-dom": "^18.3.1",
"react-ga4": "^2.1.0",
"react-router-dom": "^6.24.1",
"react-supabase": "^0.2.0",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you still using react-supabase? You can run pnpm remove react-supabase to get rid of it if you don't need it anymore

https://chatgpt.com/share/04fc4457-0e8f-40f1-b135-e59fe0c94d16

"swr": "^2.2.5"
},
"devDependencies": {
Expand All @@ -37,6 +38,7 @@
"ts-node": "^10.9.2",
"typescript": "^5.5.2",
"vite": "^5.3.1",
"vite-plugin-string": "^1.2.3",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did you add this? what is it for?

"vite-tsconfig-paths": "^4.3.2"
}
}
Expand Down
51 changes: 51 additions & 0 deletions nepalingo-web/pnpm-lock.yaml

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

Empty file.
Empty file.
4 changes: 4 additions & 0 deletions nepalingo-web/public/quotes/tajpuriya.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
"जैठा तक दमल ड छोक ऐठा तक जाईस, आगुबिती जलेसे दमाल ड ऐठा जाए हुना दख्बो","Walk as far as you can see the road, The way forward is visible after reaching there"
"सफलतर सुरुवत सबै दिन आसफलतारसे हल्कु","Success always begins with failure"
"जैला ठिक हो ऐला करिस, जैला सजिलो लगेसोक ऐल ना करिस","Do what is right, not what is easy"
"जैला जीवन डक समयर महत्व रखेसेक ओईला आप्नाई आप्नाक जनेसेक","The one who has accepted the time in life has known himself"
36 changes: 5 additions & 31 deletions nepalingo-web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React from 'react';
import {
BrowserRouter as Router,
Route,
Expand All @@ -7,46 +7,20 @@ import {
} from "react-router-dom";
import User_auth from "./components/userAuth/UserAuth";
import Home from "./pages/Home/Home";
import supabase from "./components/userAuth/supabaseClient";
import ReactGA from 'react-ga4';
import { useAuth } from "./components/userAuth/AuthContext";
import ReactGA from "react-ga4";

const App: React.FC = () => {
const TrackingID = import.meta.env.VITE_GOOGLE_ANALYTICS_TRACKING_ID;
ReactGA.initialize(TrackingID);
const [isAuthenticated, setIsAuthenticated] = useState(false);

// useEffect to check the current session and subscribe to authentication state changes
useEffect(() => {
// Function to fetch the current session
const fetchSession = async () => {
const {
data: { session },
} = await supabase.auth.getSession();
setIsAuthenticated(!!session); // Update authentication state
};

fetchSession(); // Initial session fetch

// Subscribe to authentication state changes
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
setIsAuthenticated(!!session); // Update authentication state on changes
});

// Cleanup subscription on component unmount
return () => subscription.unsubscribe();
}, []);
const { user } = useAuth();

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yessss!! This code looks much cleaner now!

return (
<Router>
<Routes>
<Route path="/login" element={<User_auth />} />
{/* Protect the / route, redirect to /login if not authenticated */}
<Route
path="/"
element={isAuthenticated ? <Home /> : <Navigate to="/login" />}
/>
<Route path="/" element={user ? <Home /> : <Navigate to="/login" />} />
{/* Default route redirects to /login */}
<Route path="/" element={<Navigate to="/login" />} />
</Routes>
Expand Down
61 changes: 61 additions & 0 deletions nepalingo-web/src/components/userAuth/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, {
createContext,
useContext,
useState,
ReactNode,
useEffect,
} from "react";
import supabase from "./supabaseClient";
import { AuthError, AuthResponse, AuthTokenResponsePassword, SignInWithPasswordCredentials, SignUpWithPasswordCredentials, User } from "@supabase/supabase-js";

interface AuthContextProps {
user: User | null;
signUp: (data: SignUpWithPasswordCredentials) => Promise<AuthResponse>;
signIn: (data: SignInWithPasswordCredentials) => Promise<AuthTokenResponsePassword>;
signOut: () => Promise<{ error: AuthError | null }>
}

const AuthContext = createContext<AuthContextProps | undefined>(undefined);

export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<User | null>(null);
const [, setIsAuthenticated] = useState(false);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you don't need isAuthenticated anymore - you can get rid of this. Since you can figure out whether the user is authenticated from the user data


useEffect(() => {
const fetchSession = async () => {
const {
data: { session },
} = await supabase.auth.getSession();
setIsAuthenticated(!!session);
setUser(session?.user ?? null);
};

fetchSession();

const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
setIsAuthenticated(!!session);
setUser(session?.user ?? null);
});

return () => subscription.unsubscribe();
}, []);

const value: AuthContextProps = {
signUp: (data) => supabase.auth.signUp(data),
signIn: (data) => supabase.auth.signInWithPassword(data),
signOut: () => supabase.auth.signOut(),
user,
};

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};
21 changes: 7 additions & 14 deletions nepalingo-web/src/components/userAuth/UserAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from "react";
import supabase from "./supabaseClient";
import { useNavigate } from "react-router-dom";
import { useAuth } from "./AuthContext";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faUser,
Expand All @@ -20,6 +20,7 @@ const User_auth: React.FC = () => {
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<boolean>(false);
const [showPassword, setShowPassword] = useState(false);
const { signUp, signIn } = useAuth();
const navigate = useNavigate();

// Function to handle form submission
Expand All @@ -33,28 +34,23 @@ const User_auth: React.FC = () => {
}

if (action === "Sign Up" && username != "") {
// Attempt to sign up the user with the provided email and password
const { error } = await supabase.auth.signUp({
const { error } = await signUp({
email,
password,
options: {
data: {
// Store the username in the user metadata
username: username,
},
},
});

if (error) {
// If there is an error during sign up, set the error message
setError(error.message);
} else {
// If sign up is successful, set success to true
setSuccess(true);
}
} else {
// Attempt to log in the user with the provided email and password
const { data, error } = await supabase.auth.signInWithPassword({
const { error } = await signIn({
email,
password,
});
Expand All @@ -63,12 +59,7 @@ const User_auth: React.FC = () => {
// If there is an error during log in, set the error message
setError(error.message);
} else {
const { user } = data;
if (user) {
const { user_metadata } = user;
// Navigate to home page with the username passed as state
navigate("/", { state: { username: user_metadata.username } });
}
navigate("/");
}
}
};
Expand All @@ -78,6 +69,8 @@ const User_auth: React.FC = () => {
setAction(newAction);
setError(null);
setSuccess(false);
setEmail(""); // the email and password field will reset everytime action is changed
setPassword("");
};

return (
Expand Down
Loading
Loading