Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
students
messenger
Commits
c748afc4
Commit
c748afc4
authored
Jan 08, 2021
by
우지원
Browse files
로그인, 회원가입 localStorage에 저장
parent
00e7f876
Changes
9
Hide whitespace changes
Inline
Side-by-side
client/src/Components/Menu.js
View file @
c748afc4
import
React
from
'
react
'
import
{
Navbar
,
Nav
,
Button
}
from
'
react-bootstrap
'
;
import
{
handleLogout
}
from
'
../utils/auth
'
;
function
Menu
()
{
const
userName
=
"
정연우
"
;
...
...
@@ -13,7 +14,7 @@ function Menu() {
<
Nav
.
Link
href
=
"
/profile
"
>
Profile
<
/Nav.Link
>
<
Nav
.
Link
href
=
"
/hello
"
>
Hello
<
/Nav.Link
>
<
/Nav
>
<
Button
variant
=
"
light
"
className
=
"
ml-3
"
>
Logout
<
/Button
>
<
Button
onClick
=
{()
=>
handleLogout
()}
variant
=
"
light
"
className
=
"
ml-3
"
>
Logout
<
/Button
>
<
/Navbar
>
)
}
...
...
client/src/Pages/LogInPage.js
View file @
c748afc4
...
...
@@ -36,19 +36,19 @@ function LogIn() {
async
function
handleSubmit
(
event
)
{
event
.
preventDefault
()
const
form
=
event
.
currentTarget
;
if
(
form
.
checkValidity
()
===
false
)
{
event
.
preventDefault
();
event
.
stopPropagation
();
}
setValidated
(
true
);
//
const form = event.currentTarget;
//
if (form.checkValidity() === false) {
//
event.preventDefault();
//
event.stopPropagation();
//
}
//
setValidated(true);
try
{
setLoading
(
true
)
setError
(
''
)
await
axios
.
post
(
'
/auth/login
'
,
user
)
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
handleLogin
()
handleLogin
(
user
)
setSucces
(
true
)
}
catch
(
error
)
{
catchErrors
(
error
,
setError
)
...
...
@@ -76,7 +76,7 @@ function LogIn() {
<
Container
className
=
"
d-flex justify-content-center
"
>
<
div
className
=
"
mt-5 p-5 shadow w-75
"
>
<
h2
className
=
"
text-center
"
>
로그인
<
/h2
>
<
h2
className
=
"
text-center
"
>
로그인
<
/h2
>
<
Form
.
Group
controlId
=
"
formGroupEmail
"
>
<
Form
.
Label
>
이메일
<
/Form.Label
>
...
...
client/src/Pages/SignUpPage.js
View file @
c748afc4
...
...
@@ -41,7 +41,7 @@ function SingUp() {
event
.
stopPropagation
();
}
setValidated
(
true
);
console
.
log
(
user
)
//
console.log(user)
try
{
setError
(
''
)
...
...
@@ -59,6 +59,7 @@ function SingUp() {
// 알아서 stringify하기 때문에 따로 해줄 필요 없음.
// console.log(response.data)
console
.
log
(
user
)
// ?????????hash 처리된 password가 저장되지 않았음
// setUser(INIT_USER)
}
catch
(
error
)
{
...
...
client/src/utils/auth.js
View file @
c748afc4
import
axios
from
"
axios
"
//자동으로 localstorage에 login이 생성됨
export
function
handleLogin
()
{
localStorage
.
setItem
(
'
loginStatus
'
,
'
true
'
)
export
function
handleLogin
(
props
)
{
localStorage
.
setItem
(
'
user
'
,
JSON
.
stringify
({
email
:
props
.
email
})
)
}
export
async
function
handleLogout
()
{
localStorage
.
removeItem
(
'
loginStat
us
'
)
await
axios
.
get
(
'
/
api/
auth/logout
'
)
localStorage
.
removeItem
(
'
us
er
'
)
await
axios
.
get
(
'
/auth/logout
'
)
}
\ No newline at end of file
server/controllers/auth.controller.js
View file @
c748afc4
...
...
@@ -2,8 +2,7 @@ import User from "../models/User.js"
import
bcrypt
from
'
bcryptjs
'
import
jwt
from
'
jsonwebtoken
'
import
config
from
"
../config.js
"
//꼭 js붙여주기!!
//isEmail
//server부분에는 꼭 js붙여주기!!
//sign validation해야됨
const
login
=
async
(
req
,
res
)
=>
{
...
...
@@ -14,9 +13,10 @@ const login = async (req, res) => {
try
{
// 1) 사용자 확인
const
user
=
await
User
.
findOne
({
email
}).
select
(
'
+password
'
)
// 2) 이메일 사용자가 없으면 에러 반환
if
(
!
user
)
{
return
res
.
status
(
404
).
send
(
`
${
email
}
이
없습니다`
)
return
res
.
status
(
404
).
send
(
`
${
email
}
을 사용하는 사용자가
없습니다`
)
}
// 3) 비밀번호 일치 확인
...
...
@@ -25,11 +25,10 @@ const login = async (req, res) => {
// 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
if
(
passwordMatch
)
{
//토큰 생성
const
token
=
jwt
.
sign
({
userId
:
user
.
_id
},
config
.
jwtSecret
,
{
//jwtSecret : 노출되면 안됨. 문자열
expiresIn
:
'
7d
'
//만기날짜 : 만든 7일후 만기
})
const
token
=
jwt
.
sign
({
userId
:
user
.
_id
},
config
.
jwtSecret
,
{
expiresIn
:
'
7d
'
})
//jwtSecret : 노출되면 안됨. 문자열
//expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기
//쿠키에 저장
//res : client로 넘어가는 객체 cookie('이름', value)
res
.
cookie
(
'
token
'
,
token
,
{
...
...
@@ -37,10 +36,11 @@ const login = async (req, res) => {
//생성일로부터 어느정도까지 살아있을 것인가
httpOnly
:
true
,
//client에서 javascript로 접근할 수 없음
secure
:
config
.
env
===
'
production
'
secure
:
config
.
env
===
'
production
'
,
//secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
})
res
.
send
(
'
Login Successful
'
)
}
else
{
// 5) 비밀번호가 틀리면 에러 반환
res
.
status
(
401
).
send
(
'
비밀번호가 일치하지 않습니다
'
)
...
...
server/controllers/user.controller.js
View file @
c748afc4
...
...
@@ -48,7 +48,7 @@ const signup = async (req, res) => {
username
,
nickname
,
email
,
password
,
password
:
hash
,
//required를 하였기 때문에 이중 하나라도 없으면 에러 발생
}).
save
()
//save시 user schema형식에 맞는지 확인후 틀리면 error발생 맞으면 mongooDb로 들어감
...
...
@@ -59,7 +59,7 @@ const signup = async (req, res) => {
}
catch
(
error
)
{
//알수없는 모든 에러발생시 처리
console
.
log
(
error
)
res
.
status
(
500
).
send
(
'
User signup error
'
)
res
.
status
(
500
).
send
(
'
회원가입 에러발생하였습니다.
'
)
}
//newUSer (객체)를 json형식으로 바꿔서 객체열로 보냄
...
...
server/models/User.js
View file @
c748afc4
...
...
@@ -2,7 +2,7 @@
import
mongoose
from
'
mongoose
'
const
{
String
}
=
mongoose
.
Schema
.
Types
const
{
String
}
=
mongoose
.
Schema
.
Types
//원래 java의 string이 아니라 mongoose의 string을 쓰기 위해 불러옴.
//object의 id를 쓸때에도 추가시켜줘야됨.
...
...
@@ -29,14 +29,6 @@ const UserSchema = new mongoose.Schema({
//정보를 찾을때 찾지 않게함
//플러스 옵션을 주면 찾을 수 있음(mongoose에서 용법찾아봐야됨)
},
// role: {
// type: String,
// required: true,
// default: 'user',
// enum: ['user', 'admin', 'root'],
// //열거, 배열 : role이라는 것이 'user', 'admin', 'root'중 하나를 쓰임
// //사용자에 역할을 줄 때 사용함.
//}
},{
//옵셥을 정의함.
timestamps
:
true
...
...
server/routes/auth.routes.js
View file @
c748afc4
...
...
@@ -6,6 +6,7 @@ const router = express.Router()
router
.
route
(
'
/auth/login
'
)
.
post
(
authCtrl
.
login
)
.
get
(
authCtrl
.
login
)
router
.
route
(
'
/auth/logout
'
)
.
get
(
authCtrl
.
logout
)
...
...
server/server.js
View file @
c748afc4
import
express
from
'
express
'
import
connectDb
from
'
./utils/connectDb.js
'
import
userRouter
from
'
./routes/user.routes.js
'
import
authRouter
from
'
./routes/auth.routes.js
'
connectDb
()
...
...
@@ -12,6 +13,7 @@ app.use(express.json())
//이부분 다음부터는 req.body라는 부분을 실행할 수 있음
app
.
use
(
userRouter
)
app
.
use
(
authRouter
)
//userRouter로 이동
app
.
get
(
'
/
'
,
(
req
,
res
)
=>
{
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment