social login
github login
먼저 developer setting에 들어가서 Oauth 앱을 만들어준다. authorization callback URL은 본인 페이지 뒤에 콜백할 url을 맘대로 지어도 된다. 예) http://localhost:9999/user/github/login
Client ID와 Client Secrets은 .env파일에 넣어준다. 특히 client screts은 잘못 기재하면 다시 generate 해야하니 귀찮은 일을 만들지 않도록 잘 기입해준다.
https://docs.github.com/ko/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps
OAuth 앱 권한 부여 - GitHub Docs
다른 사용자가 OAuth app에 권한을 부여하도록 설정할 수 있습니다.
docs.github.com
구현 방법 (주요사항만)
1. 깃헙으로 로그인을 하고 싶다면 사용자로 깃헙으로 보내준다.
핵심적인 부분을 살펴보자면 먼저 github id 요청으로 접속을 해야한다. 접속과 동시에 매개변수를 보내주어야하는데 앱을 만들었을 때 client_id를 보내주어야 404페이지가 안나온다. scope를 설정하면 가입하고자하는 깃허브 유저의 정보 제공을 설정할 수 있다. 필요한것만 가져오면 된다.
object를 url로 바꾸는 방법
const cfg = {
charater: "cho-gal",
scope: "weapon:hands spieces:oger",
};
const param = new URLSearchParams(cfg).toString();
console.log(param);
2.정보를 공유하는 것을 승인하게 되면 깃헙은 사용자를 개발하고 있는 사이트로 돌려보낼것이다.
이때 깃헙에서 코드를 주는데 이것을 Access token으로 바꿔야한다.
post 처리를 위해 fetch를 사용해준다. 하지만 백엔드에서는 라이브러리 이용하지 않으면 fetch를 할 수가 없다. node에서 fetch를 사용하기 위해서는 node-fetch같은 라이브러리를 설치하고 이것을 fetch로 import시키고 json데이터를 받아오면 된다.
3. 깃헙은 사용자를 token과 함께 redirect시킬것이다.
이제 access_token을가지고 github api을 사용해 user정보를 가져와야한다.
user 정보를 가져왔는데 이메일이 null 일 경우 아래 url를 참고
https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28
Emails - GitHub Docs
Use the REST API to manage email addresses of authenticated users. If a request URL does not include a {username} parameter then the response will be for the signed-in user (and you must pass authentication information with your request). Additional privat
docs.github.com
소셜 로그인에 대한 mongoose 스키마 모델을 재정의 할 필요가 있다. 또한 소셜 로그인 한 유저에게 세션을 주는 것도 잊지말자
LogOut
get 요청을 하는 /logout 라우터를 만들고 미들웨어로 req.session.destroy() 끝. 세션을 없애주면 된다. 그리고 홈으로 리다이렉트.