nodejs 회원가입 및 로그인 하기

SangHoon Lee·2020년 5월 28일
0

이번에는 과제로 해본 nodejs로 회원가입 및 로그인하는것을 구현하려고 합니다.

기본적으로 html 대신 ejs 파일로 만들어서 하였습니다.

ejs : Embedded JavaScript Template의 약자로 nodejs 진영에서 많이 사용하는 템플릿엔진

먼저 몽고디비에 대하여 정리 해 보았습니다.
몽고디비는 따로 설치해야하며, 서버를 연결하기 전에 몽고디비를 먼저 연결시켜주어야합니다.
mongodb 설치파일에서 bin파일에 mongod 을 통해 연결시킵니다.
mongod dbpath "경로" 를하면 특정 경로에 연결 할 수 있습니다.
연결한다음, 따로 cmd창을 하나 더 열어서 mongo 명령어를 사용하여 연결합니다.
그리고 ,

show dbs 로 db목록을 한번 확인 해 보고,
show collections 명령어로 어떤디비가있는지 볼 수 있습니다.
use "db명" 하면, 해당 디비를 사용합니다.

이제 소스코드를 보여드리겠습니다.

먼저 ejs파일 목록입니다.

login.ejs

<html>

<head>
    <meta charset="utf-8">
    <title>
        Login
    </title>
</head>

<body>
    <center>
        <h1>Login Page</h1>
        <table>
            <form action="/" method="POST">
                <input id="user_id" name="user_id" type="text" pleaceholder="ID">
                <br />
                <input id="password" name="password" type="password" placeholder="Password">
                <br />
                <button type="submit ">로그인</button>
            </form>
            <form action="/regist" method="POST">
                <button type="submit">회원가입</button>
            </form>
            <form action="/findID" method="POST">
                <button type="submit">아이디 찾기</button>
            </form>
            <form action="/findpwd" method="POST">
                <button type="submit">비밀번호 찾기</button>
            </form>
        </table>
    </center>
</body>

</html>

logout.ejs

<html>

<head>
    <meta charset="utf-8">
    <title>
        Logout
    </title>

    <body>
        <h1>
            <%= id %>
        </h1>
        <h1>Nice to meet you
        </h1>
        <form action="/logout" method="POST">
            <button type="submit">Logout</button>
        </form>
    </body>
    <h1>
        <center> Calculator </center>
        <link type="text/css" rel="stylesheet" href="stylesheet.css" />
    </h1>
    <style>
        body {
            background-color: cornsilk;
        }
        
        table {
            border-collapse: collapse;
        }
        
        td {
            background-color: lightgreen;
            padding: 20px 105px;
        }
        
        input {
            text-align: right;
            border: none;
        }
        
        input:focus {
            outline: none;
        }
        
        .button {
            background-color: greenyellow;
            padding: 20px 40px;
            border-radius: 5px;
            box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        }
        
        .button:hover {
            -webkit-transition-duration: 0.4s;
            transition-duration: 0.4s;
            background: tomato;
            color: white;
            box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
        }
    </style>
</head>

