Skip to content

Commit

Permalink
fix: login jwt token logic
Browse files Browse the repository at this point in the history
  • Loading branch information
2-one-week committed Dec 22, 2020
1 parent 5c1ee53 commit fd1c3a6
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
24 changes: 20 additions & 4 deletions client/src/hoc/Auth.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, { useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import { useHistory } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import A from '@atom'
import userAPI from '@api/user'
import axios from 'axios'
import { ResponseType, serverURL } from '@util/myAxios'
import { insertUserInfo } from '@store/reducer/user.reducer'
import { joinWorkspace } from '@store/reducer/workspace.reducer'

Expand All @@ -30,7 +30,13 @@ const Auth = (Component: any, option: boolean) => () => {

try {
if (token) {
const { success, data } = await userAPI.getUserInfo()
const {
data: { success, data },
} = await axios.get<ResponseType>(`${serverURL}/api/user/status`, {
headers: {
Authorization: `Bearer ${token}`,
},
})

if (success && option) {
dispatch(insertUserInfo(data))
Expand All @@ -54,7 +60,17 @@ const Auth = (Component: any, option: boolean) => () => {

setLoading(false)
} catch (error) {
window.location.href = '/'
switch (error.response.status) {
case 401:
localStorage.removeItem('token')
window.location.href = '/'
break
case 403:
window.location.href = '/'
break
default:
break
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions client/src/util/myAxios.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import axios from 'axios'

const serverURL =
export const serverURL =
process.env.NODE_ENV === 'development'
? process.env.SERVER_DOMAIN_DEVELOP
: process.env.SERVER_DOMAIN_PRODUCTION

const headerConfig = {
export const headerConfig = {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
Expand Down
3 changes: 2 additions & 1 deletion server/src/middleware/user.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ const verifyUser = (req: Request, res: Response, next: NextFunction) => {
req.user = { id, email, name, profileImageUrl }
return next()
}
} catch (error) {
return res.status(403).json({ success: false })
} catch (error) {
return res.status(401).json({ success: false })
}
}

Expand Down

0 comments on commit fd1c3a6

Please sign in to comment.