Merge pull request #13 from Sundowndev/develop

[1.0.0rc1] Task resources, Database, Client init
master
Raphael Cerveaux 2018-07-31 17:09:08 +02:00 committed by GitHub
commit 02207e6c2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 5938 additions and 37 deletions

61
client/.gitignore vendored Normal file
View File

@ -0,0 +1,61 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
#dist
dist

5517
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,26 @@
{
"name": "client",
"version": "1.0.0",
"name": "node.express.starter",
"version": "0.0.1",
"description": "",
"main": "index.js",
"main": "dist/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"build:prod": "webpack --config webpack.config.prod.js",
"build:dev": "webpack --config webpack.config.js",
"watch": "webpack-watch-server --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC"
"author": "Dr. Patrick Bartsch",
"license": "MIT",
"devDependencies": {
"uglifyjs-webpack-plugin": "^1.1.6",
"webpack": "^3.10.0"
},
"dependencies": {
"@types/express": "^4.11.0",
"express": "^4.16.2",
"ts-loader": "^3.2.0",
"twig": "^1.12.0",
"typescript": "^2.6.2",
"webpack-watch-server": "^1.2.1"
}
}

View File

@ -1,12 +0,0 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- -->
</body>
</html>

0
client/src/index.d.ts vendored Normal file
View File

24
client/src/index.js Normal file
View File

@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//import * as bodyParser from "body-parser";
const express = require("express");
const http = require("http");
let app = express();
app.set('view engine', 'twig');
app.set('views', __dirname + '/views');
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' });
});
app.get('/task/{id}', (req, res) => {
//res.render('index', {title: 'Hey', message: 'Hello there!'});
});
app.get('/task/{id}/edit', (req, res) => {
//res.render('index', {title: 'Hey', message: 'Hello there!'});
});
let httpPort = 3000;
app.set("port", httpPort);
let httpServer = http.createServer(app);
// listen on provided ports
httpServer.listen(httpPort, (data) => {
console.log(`Listening on port ${httpPort}`);
});

30
client/src/index.ts Normal file
View File

@ -0,0 +1,30 @@
//import * as bodyParser from "body-parser";
import * as express from "express";
import {Request, Response} from "express";
import * as http from 'http';
let app: express.Application = express();
app.set('view engine', 'twig');
app.set('views', __dirname + '/views');
app.get('/', (req: Request, res: Response) => {
res.render('index', {title: 'Hey', message: 'Hello there!'});
});
app.get('/task/{id}', (req: Request, res: Response) => {
//res.render('index', {title: 'Hey', message: 'Hello there!'});
});
app.get('/task/{id}/edit', (req: Request, res: Response) => {
//res.render('index', {title: 'Hey', message: 'Hello there!'});
});
let httpPort = 3000;
app.set("port", httpPort);
let httpServer = http.createServer(app);
// listen on provided ports
httpServer.listen(httpPort, (data) => {
console.log(`Listening on port ${httpPort}`)
});

123
client/src/views/index.twig Normal file
View File

@ -0,0 +1,123 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/favicon.ico">
<title>Project manager</title>
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="https://getbootstrap.com/docs/4.1/examples/offcanvas/offcanvas.css" rel="stylesheet">
</head>
<body class="bg-light">
<nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark">
<a class="navbar-brand mr-auto mr-lg-0" href="#">Project manager</a>
<button class="navbar-toggler p-0 border-0" type="button" data-toggle="offcanvas">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Sign in</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
</ul>
</div>
</nav>
<div class="nav-scroller bg-white box-shadow">
<nav class="nav nav-underline">
<a class="nav-link" href="#">Tasks</a>
<a class="nav-link" href="#">Users</a>
</nav>
</div>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<main role="main" class="container">
<div class="d-flex align-items-center p-3 my-3 text-white-50 bg-info rounded box-shadow">
<img class="mr-3" src="https://image.flaticon.com/icons/svg/138/138839.svg" alt="" width="48" height="48">
<div class="lh-100">
<h6 class="mb-0 text-white lh-100">Task manager</h6>
<small>https://github.com/Sundowndev/interview-v1</small>
</div>
</div>
<div class="my-3 p-3 bg-white rounded box-shadow">
<form action="#">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-success">Create task</button>
</form>
</div>
<div class="my-3 p-3 bg-white rounded box-shadow">
<h6 class="border-bottom border-gray pb-2 mb-0">All tasks</h6>
<div class="media text-muted pt-3">
<img src="https://dummyimage.com/32x32/54bf22/fff.jpg&text=+" alt="" class="mr-2 rounded">
<div class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<div class="d-flex justify-content-between align-items-center w-100">
<a href=""><strong class="text-gray-dark">Faire rapport de stage</strong></a>
<span class="badge badge-pill badge-primary">Open</span>
</div>
<span class="d-block">Je dois faire ça lààààà</span>
</div>
</div>
<div class="media text-muted pt-3">
<img src="https://dummyimage.com/32x32/54bf22/fff.jpg&text=+" alt="" class="mr-2 rounded">
<div class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<div class="d-flex justify-content-between align-items-center w-100">
<a href=""><strong class="text-gray-dark">Faire rapport de stage</strong></a>
<span class="badge badge-pill badge-primary">Open</span>
</div>
<span class="d-block">Je dois faire ça lààààà</span>
</div>
</div>
<div class="media text-muted pt-3">
<img src="https://dummyimage.com/32x32/54bf22/fff.jpg&text=+" alt="" class="mr-2 rounded">
<div class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<div class="d-flex justify-content-between align-items-center w-100">
<a href=""><strong class="text-gray-dark">Faire rapport de stage</strong></a>
<span class="badge badge-pill badge-primary">Open</span>
</div>
<span class="d-block">Je dois faire ça lààààà</span>
</div>
</div>
</div>
</main>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
$(".close").on('click', () => {
$(".close").alert('close');
});
</script>
</body>
</html>