<body>
    <center>
        <table border="1">
            <tr>
                <td colspan="10">
                    <input type="text" id="display">
                </td>
            </tr>
            <tr>
                <td colspan="10">
                    <input type="text" id="result">
                </td>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " style="width: 205pt; height: 47pt; " onclick="reset() ">AC</button>
                <button class="button " onclick="cal('/') ">/</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " onclick="sin()" style="width: 90pt;">Sin</button>
                <button class=" button " onclick="cos()" style="width: 90pt;">Cos</button>
                <button class="button " onclick="tan()" style="width: 90pt;">Tan</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " onclick="abs()" style="width: 90pt;">Abs</button>
                <button class=" button " onclick="pow()" style="width: 90pt;">Pow</button>
                <button class="button " onclick="log()" style="width: 90pt;">Log</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " onclick="asin()" style="width: 90pt;">Asn</button>
                <button class=" button " onclick="acos()" style="width: 90pt;">Aco</button>
                <button class="button " onclick="atan()" style="width: 90pt;">Ata</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " onclick="cal(7) ">7</button>
                <button class="button " onclick="cal(8) ">8</button>
                <button class="button " onclick="cal(9) ">9</button>
                <button class="button " onclick="cal('*') ">x</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " onclick="cal(4) ">4</button>
                <button class="button " onclick="cal(5) ">5</button>
                <button class="button " onclick="cal(6) ">6</button>
                <button class="button " onclick="cal( '-') ">-</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " onclick="cal(1) ">1</button>
                <button class="button " onclick="cal(2) ">2</button>
                <button class="button " onclick="cal(3) ">3</button>
                <button class="button " onclick="cal( '+') ">+</button>
            </tr>
        </table>
        <table>
            <tr>
                <button class="button " style="width: 140pt; height: 47pt; " onclick="cal(0) ">0</button>
                <button class="button " onclick="cal( '.') ">.</button>
                <button class="button " onclick="resultCal() ">=</button>
            </tr>
        </table>

        <script>
            function asin() {
                var display = document.getElementById('display');
                var result = Math.asin(display.value);
                document.getElementById('result').value = result;
                display.value = result;
            }

            function acos() {
                var display = document.getElementById('display');
                var result = Math.acos(display.value);
                document.getElementById('result').value = result;
                display.value = result;
            }

            function atan() {
                var display = document.getElementById('display');
                var result = Math.atan(display.value);
                document.getElementById('result').value = result;
                display.value = result;
            }

            function log() {
                var display = document.getElementById('display');
                var result = Math.log(display.value);
                document.getElementById('result').value = result;
                display.value = result;
            }

            function pow() {
                var display = document.getElementById('display');
                var result = display.value * display.value;
                document.getElementById('result').value = result;
                display.value = result;
            }

            function abs() {
                var display = document.getElementById('display');
                var result = Math.abs(display.value);
                document.getElementById('result').value = result;
                display.value = result;
            }

            function del() {
                display.result.value =
                    display.result.value.substring(0, display.result.value.length - 1);
            }

            function sin() {
                var display = document.getElementById('display');
                var result = Math.sin((display.value * 3.14159265359) / 180)
                document.getElementById('result').value = result;
                display.value = result;
            }

            function cos() {
                var display = document.getElementById('display');
                var result = Math.cos((display.value * 3.14159265359) / 180)
                document.getElementById('result').value = result;
                display.value = result;
            }

            function tan() {
                var display = document.getElementById('display');
                var result = Math.tan((display.value * 3.14159265359) / 180)
                document.getElementById('result').value = result;
                display.value = result;
            }

            function cal(char) {
                var display = document.getElementById('display');
                display.value = display.value + char;
            }

            function resultCal(char) {
                var display = document.getElementById('display');
                var result = eval(display.value);
                document.getElementById('result').value = result;
                document.getElementById('display').value = " ";
                display.value = result;
            }

            function reset() {
                document.getElementById('display').value = " ";
                document.getElementById('result').value = " ";
            }
        </script>
    </center>
</body>
</head>

</html>

findID.ejs

<html>

<head>
    <meta charset="utf-8">
    <title>
        FindID
    </title>
</head>

<body>
    <center>
        <h1>FindID Page</h1>
        <table>
            <form action="/findIDRst" method="POST">
                <input id="name" name="name" type="text" pleaceholder="name">
                <br />
                <input id="email" name="email" type="text" placeholder="email">
                <br />
                <input id="address" name="address" type="text" placeholder="address">
                <br />
                <button type="submit ">아이디 찾기</button>
            </form>
            <form action="/findIDBack" method="POST">
                <button type="submit">뒤로가기</button>
            </form>
        </table>
    </center>
</body>

</html>

findIDResult.ejs

<html>

<head>
    <meta charset="utf-8">
    <title>
        find ID
    </title>

    <body>
        <h1>
            your ID
            <%= Findid %>
        </h1>

        <form action="/findIDRstBack" method="POST">
            <button type="submit">뒤로가기</button>
        </form>
    </body>
</head>

</html>

findPassword.ejs

<html>

<head>
    <meta charset="utf-8">
    <title>
        FindPassword
    </title>
</head>

<body>
    <center>
        <h1>FindPassword Page</h1>
        <table>
            <form action="/findPasswordRst" method="POST">
                <input id="user_id" name="user_id" type="text" pleaceholder="ID">
                <br />
                <input id="name" name="name" type="text" pleaceholder="name">
                <br />
                <input id="email" name="email" type="text" placeholder="email">
                <br />
                <input id="address" name="address" type="text" placeholder="address">
                <br />
                <button type="submit ">아이디 찾기</button>
            </form>
            <form action="/findPasswordBack" method="POST">
                <button type="submit">뒤로가기</button>
            </form>
        </table>
    </center>
</body>

</html>

findPasswordResult.ejs

<html>

<head>
    <meta charset="utf-8">
    <title>
        find Password
    </title>

    <body>
        <h1>
            your Password
        </h1>
        <h1>
            <%= passwordid %>
        </h1>

        <form action="/findPasswordRstBack" method="POST">
            <button type="submit">뒤로가기</button>
        </form>
    </body>
</head>

</html>

app.js

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/sessions');
const db = mongoose.connection;

db.once('err', () => {
    console.log(err);
});

db.once('open', () => {
    console.log('DB connected');
});

const UserSchema = mongoose.Schema({
    user_id: String,
    password: String,
    name: String,
    email: String,
    address: String,
});

const User = mongoose.model('sessions', UserSchema);
const app = require('express')();
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');
const url = require('url');

app.set('view engine', 'ejs');
app.set('views', './views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({
        url: "mongodb://localhost:27017/sessions",
        collection: "sessions"
    })
}));

