Skip to content

Commit

Permalink
trying to get auth redirects to work
Browse files Browse the repository at this point in the history
  • Loading branch information
codelirik committed Dec 8, 2022
1 parent f50a1a7 commit 2fd48f6
Show file tree
Hide file tree
Showing 20 changed files with 219 additions and 20 deletions.
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,9 @@ dist
.tern-port

# WebStorm
.idea
.idea

# Emacs (Yes there are still people out there using it)
*~
\#*\#
\.#*
3 changes: 3 additions & 0 deletions client/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<RouterLink to="/auth" class="nav-link">Login</RouterLink>
</li>
<li class="nav-item">
<RouterLink to="/" class="nav-link">Home</RouterLink>
<!-- <a class="nav-link active" aria-current="page" href="#">Home</a> -->
Expand Down
5 changes: 5 additions & 0 deletions client/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ const router = createRouter({
name: "home",
component: () => import("@/views/HomeView.vue"),
},
{
path: "/auth",
name: "authenticate",
component: () => import("@/views/AuthView.vue"),
},
{
path: "/posts",
name: "posts",
Expand Down
25 changes: 25 additions & 0 deletions client/src/views/AuthView.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<template>
<div id="login" class="">
<h2>Login</h2>
<button @click="login" class="">Login</button>
</div>
</template>

<script>
export default {
name: "AuthView",
methods: {
login: async () => {
const authRequest = new Request("http://localhost:5000/auth/login",{
method: "GET"
});
const response = await fetch(authRequest);
console.log(response);
}
}
}
</script>

<style scoped>
</style>
2 changes: 1 addition & 1 deletion client/src/views/PostFormView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
import { defineComponent, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import MarkDown from "../components/MarkDown.vue";
import { debounce } from "./../debounce";
import { debounce } from "@/debounce";
export default defineComponent({
components: { MarkDown },
Expand Down
84 changes: 82 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,8 @@
"license": "Apache-2.0",
"devDependencies": {
"concurrently": "^7.5.0"
},
"dependencies": {
"dotenv": "^16.0.3"
}
}
4 changes: 4 additions & 0 deletions server/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
APP_HOST=null
APP_PORT=null
OAUTH_CLIENT_ID=null
OAUTH_CLIENT_SECRET=null
5 changes: 3 additions & 2 deletions server/.eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"sourceType": "module"
},
"rules": {
"quotes": [2, "double", "avoid-escape"]
"quotes": [2, "double", "avoid-escape"],
"object-curly-spacing": ["error", "always"]
}
}
}
16 changes: 15 additions & 1 deletion server/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
## Common ##

### Managing environment variables ###

* To load environment variables into the application we use an external library - [dotenv](https://www.npmjs.com/package/dotenv) `npm i dotenv`
* It relies on a file called `.env` where the key-value pairs are defined.
* We also use node's / ts-node's `--require (-r)` command line option to preload the library. By doing this we do not need to load dotenv in our applicaion -
thus `require("dotenv")` or `import dotenv from "dotenv"` is not necessary.
* We provide an environemt variables declaration file called `env.template`.
* Copy `.env.template` to `.env` and provide your own valid values.
* Your scripts must be adapted correspondingly `ts-node -r dotenv/config your-script.js`

## TypeORM

To create a new migration use the following:
Expand All @@ -10,4 +22,6 @@ All entities are currently run automatically upon starting the node server. To c

- Datasource configuration: `./src/data-source.ts`

- Example usage of the entity manager: `await AppDataSource.manager.getRepository(Post)`
- Example usage of the entity manager: `await AppDataSource.manager.getRepository(Post)`

## OAuth ##
4 changes: 3 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Backend Server for Blog in Node/Express",
"main": "index.js",
"scripts": {
"dev": "nodemon ./src/server.ts",
"dev": "nodemon -r dotenv/config ./src/server.ts",
"build": "tsc",
"lint": "eslint src/**/*.ts",
"format": "eslint src/**/*.ts --fix",
Expand All @@ -30,6 +30,7 @@
"dependencies": {
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"common": "../common",
"pg": "^8.4.0",
Expand All @@ -48,6 +49,7 @@
"@typescript-eslint/eslint-plugin": "^5.42.1",
"@typescript-eslint/parser": "^5.42.1",
"nodemon": "^2.0.20",
"openid-client": "^5.3.1",
"prettier": "^2.7.1",
"ts-node": "10.9.1",
"typescript": "4.9.3"
Expand Down
22 changes: 22 additions & 0 deletions server/src/auth/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextFunction, Request, Response } from "express";
import { Issuer } from "openid-client";

export async function init(req: Request, res: Response, next: NextFunction) {
const initialized = !!req.app.authIssuer && req.app.authClient;
if (!initialized) {
const issuer = await Issuer.discover("https://accounts.google.com");
const client = new issuer.Client({
client_id: process.env.OAUTH_CLIENT_ID!,
client_secret: process.env.OAUTH_CLIENT_SECRET!,
redirect_uris: [`${getDomain()}/auth/callback`],
response_types: ["code"]
});
req.app.authIssuer = issuer;
req.app.authClient = client;
}
next();
}

export function getDomain(): string {
return `http://${process.env.APP_HOST}:${process.env.APP_PORT}`;
}
4 changes: 2 additions & 2 deletions server/src/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm"
import {User} from "./User";
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User";

/**
* Blog post
Expand Down
2 changes: 1 addition & 1 deletion server/src/migration/1668524133068-CreatePosts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {MigrationInterface, QueryRunner, Table} from "typeorm"
import { MigrationInterface, QueryRunner, Table } from "typeorm"

export class CreatePosts1668524133068 implements MigrationInterface {

Expand Down
2 changes: 1 addition & 1 deletion server/src/migration/1668591563832-CreateUser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {MigrationInterface, QueryRunner, Table, TableColumn, TableForeignKey} from "typeorm"
import { MigrationInterface, QueryRunner, Table, TableColumn, TableForeignKey } from "typeorm"

export class CreateUser1668591563832 implements MigrationInterface {

Expand Down
17 changes: 17 additions & 0 deletions server/src/routes/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import express, { Request, Response, Router } from "express";

// This is local instance of express' router that is scoped to the current (controller) module.
// It is probably a good idea to crate a singleton in an extra module that can be referenced (imported) by all
// controllers
const router: Router = express.Router();

router.get("/login", (req: Request, res: Response) => {
const authUrl = req.app.authClient!.authorizationUrl({
scope: "openid email profile"
});
// console.log("REDIRECTING URIS: ", req.app.authClient?.metadata.redirect_uris);
console.log("REDIRECTING TO: ", authUrl);
res.redirect(authUrl);
});

export default router;
3 changes: 1 addition & 2 deletions server/src/routes/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ router.get("/", async (req: Request, res: Response) => {
res.status(200).json({ data: sortedPosts });
});


// GET POST BY ID
router.get("/:id", async (req: Request, res: Response) => {
const post = await AppDataSource.manager.getRepository(Post).findOneBy({
Expand Down Expand Up @@ -107,4 +106,4 @@ router.get("/delete/:id", async (req: Request, res: Response) => {
}
});

export default router;
export default router;
Loading

0 comments on commit 2fd48f6

Please sign in to comment.