@@ -10,13 +10,16 @@ import {
10
10
updateProfile ,
11
11
} from "firebase/auth" ;
12
12
import app from "./firbase.config" ;
13
+ import axios from "axios" ;
14
+ import useAxiosCommon from "../../Hooks/useAxiosCommon" ;
13
15
14
16
export const AuthContext = createContext ( null ) ;
15
17
const auth = getAuth ( app ) ;
16
18
const googlepro = new GoogleAuthProvider ( ) ;
17
19
const AuthProvider = ( { children } ) => {
18
20
const [ user , setuser ] = useState ( null ) ;
19
21
const [ loding , setloding ] = useState ( true ) ;
22
+ const axiosCommon = useAxiosCommon ( ) ;
20
23
21
24
//user create
22
25
const creatuser = ( email , password ) => {
@@ -43,16 +46,20 @@ const AuthProvider = ({ children }) => {
43
46
// logout
44
47
const logout = async ( ) => {
45
48
setuser ( null ) ;
46
-
47
- signOut ( auth ) ;
49
+ return signOut ( auth ) ;
48
50
} ;
49
51
50
- // Get token from server
51
- const getToken = async ( email ) => {
52
+ //save user
53
+
54
+ const saveUser = async ( user ) => {
55
+ const cuser = {
56
+ name : user ?. displayName ,
57
+ email : user ?. email ,
58
+ badge : "bronze" ,
59
+ } ;
52
60
const { data } = await axios . post (
53
- `${ import . meta. env . VITE_API_URL } /jwt` ,
54
- { email } ,
55
- { withCredentials : true }
61
+ `${ import . meta. env . VITE_API_URL } /user` ,
62
+ cuser
56
63
) ;
57
64
return data ;
58
65
} ;
@@ -61,15 +68,26 @@ const AuthProvider = ({ children }) => {
61
68
useEffect ( ( ) => {
62
69
const unsubscribe = onAuthStateChanged ( auth , ( user ) => {
63
70
setuser ( user ) ;
71
+ console . log ( user ) ;
72
+
64
73
if ( user ) {
65
- getToken ( user . email ) ;
74
+ const userinfo = { email : user . email } ;
75
+ axiosCommon . post ( "/jwt" , userinfo ) . then ( ( res ) => {
76
+ if ( res . data . token ) {
77
+ localStorage . setItem ( "access-token" , res . data . token ) ;
78
+ }
79
+ } ) ;
80
+
81
+ saveUser ( user ) ;
82
+ } else {
83
+ localStorage . removeItem ( "access-token" ) ;
66
84
}
67
85
setloding ( false ) ;
68
86
} ) ;
69
87
return ( ) => {
70
88
return unsubscribe ( ) ;
71
89
} ;
72
- } , [ ] ) ;
90
+ } , [ axiosCommon ] ) ;
73
91
74
92
const allvalue = {
75
93
user,
@@ -80,6 +98,7 @@ const AuthProvider = ({ children }) => {
80
98
logout,
81
99
setuser,
82
100
loding,
101
+ setloding,
83
102
} ;
84
103
return (
85
104
< AuthContext . Provider value = { allvalue } > { children } </ AuthContext . Provider >
0 commit comments