-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
105 lines (71 loc) · 2.49 KB
/
Copy pathauth.js
File metadata and controls
105 lines (71 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import {useState} from "react";
import axios from "axios";
import {useCookies} from "react-cookie"
import {useNavigate} from 'react-router-dom'
export const Auth = () =>{
return<div className="auth" >
<Login />
<Register />
</div>
}
// Login
const Login = () =>{
const[username,setUsername] = useState("");
const[password,setPassword] = useState("");
const [_,setCookies] = useCookies(["access_token"])
const navigate = useNavigate();
const onSubmit = async (event) =>{
event.preventDefault();
try{
const response = await axios.post("http://localhost:3001/auth/login",{
username,password,
});
setCookies("access_token",response.data.token);
window.localStorage.setItem("userID",response.data.userID);
navigate("/");
}catch(err){
console.error(err);
}
}
return (<Form username={username} setUsername={setUsername}
password={password} setPassword={setPassword} label="Login" onSubmit={onSubmit}/>);
};
// Register
const Register = (event) =>{
const[username,setUsername] = useState("");
const[password,setPassword] = useState("");
const onSubmit = async (event) =>{
event.preventDefault();
try{
await axios.post("http://localhost:3001/auth/register",{
username,password,
});
alert("Registration Completed ! Please Login")
}catch(err){
console.error(err);
}
};
return (<Form username={username} setUsername={setUsername}
password={password} setPassword={setPassword} label="Register"
onSubmit={onSubmit} />);
};
const Form = ({username,setUsername,password,setPassword,label,onSubmit,})=>{
return<div className="auth-container" >
<form onSubmit={onSubmit}>
<h2>{label}</h2>
<div className="form-group" >
<label htmlFor="username">
Username :
</label>
<input type="text" id="username" value={username} onChange={(event)=>setUsername(event.target.value)} />
</div>
<div className="form-group" >
<label htmlFor="password">
Password :
</label>
<input type="password" id="password" value={password} onChange={(event)=>setPassword(event.target.value)} />
</div>
<button type="submit">{label}</button>
</form>
</div>
}