Skip to content

Commit 7254e18

Browse files
Dan WahlinDan Wahlin
Dan Wahlin
authored and
Dan Wahlin
committed
Added csurf support, tokens api and updated client-side.
1 parent f44632a commit 7254e18

File tree

9 files changed

+96
-43
lines changed

9 files changed

+96
-43
lines changed

.vscode/settings.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,6 @@
44
"**/app/**/*.js.map": true,
55
"**/app/**/*.js": true
66
}
7+
,
8+
"typescript.tsdk": "./node_modules/typescript/lib"
79
}

controllers/api/customers/customers.controller.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
var customersRepo = require('../../../lib/customersRepository'),
2-
statesRepo = require('../../../lib/statesRepository'),
3-
util = require('util');
1+
const customersRepo = require('../../../lib/customersRepository'),
2+
statesRepo = require('../../../lib/statesRepository'),
3+
util = require('util');
44

55
class CustomersController {
66

@@ -65,12 +65,12 @@ class CustomersController {
6565

6666
insertCustomer(req, res) {
6767
console.log('*** insertCustomer');
68-
statesRepo.getState(req.body.stateId, function (err, state) {
68+
statesRepo.getState(req.body.stateId, (err, state) => {
6969
if (err) {
7070
console.log('*** statesRepo.getState error: ' + util.inspect(err));
7171
res.json({ 'status': false });
7272
} else {
73-
customersRepo.insertCustomer(req.body, state, function (err) {
73+
customersRepo.insertCustomer(req.body, state, (err) => {
7474
if (err) {
7575
console.log('*** customersRepo.insertCustomer error: ' + util.inspect(err));
7676
res.json(false);
@@ -92,12 +92,12 @@ class CustomersController {
9292
throw new Error('Customer and associated stateId required');
9393
}
9494

95-
statesRepo.getState(req.body.stateId, function (err, state) {
95+
statesRepo.getState(req.body.stateId, (err, state) => {
9696
if (err) {
9797
console.log('*** statesRepo.getState error: ' + util.inspect(err));
9898
res.json({ 'status': false });
9999
} else {
100-
customersRepo.updateCustomer(req.params.id, req.body, state, function (err) {
100+
customersRepo.updateCustomer(req.params.id, req.body, state, (err) => {
101101
if (err) {
102102
console.log('*** updateCustomer error: ' + util.inspect(err));
103103
res.json({ 'status': false });
@@ -113,7 +113,7 @@ class CustomersController {
113113
deleteCustomer(req, res) {
114114
console.log('*** deleteCustomer');
115115

116-
customersRepo.deleteCustomer(req.params.id, function (err) {
116+
customersRepo.deleteCustomer(req.params.id, (err) => {
117117
if (err) {
118118
console.log('*** deleteCustomer error: ' + util.inspect(err));
119119
res.json({ 'status': false });

controllers/api/states/states.controller.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
var statesRepo = require('../../../lib/statesRepository'),
2-
util = require('util');
1+
const statesRepo = require('../../../lib/statesRepository'),
2+
util = require('util');
33

44
class StatesController {
55

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const util = require('util');
2+
3+
class TokensController {
4+
5+
constructor(router) {
6+
router.get('/csrf', this.getCsrfToken.bind(this));
7+
}
8+
9+
getCsrfToken(req, res) {
10+
console.log('*** getCsrfToken');
11+
const csrfToken = res.locals._csrf;
12+
res.json({ csrfToken: csrfToken });
13+
}
14+
}
15+
16+
module.exports = TokensController;

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
"devDependencies": {
4444
"concurrently": "^3.1.0",
4545
"lite-server": "^2.2.2",
46-
"typescript": "2.0.3",
46+
"typescript": "2.0.8",
4747
"del": "^2.2.2",
4848
"gulp": "^3.9.1",
4949
"gulp-concat": "^2.6.0",

public/app/core/data.service.ts

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Injectable } from '@angular/core';
2-
import { Http, Response } from '@angular/http';
2+
import { Http, Headers, Response, RequestOptions } from '@angular/http';
33

44
//Grab everything with import 'rxjs/Rx';
55
import { Observable } from 'rxjs/Observable';
@@ -13,8 +13,21 @@ import { ICustomer, IOrder, IState } from '../shared/interfaces';
1313
export class DataService {
1414

1515
baseUrl: string = '/api/customers';
16+
csrfToken: string = null;
1617

17-
constructor(private http: Http) { }
18+
constructor(private http: Http) {
19+
this.getCsrfToken();
20+
}
21+
22+
getCsrfToken() {
23+
return this.http.get('/api/tokens/csrf')
24+
.map((res: Response) => res.json().csrfToken)
25+
.catch(this.handleError)
26+
.subscribe((token: string) => {
27+
this.csrfToken = token;
28+
},
29+
(err) => console.log(err));
30+
}
1831

1932
getCustomers() : Observable<ICustomer[]> {
2033
return this.http.get(this.baseUrl)
@@ -47,24 +60,32 @@ export class DataService {
4760
}
4861

4962
insertCustomer(customer: ICustomer) : Observable<ICustomer> {
50-
return this.http.post(this.baseUrl, customer)
63+
return this.http.post(this.baseUrl, customer, this.getRequestOptions())
5164
.map((res: Response) => {
5265
return res.json();
5366
})
5467
.catch(this.handleError);
5568
}
5669

5770
updateCustomer(customer: ICustomer) : Observable<boolean> {
58-
return this.http.put(this.baseUrl + '/' + customer._id, customer)
71+
return this.http.put(this.baseUrl + '/' + customer._id, customer, this.getRequestOptions())
5972
.map((res: Response) => res.json())
6073
.catch(this.handleError);
6174
}
6275

6376
deleteCustomer(id: string) : Observable<boolean> {
64-
return this.http.delete(this.baseUrl + '/' + id)
77+
78+
return this.http.delete(`${this.baseUrl}/${id}?_csrf=${this.csrfToken}`, this.getRequestOptions())
6579
.map((res: Response) => res.json())
6680
.catch(this.handleError);
6781
}
82+
83+
getRequestOptions() {
84+
const options = new RequestOptions({
85+
headers: new Headers({ 'csrf-token': this.csrfToken })
86+
});
87+
return options;
88+
}
6889

6990
getStates(): Observable<IState[]> {
7091
return this.http.get('/api/states')

public/app/customers/customer-edit.component.ts

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,18 +39,30 @@ export class CustomerEditComponent implements OnInit {
3939
let id = this.route.snapshot.params['id'];
4040
if (id !== '0') {
4141
this.operationText = 'Update';
42-
this.dataService.getCustomer(id).subscribe((customer: ICustomer) => {
43-
//Quick and dirty clone used in case user cancels out of form
44-
const cust = JSON.stringify(customer);
45-
this.customer = JSON.parse(cust);
46-
});
42+
this.getCustomer(id);
4743
}
4844

45+
this.getStates();
46+
}
47+
48+
getCustomer(id: string) {
49+
this.dataService.getCustomer(id)
50+
.subscribe((customer: ICustomer) => {
51+
//Quick and dirty clone used in case user cancels out of form
52+
const cust = JSON.stringify(customer);
53+
this.customer = JSON.parse(cust);
54+
},
55+
(err) => console.log(err));
56+
}
57+
58+
getStates() {
4959
this.dataService.getStates().subscribe((states: IState[]) => this.states = states);
5060
}
5161

5262
submit() {
63+
5364
if (this.customer._id) {
65+
5466
this.dataService.updateCustomer(this.customer)
5567
.subscribe((status: boolean) => {
5668
if (status) {
@@ -59,8 +71,11 @@ export class CustomerEditComponent implements OnInit {
5971
else {
6072
this.errorMessage = 'Unable to save customer';
6173
}
62-
});
74+
},
75+
(err) => console.log(err));
76+
6377
} else {
78+
6479
this.dataService.insertCustomer(this.customer)
6580
.subscribe((customer: ICustomer) => {
6681
if (customer) {
@@ -69,7 +84,9 @@ export class CustomerEditComponent implements OnInit {
6984
else {
7085
this.errorMessage = 'Unable to add customer';
7186
}
72-
});
87+
},
88+
(err) => console.log(err));
89+
7390
}
7491
}
7592

@@ -88,7 +105,8 @@ export class CustomerEditComponent implements OnInit {
88105
else {
89106
this.errorMessage = 'Unable to delete customer';
90107
}
91-
});
108+
},
109+
(err) => console.log(err));
92110
}
93111

94112
}

public/app/customers/customers.component.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,6 @@ export class CustomersComponent implements OnInit {
2626
ngOnInit() {
2727
this.title = 'Customers';
2828
this.getCustomersPage(1);
29-
30-
// this.dataService.getCustomers()
31-
// .subscribe((customers: ICustomer[]) => {
32-
// this.customers = this.filteredCustomers = customers;
33-
// });
34-
3529
}
3630

3731
filterChanged(filterText: string) {
@@ -53,7 +47,9 @@ export class CustomersComponent implements OnInit {
5347
.subscribe((response: IPagedResults<ICustomer[]>) => {
5448
this.customers = this.filteredCustomers = response.results;
5549
this.totalRecords = response.totalRecords;
56-
});
50+
},
51+
(err: any) => console.log(err),
52+
() => console.log('getCustomersPage() retrieved customers'));
5753
}
5854

5955
}

server.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,23 +41,22 @@ class Server {
4141
}
4242

4343
initExpressMiddleWare() {
44-
// app.use(session({
45-
// secret: 'customermanagerdemo',
46-
// saveUninitialized: true,
47-
// resave: true }));
4844
app.use(cookieParser());
4945
app.use(bodyParser.urlencoded({ extended: true }));
5046
app.use(bodyParser.json());
47+
app.use(session({
48+
secret: 'customermanagerdemo',
49+
saveUninitialized: true,
50+
resave: true })
51+
);
5152
app.use(express.static(__dirname + '/public'));
5253
app.use(errorhandler());
53-
// app.use(csrf());
54+
app.use(csrf());
5455

55-
// app.use(function (req, res, next) {
56-
// var csrf = req.csrfToken();
57-
// res.cookie('XSRF-TOKEN', csrf);
58-
// res.locals._csrf = csrf;
59-
// next();
60-
// });
56+
app.use(function (req, res, next) {
57+
res.locals._csrf = req.csrfToken();
58+
next();
59+
});
6160

6261
process.on('uncaughtException', function (err) {
6362
if (err) console.log(err, err.stack);
@@ -86,8 +85,9 @@ class Server {
8685
//Set NODE_ENV to 'development' and uncomment the following if to only run
8786
//the seeder when in dev mode
8887
//if (process.env.NODE_ENV === 'development') {
89-
seeder.init();
88+
// seeder.init();
9089
//}
90+
seeder.init();
9191
});
9292
}
9393

0 commit comments

Comments
 (0)