Mingyu

Data base Conn, Create user data with signup page

node_modules
\ No newline at end of file
const mysql = require('mysql')
var pool = mysql.createPool({
host: "localhost",
user: "root",
password: "1234",
port: 3306,
database: "rest_stop"
})
var adduser = function(name, id, password, callback) {
console.log('addUser');
pool.getConnection(function(err, conn) {
if(err){
if(conn){
conn.release();
}
callback(err, null);
return;
}
var data = {name:name, id:id, password:password};
var exec = conn.query('insert into users set ?', data, function(err, result) {
conn.release();
if(err){
console.log('SQL 실행 시 오류 발생');
console.dir(err);
callback(err,null);
return;
}
callback(null, result);
})
})
}
module.exports.pool = pool;
//module.exports.login = login;
module.exports.adduser = adduser;
//module.exports.listuser = listuser;
const Connection = require('./Connection')
var adduser = async (username,userId,userPassword) => {
try {
const query = `INSERT INTO ` +
`accounts ` +
`VALUES ` +
`(null, '$(username)', '$(userId)', '$(userPassword)')`
await Connection(query)
return true;
} catch (error) {
return false;
}
};
var login;
var listuser = function(req, res) {
console.log('user(user2.js) 모듈 안에 있는 listuser 호출됨.');
// 데이터베이스 객체 참조
var database = req.app.get('database');
// 데이터베이스 객체가 초기화된 경우, 모델 객체의 findAll 메소드 호출
if (database.db) {
// 1. 모든 사용자 검색
database.UserModel.findAll(function(err, results) {
// 에러 발생 시, 클라이언트로 에러 전송
if (err) {
console.error('사용자 리스트 조회 중 에러 발생 : ' + err.stack);
res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
res.write('<h2>사용자 리스트 조회 중 에러 발생</h2>');
res.write('<p>' + err.stack + '</p>');
res.end();
return;
}
if (results) {
console.dir(results);
res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
res.write('<h2>사용자 리스트</h2>');
res.write('<div><ul>');
for (var i = 0; i < results.length; i++) {
var curId = results[i]._doc.id;
var curName = results[i]._doc.name;
res.write(' <li>#' + i + ' : ' + curId + ', ' + curName + '</li>');
}
res.write('</ul></div>');
res.end();
} else {
res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
res.write('<h2>사용자 리스트 조회 실패</h2>');
res.end();
}
});
} else {
res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
res.write('<h2>데이터베이스 연결 실패</h2>');
res.end();
}
};
//사용자를 인증하는 함수 : 아이디로 먼저 찾고 비밀번호를 그 다음에 비교하도록 함
var authUser = function(database, id, password, callback) {
console.log('authUser 호출됨.');
// 1. 아이디를 이용해 검색
database.UserModel.findById(id, function(err, results) {
if (err) {
callback(err, null);
return;
}
console.log('아이디 [%s]로 사용자 검색결과', id);
console.dir(results);
if (results.length > 0) {
console.log('아이디와 일치하는 사용자 찾음.');
// 2. 패스워드 확인 : 모델 인스턴스를 객체를 만들고 authenticate() 메소드 호출
var user = new database.UserModel({id:id});
var authenticated = user.authenticate(password, results[0]._doc.salt, results[0]._doc.hashed_password);
if (authenticated) {
console.log('비밀번호 일치함');
callback(null, results);
} else {
console.log('비밀번호 일치하지 않음');
callback(null, null);
}
} else {
console.log("아이디와 일치하는 사용자를 찾지 못함.");
callback(null, null);
}
});
}
//사용자를 등록하는 함수
var addUser = function(database, id, password, name, callback) {
console.log('addUser 호출됨.');
// UserModel 인스턴스 생성
var user = new database.UserModel({"id":id, "password":password, "name":name});
// save()로 저장
user.save(function(err) {
if (err) {
callback(err, null);
return;
}
console.log("사용자 데이터 추가함.");
callback(null, user);
});
}
module.exports.login = login;
module.exports.adduser = adduser;
module.exports.listuser = listuser;
......@@ -60,7 +60,7 @@
<div class="text-center my-5">
<h1>로그인</h1>
<br>
<form method="post" action="/login/process">
<form method="post" action="/signup/process">
<table>
<tr>
<td><label>이름</label></td>
......
var express = require('express')
var User = require('../database/User')
var router = express.Router()
//라우팅 함수 등록
......@@ -7,19 +8,30 @@ router.get('/',function(req,res){
res.render('login.html')
});
router.post('/process', function(req, res) {
router.post('/process', async (req, res) => {
console.log('/process/login 처리함');
var paramId = req.body.id || req.query.id;
var paramPassword = req.body.password || req.query.password;
//GET, POST 모두 고려해서 둘 다 검사
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>Result form Express Server</h1>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
const results = await User.login(paramId, paramPassword);
if (results){
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>로그인 성공</h1>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
} else {
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>정보가 잘못되었습니다.</h1>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
}
});
module.exports = router
\ No newline at end of file
......
var express = require('express')
var Conn = require('../database/Connection')
var router = express.Router()
router.get('/',function(req,res){
......@@ -14,13 +15,47 @@ router.post('/process', function(req, res) {
var paramPassword = req.body.password || req.query.password;
//GET, POST 모두 고려해서 둘 다 검사
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>Result form Express Server</h1>');
res.write('<div><p>Param name : ' + paramName + '</p></div>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
if(Conn.pool){
Conn.adduser(paramName, paramId, paramPassword, function(err, addedUser) {
if(err){
console.error(err.stack);
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>추가 중 오류</h1>');
res.write('<div><p>Param name : ' + paramName + '</p></div>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
return;
}
if (addedUser){
console.dir(addedUser);
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>회원가입 성공</h1>');
res.write('<div><p>Param name : ' + paramName + '</p></div>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
} else {
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>회원가입 실패.</h1>');
res.write('<div><p>Param id : ' + paramId + '</p></div>');
res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
res.write("<br><br><a href ='/login.html'>로그인 페이지로 돌아가기</a>");
res.end();
}
})
}else{
res.writeHead('200', { 'Content-Type': 'text/html;charset=utf8' });
res.write('<h1>데이터베이스 연결 실패</h1>');
res.end();
}
});
module.exports = router
\ No newline at end of file
......
../ejs/bin/cli.js
\ No newline at end of file
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../ejs/bin/cli.js" "$@"
else
exec node "$basedir/../ejs/bin/cli.js" "$@"
fi
......
../jake/bin/cli.js
\ No newline at end of file
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../jake/bin/cli.js" "$@"
else
exec node "$basedir/../jake/bin/cli.js" "$@"
fi
......
../mime/cli.js
\ No newline at end of file
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../mime/cli.js" "$@"
else
exec node "$basedir/../mime/cli.js" "$@"
fi
......
......@@ -55,6 +55,14 @@
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
"node_modules/bignumber.js": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
"integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==",
"engines": {
"node": "*"
}
},
"node_modules/body-parser": {
"version": "1.20.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.0.tgz",
......@@ -187,6 +195,11 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
......@@ -453,6 +466,11 @@
"node": ">= 0.10"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
},
"node_modules/jake": {
"version": "10.8.5",
"resolved": "https://registry.npmjs.org/jake/-/jake-10.8.5.tgz",
......@@ -542,6 +560,25 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"node_modules/mysql": {
"version": "2.18.1",
"resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
"integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==",
"dependencies": {
"bignumber.js": "9.0.0",
"readable-stream": "2.3.7",
"safe-buffer": "5.1.2",
"sqlstring": "2.3.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mysql/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
......@@ -599,6 +636,11 @@
"node": ">= 0.6.0"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
......@@ -647,6 +689,25 @@
"node": ">= 0.8"
}
},
"node_modules/readable-stream": {
"version": "2.3.7",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
"integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
......@@ -731,6 +792,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/sqlstring": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
"integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
......@@ -739,6 +808,19 @@
"node": ">= 0.8"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string_decoder/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
......@@ -786,6 +868,11 @@
"inherits": "2.0.3"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
},
"node_modules/util/node_modules/inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
......
This diff is collapsed. Click to expand it.
......@@ -15,6 +15,7 @@
"express": "^4.18.1",
"express-error-handler": "^1.1.0",
"http": "^0.0.1-security",
"mysql": "^2.18.1",
"path": "^0.12.7",
"serve-static": "^1.15.0"
}
......