Skip to content

Commit 69c5466

Browse files
author
Your Name
committed
angular security course
1 parent 228e7c7 commit 69c5466

File tree

5 files changed

+53
-6
lines changed

5 files changed

+53
-6
lines changed

package-lock.json

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server/authorization.middleware.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
import {Request, Response, NextFunction} from 'express';
3+
import * as _ from 'lodash';
4+
5+
export function checkIfAuthorized(
6+
allowedRoles: string[],
7+
req: Request,
8+
res: Response,
9+
next: NextFunction) {
10+
11+
12+
const userInfo = req['user'];
13+
14+
const roles = _.intersection(userInfo.roles, allowedRoles);
15+
16+
if (roles.length > 0) {
17+
next();
18+
}
19+
else {
20+
res.sendStatus(403);
21+
}
22+
23+
}

server/login-as-user.route.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
3+
4+
export function loginAsUser(req, res) {
5+
6+
res.status(200).json({
7+
id:1,
8+
email:"temp@gmail.com",
9+
roles:['STUDENT']
10+
});
11+
12+
13+
}

server/security.utils.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ const SESSION_DURATION = 1000;
2323

2424

2525
export async function createSessionToken(user: DbUser) {
26-
return signJwt({},
26+
return signJwt({
27+
roles: user.roles
28+
},
2729
RSA_PRIVATE_KEY, {
2830
algorithm: 'RS256',
2931
expiresIn: 7200,

server/server.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import {login} from "./login.route";
1212
import {retrieveUserIdFromRequest} from "./get-user.middleware";
1313
import {checkIfAuthenticated} from "./authentication.middleware";
1414
import {checkCsrfToken} from "./csrf.middleware";
15-
15+
import {checkIfAuthorized} from "./authorization.middleware";
16+
import * as _ from 'lodash';
17+
import {loginAsUser} from "./login-as-user.route";
1618
const bodyParser = require('body-parser');
1719
const cookieParser = require('cookie-parser');
1820

@@ -34,7 +36,14 @@ const options = commandLineArgs(optionDefinitions);
3436

3537
// REST API
3638
app.route('/api/lessons')
37-
.get(checkIfAuthenticated, readAllLessons);
39+
.get(checkIfAuthenticated,
40+
_.partial(checkIfAuthorized,['STUDENT']),
41+
readAllLessons);
42+
43+
app.route('/api/admin')
44+
.post(checkIfAuthenticated,
45+
_.partial(checkIfAuthorized,['ADMIN']),
46+
loginAsUser);
3847

3948
app.route('/api/signup')
4049
.post(createUser);

0 commit comments

Comments
 (0)