오늘 한 것
- feature 18 login 컴포넌트
- 비회원 로그인
- github Oauth, google Oauth
비회원 로그인 기능과 Oauth기능을 구현하였다. 먼저 비회원 기능은 단지 로그인 없이 웰컴 페이지로 라우팅 하게 만들었다. history.push를 쓰니 redirect 할 때 굉장히 편했다.
const guestHandler=(e)=>{
history.push('/main')
}
<button type="button" onClick={guestHandler}>Guest?</button>
굉장히 간단히 구현 가능했다.
Oauth기능은 전에 해봤던 github Oauth를 할 예정이고 advanced로 google Oauth를 할 예정이다.
const getAccessToken =(authorizationCode)=>{
axios.post('https://localhost:5000/main/oauth/accesstoken',
{ authorizationCode: authorizationCode,accept:'application/json',withCredentials:true})
.then(res=> {
setAccessToken(res.data.data.accessToken)
})
}
먼저 서버로 권한 코드와 함께 서버로 accessToken을 요청한다.
oAuth: {
accessToken: async (req, res) => {
if (!req.body.authorizationCode) {
res.status(401).json({messgae: "check authorization code again"})
} else {
const params = {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code: req.body.authorizationCode
}
await axios.post('https://github.com/login/oauth/access_token',
params,
{headers: {accept: 'application/json'}})
.then(result=>{
res.json(
{
data: {accessToken: result.data.access_token},
message: "issued access_token successfully"
})})
.catch(e=>console.log(e))
}
}
}
요청을 보내면 github으로 인증 토큰을 받아온다. 그 후 state에 토큰을 저장했다가 github에 유저 정보를 요청한다.
const getUserInfo = ()=>{
axios.get('https://api.github.com/user',{headers:{authorization:`token ${accessToken}`, Accept: 'application/json'}})
.then(res=>{
const { login, id, name } = res.data;
const param = {email: `${login}@github.com`, password: id, userName: name?name:login};
axios.post('https://localhost:5000/main/signup', param, {accept: 'application/json'})
.finally(e => {
axios.post('https://localhost:5000/main/login', param, {accept: 'application/json',withCredentials:true})
.then(res => {
dispatch(setIsLogin());
dispatch(setUserInfo());
})
})
})
}
정보를 받아와 다시 서버에 회원가입 요청을 보내고 그 뒤에 로그인 요청을 하여 로그인한다.
팀원들과 서버와 클라이언트를 연결해보았다. 처음 연결해보는 거라 시간이 좀 걸렸지만 연결이 잘돼서 신기했고 재밌었다. 하루가 정말 순삭이다. 프로젝트를 하면서 팀원들과 합을 맞추는 법도 배우지만 놓쳤던 부분에 대해서 공부를 더 할 수 있어서 좋았다. 많이 배워야겠다.
'TIL' 카테고리의 다른 글
20210325 first project #5 (0) | 2021.03.26 |
---|---|
20210323 first project #4 (0) | 2021.03.23 |
20210318 first project #2 (0) | 2021.03.19 |
20210317 first project #1 (2) | 2021.03.18 |
20210308 TIL (0) | 2021.03.08 |
댓글