Skip to content

Commit

Permalink
set up server and create user registration
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzzwen committed Jan 18, 2017
1 parent 6737991 commit def98c5
Show file tree
Hide file tree
Showing 8 changed files with 247 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Compiled classfiles
bin/
*.class

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.ear

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# IDEA files
.idea/
*.iml

# Node modules
backend/node_modules/
14 changes: 14 additions & 0 deletions backend/database.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"dev": {
"driver": "mysql",
"user": "root",
"database": "test",
"password": "root"
},

"production": {
"driver": "mysql",
"user": "root",
"database": "myapp"
}
}
14 changes: 14 additions & 0 deletions backend/database.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE DATABASE `tutorial` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `tutorial`;


CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

19 changes: 19 additions & 0 deletions backend/models/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
var Sequelize = require('sequelize');

// db config
var env = "dev";
var config = require('../database.json')[env];
var password = config.password ? config.password : null;

module.exports = new Sequelize(
config.database,
config.user,
config.password,
{
dialect: config.driver,
logging: console.log,
define: {
timestamps: false
}
}
);
46 changes: 46 additions & 0 deletions backend/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
var sequelize = require('./db.js');

var crypto = require('crypto');
var DataTypes = require("sequelize");

var User = sequelize.define('users', {
username: DataTypes.STRING,
password: DataTypes.STRING
}, {
instanceMethods: {
retrieveAll: function(onSuccess, onError) {
User.findAll({}, {raw: true}).then(onSuccess).catch(onError);
},
retrieveById: function(user_id, onSuccess, onError) {
User.find({where: {id: user_id}}, {raw: true}).then(onSuccess).catch(onError);
},
add: function(onSuccess, onError) {
var username = this.username;
var password = this.password;

var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');

User.build({ username: username, password: password })
.save().then(onSuccess).catch(onError);
},
updateById: function(user_id, onSuccess, onError) {
var id = user_id;
var username = this.username;
var password = this.password;

var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');

User.update({ username: username,password: password},{where: {id: id} })
.then(onSuccess).catch(onError);
},
removeById: function(user_id, onSuccess, onError) {
User.destroy({where: {id: user_id}}).then(onSuccess).catch(onError);
}
}
});

module.exports = User;
12 changes: 12 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "node-api",
"main": "server.js",
"dependencies": {
"express": "~4.0.0",
"body-parser": "~1.0.1",
"mysql": "~2.5.0",
"sequelize": "~2.0.0",
"crypto": "~0.0.3",
"morgan": "~1.7.0"
}
}
92 changes: 92 additions & 0 deletions backend/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
var express = require('express');
var router = express.Router();
var User = require('../models/user.js');
// on routes that end in /users
// ----------------------------------------------------
router.route('/users')

// create a user (accessed at POST http://localhost:8080/api/users)
.post(function(req, res) {
var username = req.body.username; //bodyParser does the magic
var password = req.body.password;

var user = User.build({ username: username, password: password });

user.add(function(success){
res.json({ message: 'User created!' });
},
function(err) {
res.send(err);
});
})

// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
var user = User.build();

user.retrieveAll(function(users) {
if (users) {
res.json(users);
} else {
res.send(401, "User not found");
}
}, function(error) {
res.send("User not found");
});
});


// on routes that end in /users/:user_id
// ----------------------------------------------------
router.route('/users/:user_id')

// update a user (accessed at PUT http://localhost:8080/api/users/:user_id)
.put(function(req, res) {
var user = User.build();

user.username = req.body.username;
user.password = req.body.password;

user.updateById(req.params.user_id, function(success) {
console.log(success);
if (success) {
res.json({ message: 'User updated!' });
} else {
res.send(401, "User not found");
}
}, function(error) {
res.send("User not found");
});
})

// get a user by id(accessed at GET http://localhost:8080/api/users/:user_id)
.get(function(req, res) {
var user = User.build();

user.retrieveById(req.params.user_id, function(users) {
if (users) {
res.json(users);
} else {
res.send(401, "User not found");
}
}, function(error) {
res.send("User not found");
});
})

// delete a user by id (accessed at DELETE http://localhost:port/api/users/:user_id)
.delete(function(req, res) {
var user = User.build();

user.removeById(req.params.user_id, function(users) {
if (users) {
res.json({ message: 'User removed!' });
} else {
res.send(401, "User not found");
}
}, function(error) {
res.send("User not found");
});
});

module.exports = router;
29 changes: 29 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.set('port', process.env.PORT || 3355);
app.use(logger('dev'));

var env = app.get('env') == 'development' ? 'dev' : app.get('env');

var User = require('./models/user.js');

// IMPORT ROUTES
// =============================================================================
var router = require('./routes/index.js');

// Middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});

app.use('/api', router);

app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});

0 comments on commit def98c5

Please sign in to comment.