Skip to content
This repository has been archived by the owner on Sep 8, 2021. It is now read-only.

[Hannkim, jikwon] - Best of Best #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions back/accountController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
'use strict';

const models = require('./models/index.js');
const jwt = require('jsonwebtoken');
const idValidator = require('./idvalidator.js');
const passValidator = require('./passvalidator.js');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const env = process.env;
const token = require('./token.js');

function setStatusMsg(res, scode, content)
{
res.status(scode);
res.send({msg:content});
res.end();
}

async function createNewUser(req)
{
bcrypt.genSalt(saltRounds, (err, salt)=>{
bcrypt.hash(req.body.password, salt, function(err, hash){
models.User.create({id:req.body.id, password:hash});
})
});
}

function userSignUp(req, res, next)
{
if (!idValidator(req.body.id))
return (setStatusMsg(res, 400, "userid"));
if (!passValidator(req.body.password))
return (setStatusMsg(res, 400, "password"));
models.User.findOne({where: {id : req.body.id}})
.then((result) =>{
if (result == null)
{
console.log("data is created");
createNewUser(req)
.then(()=>{setStatusMsg(res, 201, "Successfully signed up");})
.catch(()=>{setStatusMsg(res, 500, "Server error");});
}
else
{
console.log("confilct");
setStatusMsg(res, 409, "Conflict: The user is already registered");
}})
.catch((err)=>{
console.log(err);
setStatusMsg(res, 500, "Server Error");});
}


async function userSignIn(req, res, next)
{
if (!req.body.id || !req.body.password)
return setStatusMsg(res, 400, "Bad Request");
try
{
const user = await models.User.findOne({where: {id: req.body.id}});
if (!user)
return setStatusMsg(res, 401, "Wrong userid or password");
bcrypt.compare(req.body.password, user.password, (err, result)=>{
if (result == true)
{
console.log("success: log-in");
res.cookie('jwt_access', token.issue(user.index, "30m"), {maxAge:30 *60 * 1000});
const refresh = token.issue(user.index, "7d");
res.cookie('jwt_refresh', refresh, {maxAge: 7 * 60 * 60 * 1000});
user.update({'jwtkey' : refresh});
setStatusMsg(res, 200, "Successfully signed in");
}
else
{
console.log("fail : log-in");
setStatusMsg(res, 401, "Wrong userid or password");
}});
}
catch (err)
{
console.log(err);
setStatusMsg(res, 500, "Server Error");
}


}

function userSignOut(req, res, next)
{
console.log("SIGN-OUT");
const jwt_access = req.cookies.jwt_access;
const jwt_refresh = req.cookies.jwt_refresh;
if (!jwt_access || !jwt_refresh)
return setStatusMsg(res, 401, "Not signed in");
token.verify(jwt_access)
.then(async (decoded_data)=>{
const user = await models.User.findOne({where : {index : decoded_data["sub"]}});
if (jwt_refresh !== user.jwtkey)
return (setStatusMsg(res, 401, "Not signed in"));
user.update({'jwtkey' : null});
res.cookie('jwt_access', token.issue('', "0ms"), {maxAge : 0});
res.cookie('jwt_refresh', token.issue('', "0ms"), {maxAge : 0});
setStatusMsg(res, 200, "Succesfully signed out");
})
.catch((err)=>{
console.log(err);
setStatusMsg(res, 401, "Not signed in");
})
}

module.exports = {userSignUp, userSignIn, userSignOut}
20 changes: 20 additions & 0 deletions back/config/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
require('dotenv').config({path : './config/.env'});
const env = process.env;

const development = {
"username": env.MYSQL_DBUSER,
"password": env.MYSQL_DBPASS,
"database": env.MYSQL_DBNAME,
"host": env.MYSQL_DBHOST,
"dialect": env.MYSQL_DIALECT
};

const production = {
"username": env.MYSQL_DBUSER,
"password": env.MYSQL_DBPASS,
"database": env.MYSQL_DBNAME,
"host": env.MYSQL_DBHOST,
"dialect": env.MYSQL_DIALECT
};

module.exports = {development, production};
12 changes: 12 additions & 0 deletions back/idvalidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const list = "0123456789abcdefghijklmnopqrstuvwxyz";
module.exports = function idValidator (str) {

if (!str || str.length <= 0 || str.length > 8)
return (false);
for (i in str)
{
if (list.indexOf(str[i]) == -1)
return (false);
}
return (true);
}
35 changes: 35 additions & 0 deletions back/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const express = require('express');
const app = express(); //server create
const cookieParser = require('cookie-parser');
const {sequelize} = require('./models/index');
const router = require('./route.js');
const cors = require('cors');
const port = process.env.EXPRESS_PORT;

async function main()
{
const driver = ()=>{
sequelize.sync({})
.then(()=>{console.log("init table");})
.catch((err)=>{console.log(err);})
}
try
{
await sequelize.authenticate();
console.log("DB connected successfully");
await driver();
}
catch (err)
{
console.error(err);
}
let corsOptions = {
origin: "http://localhost:4200"
}
app.use(express.json());
app.use(cookieParser());
app.use('/', cors(corsOptions), router);
app.listen(port, ()=>{});
}

main();
34 changes: 34 additions & 0 deletions back/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module.exports = function (sequelize, DataTypes) {
let user = sequelize.define("User", {
index : {
filled : "index",
type: DataTypes.INTEGER,
unique: true,
allowNull: false,
autoIncrement : true
},
id : {
filled : "id",
type: DataTypes.STRING(8),
unique: true,
allowNull: false,
primaryKey: true
},
jwtkey : {
filed : "jwtkey",
type: DataTypes.STRING(150),
allowNull : true
},
password: {
filled: "pass",
type: DataTypes.STRING(100),
allowNull: false
}},
{
charset: "utf8",
freezeTableName: true,
tableName: "User",
timestamps: true
});
return user;
}
37 changes: 37 additions & 0 deletions back/models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
Loading