login.js 2.23 KB
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session')

app.use(session({ secret: 'delicious biscuit', cookie: { maxAge: 60000 }}))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


var users = new Array();
users[0] = {
	"userId" : 0,
	"name" : "Admin",
	"password" : "123",
	"isAdmin" : true
}

app.get('/login', function (req, res) {
	// users 배열에서 찾도록 처리 해야 함
	// admin 여부를 확인하여 체크
	// req.body.id : ID
	// req.body.password : 패스워드
	if(users[req.body.id].password == req.body.password)
	{
		req.session.userId = users[req.body.id].userId;
		req.session.isAdmin = users[req.body.id].isAdmin;
		res.send("Login");
	}
    else if(users[req.body.id].password == req.body.password)
        res.send("PwError");
	else
		res.send("IdError");
});

app.get('/logout', function (req, res) {
	// Logout
	// 세션 유효 여부를 체크하고 세션 Delete
	if(req.session.userId != null)
	{
		req.session.destroy(function(err){});
		res.send("LogOut");
	}
	else
		res.send("Error");
});

var auth = function (req, res, next) {
	// Session Check
	// 어드민 여부 체크 필요
	if (req.session.isAdmin == true)
		next();
	else
		res.send("Error");

};
app.get('/user/:userId', auth,function (req, res) {
	// get User Information
	var userId = req.params.userId;
    console.log(users[userId]);
    res.send("OK");
});
app.post('/user', auth,function (req, res) {
	users[req.body.userId] = {
		"userId" : req.body.userId,
		"name" : req.body.name,
		"password" : req.body.password,
		"isAdmin" : false
	}
	res.send("added");
});
app.put('/user/:userId', auth,function (req, res) {
	var userId = req.params.userId;
	if (userId == users[userId].userId)
	{
		users[req.body.userId] = {
			"userId" : req.body.userId,
			"name" : req.body.name,
			"password" : req.body.password,
			"isAdmin" : req.body.isAdmin
		}
		console.log(users[userId]);
		res.send("edited");
	}
	else
		res.send("Error");
});
app.delete('/user/:userId', auth,function (req, res) {
	var userId = req.params.userId;
	delete users[userId];
	res.send("deleted");
});
// 사용자 추가 시에 admin 여부도 추가해야 함

var server = app.listen(80);