8
client/tsconfig.json Normal file
View File

@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"declaration": true
}
}

37
client/webpack.config.js Normal file
View File

@ -0,0 +1,37 @@
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function (x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function (mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/index.ts',
target: 'node',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'source-map',
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{test: /\.tsx?$/, loader: 'ts-loader'}
]
},
externals: nodeModules,
node: {
__filename: true,
__dirname: true
}
};

View File

@ -0,0 +1,39 @@
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function (x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function (mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/index.ts',
target: 'node',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'source-map',
plugins: [
new UglifyJsPlugin({
test: /\.js($|\?)/i
})
],
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{ test: /\.tsx?$/, loader: 'ts-loader' }
]
},
externals: nodeModules
};

View File

@ -72,13 +72,9 @@ $router->mount('/tasks', function () use ($router) {
* User resource
*/
$router->mount('/users', function () use ($router) {
// Create user (register)
$router->post('/', 'DefaultController@index');
// Get one user
$router->get('/(\d+)', 'DefaultController@index');
$router->get('/(\d+)', 'UserController@get');
// Get one task's tasks
$router->get('/(\d+)/tasks', 'DefaultController@index');
});
$router->get('/(\d+)/tasks', 'UserController@getTasks');
});

View File

@ -5,16 +5,13 @@ SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP DATABASE IF EXISTS `app1`;
CREATE DATABASE `app1` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `app1`;
DROP TABLE IF EXISTS `Session`;
CREATE TABLE `Session` (
`user_id` int(11) NOT NULL,
`token` varchar(255) NOT NULL,
`issued_at` datetime NOT NULL,
`expire_at` datetime NOT NULL
`expire_at` datetime NOT NULL,
`ip_address` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@ -41,4 +38,4 @@ CREATE TABLE `User` (
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- 2018-07-22 00:34:19
-- 2018-07-26 15:21:32

View File

@ -54,7 +54,7 @@ class SessionController
$expire_at = new \DateTime();
$expire_at->modify('+1 Day'); // Expire in 1 day
$this->sessionRepository->create($user['id'], $token, $expire_at->format('Y-m-d H:i:s'));
$this->sessionRepository->create($user['id'], $token, $expire_at->format('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR']);
print $this->jsonResponse->create(200, 'Welcome ' . $user['name'], [
'token' => $token,
@ -62,7 +62,7 @@ class SessionController
]);
}
/**db
/**
* Register route
*/
public function signup()

View File

@ -2,7 +2,59 @@
namespace App\Controller;
use App\Repository\TaskRepository;
use App\Service\Database;
use App\Service\JsonResponse;
use App\Repository\UserRepository;
class UserController
{
//
private $db;
private $jsonResponse;
private $repository;
private $taskRepository;
public function __construct()
{
$this->db = new Database();
$this->jsonResponse = new JsonResponse();
$this->repository = new UserRepository($this->db);
$this->taskRepository = new TaskRepository($this->db);
}
/**
* Get user by id
*
* Route: /users/$id
* Method: GET
*/
public function get($id)
{
$user = $this->repository->findOneById($id) ?? [];
$code = ($user != null) ? 200 : 404;
$message = ($user != null) ? "User found." : "User not found.";
print $this->jsonResponse->create($code, $message, [
'id' => $user['id'],
'username' => $user['name'],
'email' => $user['email'],
]);
}
public function getTasks($id)
{
$user = $this->repository->findOneById($id) ?? [];
if (is_null($user)) {
$code = ($data != null) ? 200 : 404;
$message = ($data != null) ? "User found." : "User not found.";
print $this->jsonResponse->create($code, $message, []);
exit();
}
$tasks = $this->taskRepository->findByUserId($id);
print $this->jsonResponse->create(200, 'Here are the tasks.', $tasks);
}
}

View File

@ -81,12 +81,13 @@ class SessionRepository
* @param $csrf
* @param $cookie
*/
public function create($user_id, $token, $expiration)
public function create($user_id, $token, $expiration, $ip)
{
$stmt = $this->db->getConnection()->prepare('INSERT INTO Session (`user_id`, `token`, `issued_at`, `expire_at`) VALUES(:user_id, :token, NOW(), :expire_at)');
$stmt = $this->db->getConnection()->prepare('INSERT INTO Session (`user_id`, `token`, `issued_at`, `expire_at`, `ip_address`) VALUES(:user_id, :token, NOW(), :expire_at, :ip_address)');
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':token', $token);
$stmt->bindParam(':expire_at', $expiration);
$stmt->bindParam(':ip_address', $ip);
$stmt->execute();
}

View File

@ -58,6 +58,20 @@ class TaskRepository
}
}
public function findByUserId($userId){
$stmt = $this->db->getConnection()->prepare('SELECT * FROM ' . $this->tableName . ' WHERE user_id = :user_id');
$stmt->bindParam(':user_id', $userId, \PDO::PARAM_INT);
$stmt->execute();
$task = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (!$task) {
return null;
} else {
return $task;
}
}
/**
* @param $data
* @return mixed