Skip to content

Commit

Permalink
Merge pull request #13 from ebrahimmfadae/11-upgrade-dependencies
Browse files Browse the repository at this point in the history
Upgrade dependencies
  • Loading branch information
ebrahimmfadae authored Sep 14, 2023
2 parents 62220a9 + 1d099a5 commit b5a30e9
Show file tree
Hide file tree
Showing 35 changed files with 3,924 additions and 2,554 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
node_modules
.vscode
*.log
*.log
.yarn/*
!.yarn/releases
25 changes: 25 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"printWidth": 100,
"tabWidth": 4,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"overrides": [
{
"files": ["*.html"],
"options": { "parser": "vue" }
},
{
"files": ["*.{cjs,mjs,js,jsx,ts,tsx,d.ts,css,html,graphql}"],
"options": { "useTabs": true }
},
{
"files": ["*.{json,yml,yaml}"],
"options": { "tabWidth": 2 }
}
]
}
874 changes: 874 additions & 0 deletions .yarn/releases/yarn-3.6.3.cjs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
yarnPath: .yarn/releases/yarn-3.6.3.cjs
nodeLinker: node-modules
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,28 @@

The article associated to this repository is written in 4 parts plus an introduction.

- Series: [How to Implement OpenID with Node.js & Typescript & MongoDB](https://dev.to/ebrahimmfadae/setup-openid-with-nodejs-and-mongodb-451j)
- Part I: [Develop Simple OpenID Authorization Server with Node.js & Typescript](https://dev.to/ebrahimmfadae/develop-an-openid-server-with-nodejs-typescript-9n1)
- Part II: [Persist OpenID Server Data on MongoDB with Node.js](https://dev.to/ebrahimmfadae/persist-openid-server-data-with-mongodb-5f95)
- Part III: [Add Resource Server Authorization to OpenID with Node.js](https://dev.to/ebrahimmfadae/add-a-resource-server-to-an-openid-provider-noo)
- Part IV: [Set OpenID Security Configs in Node.js](https://dev.to/ebrahimmfadae/openid-security-configuration-4nn8)
- Series: [How to Implement OpenID with Node.js & Typescript & MongoDB](https://dev.to/ebrahimmfadae/setup-openid-with-nodejs-and-mongodb-451j)
- Part I: [Develop Simple OpenID Authorization Server with Node.js & Typescript](https://dev.to/ebrahimmfadae/develop-an-openid-server-with-nodejs-typescript-9n1)
- Part II: [Persist OpenID Server Data on MongoDB with Node.js](https://dev.to/ebrahimmfadae/persist-openid-server-data-with-mongodb-5f95)
- Part III: [Add Resource Server Authorization to OpenID with Node.js](https://dev.to/ebrahimmfadae/add-a-resource-server-to-an-openid-provider-noo)
- Part IV: [Set OpenID Security Configs in Node.js](https://dev.to/ebrahimmfadae/openid-security-configuration-4nn8)

## Project requirements

The project is developed and tested in this environment.

```
$ node -v
v16.17.0
v18.17.1
$ yarn -v
v1.22.19
v3.6.3
$ docker
$ docker --version
Docker version 20.10.7, build f0df350
$ docker-compose version
Docker Compose version v2.11.2
$ docker compose version
Docker Compose version v2.15.1
```

## Run & Stop
Expand Down
12 changes: 6 additions & 6 deletions api/src/controllers/api.controller.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Middleware } from "koa";
import { Middleware } from 'koa'

export default (): { [key: string]: Middleware } => ({
pi: async (ctx) => {
ctx.status = 200;
ctx.message = Math.PI.toString();
},
});
pi: async (ctx) => {
ctx.status = 200
ctx.message = Math.PI.toString()
},
})
16 changes: 8 additions & 8 deletions api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import cors from "@koa/cors";
import Koa from "koa";
import router from "./routes";
import cors from '@koa/cors'
import Koa from 'koa'
import router from './routes'

const app = new Koa();
const app = new Koa()

app.use(cors());
app.use(router().routes());
app.use(cors())
app.use(router().routes())

app.listen(process.env.PORT, () => {
console.log(`api listening on port ${process.env.PORT}`);
});
console.log(`api listening on port ${process.env.PORT}`)
})
73 changes: 33 additions & 40 deletions api/src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,37 @@
import { Middleware } from "koa";
import fetch from "node-fetch";
import { Middleware } from 'koa'

export const authenticate: Middleware = async (ctx, next) => {
const body = new URLSearchParams();
if (!ctx.request.headers.authorization) return ctx.throw(401);
body.append(
"token",
ctx.request.headers.authorization.replace(/^Bearer /, "")
);
body.append("client_id", process.env.CLIENT_ID as string);
body.append("client_secret", process.env.CLIENT_SECRET as string);
const url = `${process.env.OIDC_ISSUER}/token/introspection`;
const response = await fetch(url, {
method: "POST",
headers: {
["Content-Type"]: "application/x-www-form-urlencoded",
},
body: body,
});
if (response.status !== 200) ctx.throw(401);
const json = await response.json();
const { active, aud } = json;
// Resource URI and audience (aud) must be equal
if (active && aud.trim() === ctx.request.href.split("?")[0]) {
ctx.state.session = json;
await next();
} else {
ctx.throw(401);
}
};
const body = new URLSearchParams()
if (!ctx.request.headers.authorization) return ctx.throw(401)
body.append('token', ctx.request.headers.authorization.replace(/^Bearer /, ''))
body.append('client_id', process.env.CLIENT_ID as string)
body.append('client_secret', process.env.CLIENT_SECRET as string)
const url = `${process.env.OIDC_ISSUER}/token/introspection`
const response = await fetch(url, {
method: 'POST',
headers: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
body: body,
})
if (response.status !== 200) ctx.throw(401)
const json = await response.json()
const { active, aud } = json
// Resource URI and audience (aud) must be equal
if (active && aud.trim() === ctx.request.href.split('?')[0]) {
ctx.state.session = json
await next()
} else {
ctx.throw(401)
}
}

export const authorize =
(...scopes: string[]): Middleware =>
async (ctx, next) => {
if (
ctx.state.session &&
scopes.every((scope) => ctx.state.session.scope.includes(scope))
) {
await next();
} else {
ctx.throw(401);
}
};
(...scopes: string[]): Middleware =>
async (ctx, next) => {
if (ctx.state.session && scopes.every((scope) => ctx.state.session.scope.includes(scope))) {
await next()
} else {
ctx.throw(401)
}
}
16 changes: 8 additions & 8 deletions api/src/routes/api.router.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import Router from "koa-router";
import apiController from "../controllers/api.controller";
import { authenticate, authorize } from "../middlewares/auth.middleware";
import Router from 'koa-router'
import apiController from '../controllers/api.controller'
import { authenticate, authorize } from '../middlewares/auth.middleware'

export default () => {
const router = new Router();
const router = new Router()

const { pi } = apiController();
const { pi } = apiController()

router.get("/pi", authenticate, authorize("api:read"), pi);
router.get('/pi', authenticate, authorize('api:read'), pi)

return router;
};
return router
}
12 changes: 6 additions & 6 deletions api/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import Router from "koa-router";
import appRouter from "./api.router";
import Router from 'koa-router'
import appRouter from './api.router'

export default () => {
const router = new Router();
const router = new Router()

router.use(appRouter().routes());
router.use(appRouter().routes())

return router;
};
return router
}
102 changes: 51 additions & 51 deletions app/src/controllers/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,53 @@
import { Middleware } from "koa";
import { Middleware } from 'koa'

export default (): { [key: string]: Middleware } => ({
registerForm: async (ctx) => {
return ctx.render("register", {
title: "Register User",
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
});
},
callback: async (ctx) => {
if ("error" in ctx.query) {
ctx.throw(401, `${ctx.query.error}: ${ctx.query.error_description}`);
} else {
return ctx.render("token", {
code: ctx.query.code,
title: "App Callback",
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
appUrl: process.env.PUBLIC_APP_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
}
},
sampleApp: async (ctx) => {
return ctx.render("sample-app", {
title: "Sample App",
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
apiUrl: process.env.PUBLIC_API_URL,
appUrl: process.env.PUBLIC_APP_URL,
clientId: process.env.CLIENT_ID,
});
},
signIn: async (ctx) => {
return ctx.render("sign-in", {
title: "Get Token With Credentials",
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
apiUrl: process.env.PUBLIC_API_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
},
clientLogin: async (ctx) => {
return ctx.render("client-login", {
title: "Client Login",
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
},
pi: async (ctx) => {
return ctx.render("pi", { title: "PI", apiUrl: process.env.PUBLIC_API_URL });
},
});
registerForm: async (ctx) => {
return ctx.render('register', {
title: 'Register User',
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
})
},
callback: async (ctx) => {
if ('error' in ctx.query) {
ctx.throw(401, `${ctx.query.error}: ${ctx.query.error_description}`)
} else {
return ctx.render('token', {
code: ctx.query.code,
title: 'App Callback',
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
appUrl: process.env.PUBLIC_APP_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
})
}
},
sampleApp: async (ctx) => {
return ctx.render('sample-app', {
title: 'Sample App',
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
apiUrl: process.env.PUBLIC_API_URL,
appUrl: process.env.PUBLIC_APP_URL,
clientId: process.env.CLIENT_ID,
})
},
signIn: async (ctx) => {
return ctx.render('sign-in', {
title: 'Get Token With Credentials',
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
apiUrl: process.env.PUBLIC_API_URL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
})
},
clientLogin: async (ctx) => {
return ctx.render('client-login', {
title: 'Client Login',
authServerUrl: process.env.PUBLIC_OIDC_ISSUER,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
})
},
pi: async (ctx) => {
return ctx.render('pi', { title: 'PI', apiUrl: process.env.PUBLIC_API_URL })
},
})
30 changes: 15 additions & 15 deletions app/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import Koa from "koa";
import render from "koa-ejs";
import koaStatic from "koa-static";
import path from "path";
import router from "./routes";
import Koa from 'koa'
import render from 'koa-ejs'
import koaStatic from 'koa-static'
import path from 'path'
import router from './routes'

const app = new Koa();
const app = new Koa()
render(app, {
cache: false,
viewExt: "ejs",
layout: false,
root: path.resolve("app/src/views"),
});
cache: false,
viewExt: 'ejs',
layout: false,
root: path.resolve('app/src/views'),
})

app.use(koaStatic(path.resolve("public")));
app.use(router().routes());
app.use(koaStatic(path.resolve('public')))
app.use(router().routes())

app.listen(process.env.PORT, () => {
console.log(`sample-app listening on port ${process.env.PORT}`);
});
console.log(`sample-app listening on port ${process.env.PORT}`)
})
Loading

0 comments on commit b5a30e9

Please sign in to comment.