app.get('/', (req, res) => {
    if (req.session.logined) {
        res.render('logout', {
            id: req.session.user_id
        });
    } else {
        res.render('login');
    }
});

app.post('/regist', (req, res) => {
    res.render('register');
})

app.post('/findID', (req, res) => {
    res.render('findID');
})

app.post('/findpwd', (req, res) => {
    res.render('findPassword');
})

app.post('/register', (req, res) => {
    var uid = req.body.user_id;
    var upwd = req.body.password;
    var uname = req.body.name;
    var uemail = req.body.email;
    var uaddress = req.body.address;

    User.findOne({ "user_id": uid }, (err, user) => {
        if (err) return res.json(err);
        if (!user) {
            User.create({ "user_id": uid, "password": upwd, "name": uname, "email": uemail, "address": uaddress }, (err) => {
                if (err) return res.json(err);
                console.log('Success');
                res.redirect('/');
            })
        } else {
            console.log('user id duplicate');
            res.send(`
                <a href="/">Back</a>
                <h1>User id duplicate</h1>
            `);
        }
    })

});

app.post('/findIDRst', (req, res) => {
    var uname = req.body.name;
    var uemail = req.body.email;
    var uaddress = req.body.address;
    var uid;
    User.findOne({ "name": uname, "email": uemail, "address": uaddress }, (err, user) => {
        if (err) return res.json(err);
        if (user) {
            res.render('findIDResult', {
                Findid: uname
            });
        } else {
            console.log('can not find ID');
            res.send(`
                <a href="/">Back</a>
                <h1>can not find id</h1>
            `);
        }
    })
})

app.post('/findIDRst', (req, res) => {
    var uid = req.body.user_id;
    var uname = req.body.name;
    var uemail = req.body.email;
    var uaddress = req.body.address;

    User.findOne({ "user_id": uid, "name": uname, "email": uemail, "address": uaddress }, (err, user) => {
        if (err) return res.json(err);
        if (user) {
            res.render('findPasswordResult', {
                passwordid: uname
            });
        } else {
            console.log('can not find ID');
            res.send(`
                <a href="/">Back</a>
                <h1>can not find id</h1>
            `);
        }
    })
})

app.post('/registBack', (req, res) => {
    res.redirect('/');
})

app.post('/findIDBack', (req, res) => {
    res.redirect('/');
})

app.post('/findPasswordBack', (req, res) => {
    res.redirect('/');
})

app.post('/findIDRstBack', (req, res) => {
    res.redirect('/');
})

app.post('/findPasswordRstBack', (req, res) => {
    res.redirect('/');
})

app.post('/', (req, res) => {
    let id = req.body.user_id;
    let pwd = req.body.password;
    duplicate(req, res, id, pwd);
});

app.post('/logout', (req, res) => {
    req.session.destroy();
    res.redirect('/');
});

app.listen(3000, () => {
    console.log('listening 3000port');
});

function duplicate(req, res, uid, upwd) {
    let parseUrl = url.parse(req.url);
    let resource = parseUrl.pathname;
    User.findOne({ "user_id": uid }, (err, user) => {
        if (err) return res.json(err);

        if (!user) {
            console.log('Cannot find user');
            res.send(`
                    <a href="/">Back</a>
                    <h1>rechecking your ID -Can't find user</h1>
                `);
        } else {
            User.findOne({ "password": upwd })
                .exec((err, user) => {
                    if (err) return res.json(err);

                    if (!user) {
                        console.log('login failed');
                        res.send(`
                    <a href="/">Back</a>
                    <h1>Login failed - different password</h1>
                `);
                    } else {
                        console.log('welcome');
                        req.session.user_id = uid;
                        req.session.logined = true;
                        res.redirect('/');
                    }
                })
        }
    })
}

기존에 제가 sun으로 가입했었는데, 기존 가입된 상태에서 똑같은 아이디로 가입하게되면,

failed 문구가 뜨게됩니다.

또한 가입되지 않은 아이디를 로그인했을시,

가입된 아이디로 가입하면,

가입된 아이디의 이름과 함께, 계산기가 뜨게됩니다.

그러면 틀린 비밀번호로 하면 어떻게될까요?

이렇게 비밀번호가 다르다고 뜹니다.

기타 기능들입니다.

아이디찾기

비밀번호 찾기

마지막으로 가입입니다.

성공하면,

실패하면,

실패이유는 한가지입니다. 아이디가 기존 가입한 겹치기때문입니다.

몽고디비에 대해서 모르는 부분이 많아서 공부를 개인적으로 조금 했습니다. 블로그에 잘 정리된것이 많아 참고를 많이하였고, nodejs가 익숙하지않아서 괜찮은 git의 오픈소스 ,블로그 내용 등을 참고하고, 제가 필요한 기능에 맞게 수정하였습니다. 많이 어려웠지만 디비를 활용해보았다는 점에서 괜찮은 공부가 되었던 것 같습니다.

profile
C++ 공부하고있는 대학생입니다.

0개의 댓글