본문 바로가기

기타/Firebase By Node js

Firebase auth 사용법 : Firebase 회원가입 예제(1)

728x90

firebase auth 사용법을 회원가입 예제를 통해 알아보도록 하겠습니다.

저번 시간에 환경을 세팅하고 간단하게 db에 데이터를 보내는 방법에 대해서 알아보았는데요.

오늘은 nodejs 서버를 활용해 클라이언트에서 회원 가입하는 페이지를 구현해보도록 하겠습니다.

 

오늘은 nodejs express프레임워크도 추가적으로 활용할 계획이니 다음과 같이 install 해주시기 바랍니다.

hifirebase 디렉토리로 이동한 후 다음 코드를 실행해주세요.

npm install express --save

 

firebase콘솔에서 authentication메뉴를 선택하고 다음과 같이 설정하고 저장해주세요.

아래 코드를 복붙 해주세요.

개인키 입력하는 것은 저번 시간과 같이 진행해주세요. 

모르신다면 전 시간 글 하단부에서 확인해주세요.
코드 설명은 아래에 할 것이니 우선 구동하는 것부터 해봅시다 ㅎ

const express = require('express')
const app = express()
const port = 3000



app.get('/', (req, res) => {
  var html = `
  <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <label for="pass" class="label">Email Address</label>
    <input id="new_email" type="text"><br>
    <label for="pass" class="label">Password</label>
    <input id="new_pw_1" type="password" class="input" data-type="password"><br>
    <label for="pass" class="label">Repeat Password</label>
    <input id="new_pw_2" type="password" class="input" data-type="password"><br>
    <input type="button" onclick="newuser();" value="제출">
    <script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script>
    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js"></script>

    <!-- Add Firebase products that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js"></script>
    <script>
        const firebaseConfig = {
            개인키 입력
        };
        firebase.initializeApp(firebaseConfig);

        function newuser() {
            email = document.getElementById('new_email').value
            new_pw_1 = document.getElementById('new_pw_1').value
            new_pw_2 = document.getElementById('new_pw_2').value
            if (new_pw_1 != new_pw_2) {
                alert("확인 비밀번호가 다릅니다.")
            } else {
                firebase.auth().createUserWithEmailAndPassword(email, new_pw_2)
                    .then(() => {
                        alert('회원가입이 완료되었습니다.')
                    })
                    .catch(function (error) {
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        alert(error.code)
                    });
            }
        }
    </script>
</body>

</html>
  `
  res.send(html)
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

그런 다음다음과 같이 해당 실행해주세요.

웹브라우저에서 localhost:3000을 검색하면 다음과 같은 페이지가 나옵니다.

test_1@naver.com

비밀번호를 입력하면 다음과 같은 메시지가 나오고

회원이 추가된 것을 볼 수 있습니다.

 

같은 메일을 한 번 더 입력하면 다음과 같이 에러 메시지가 나옵니다.

const express = require('express')
const app = express()
const port = 3000

위의 코드는 express 모듈을 가져와 실행하는 것입니다.

express를 공부하기 위한 튜토리얼이 아니니 깊게 이야기하지는 않겠습니다.

app.get('/', (req, res) => {
  var html = `
  <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <label for="pass" class="label">Email Address</label>
    <input id="new_email" type="text"><br>
    <label for="pass" class="label">Password</label>
    <input id="new_pw_1" type="password" class="input" data-type="password"><br>
    <label for="pass" class="label">Repeat Password</label>
    <input id="new_pw_2" type="password" class="input" data-type="password"><br>
    <input type="button" onclick="newuser();" value="제출">
    <script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script>
    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js"></script>

    <!-- Add Firebase products that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js"></script>
    <script>
        const firebaseConfig = {
            개인키
        };
        firebase.initializeApp(firebaseConfig);

        function newuser() {
            email = document.getElementById('new_email').value
            new_pw_1 = document.getElementById('new_pw_1').value
            new_pw_2 = document.getElementById('new_pw_2').value
            if (new_pw_1 != new_pw_2) {
                alert("확인 비밀번호가 다릅니다.")
            } else {
                firebase.auth().createUserWithEmailAndPassword(email, new_pw_2)
                    .then(() => {
                        alert('회원가입이 완료되었습니다.')
                    })
                    .catch(function (error) {
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        alert(error.code)
                    });
            }
        }
    </script>
</body>

</html>
  `
  res.send(html)
})

위의 코드는 localhost:port/를 웹브라우저에서 요청하면 html 코드를 만들어 보내주는 역할을 합니다.

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

위의 코드는 app을 port에 연결해주는 역할을 합니다.

 

오늘 진도는 여기까지 입니다.

여기서 문제 하나 드리도록 하겠습니다.

위의 코드는 회원가입을 서버사이드에서 구현한 것일까요? 클라이언트 사이드에서 구현한 것일까요?

 

 

 

정답은 클라이언트입니다.

firebase에 이메일, 비밀번호를 보내는 것은 웹브라우져에서 하기 때문이죠.

위에 있는 html 코드만을 가지고도 firebase 회원가입을 진행할 수 있습니다. 

따로 떼어서 진행해보세요 ㅎㅎ

서버는 그런 일을 할 수 있는 html 코드를 찍어서 보내주는 역할만 할 뿐이죠.

이해가 안 가신다고요?

그러면 서버와 클라이언트에 대해 추가적인 공부를 해보시기 바랍니다.

다음시간에는 서버쪽에서 firebase와 통신하도록 한 번 만들어보는 시간을 갖겠습니다ㅎㅎ 

기대해주세요.

728x90