Skip to content

Commit

Permalink
feat: implement session but cookie don't work
Browse files Browse the repository at this point in the history
  • Loading branch information
LoganTann committed Jul 3, 2022
1 parent ba1fb75 commit 9b7ea5d
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 8 deletions.
1 change: 1 addition & 0 deletions import_map.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"imports": {
"denodb": "https://raw.githubusercontent.com/Aiko-Suzuki/denodb/master/mod.ts",
"aqua": "https://deno.land/x/[email protected]/mod.ts",
"nanoid": "https://deno.land/x/[email protected]/async.ts",
"discordeno": "./deps.ts",
"config": "./config.ts",
"db": "./database/mod.ts",
Expand Down
10 changes: 9 additions & 1 deletion web-back/login/_discord.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import env from "config";

interface tokenFromCode {
access_token: string;
expires_in: number;
refresh_token: string;
scope: string;
token_type: string;
}

export default class DiscordUtils {
public static readonly oauthRedirectUrl =
"https://discord.com/api/oauth2/authorize?client_id=942097556371021924&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Flogin&response_type=code&scope=identify%20guilds";
public static readonly redirectUri = "http://localhost:3000/api/login";
public static readonly API_ENDPOINT = "https://discord.com/api/v10";

static async exchangeCode(code: string) {
static async exchangeCode(code: string): Promise<tokenFromCode> {
const data = {
client_id: env.CLIENT_ID,
client_secret: env.CLIENT_SECRET,
Expand Down
25 changes: 18 additions & 7 deletions web-back/login/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,28 @@ import DiscordUtils from "./_discord.ts";
const oauthRedirectUrl =
"https://discord.com/api/oauth2/authorize?client_id=942097556371021924&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Flogin&response_type=code&scope=identify%20guilds";

import Session from "../sessions.ts";

app.get("/api/login", async (req) => {
const session: Session = new Session(req);
const { code } = req.query;
if (!code) {
return jsonResponse(400, { redirect: oauthRedirectUrl });
}
const result = await DiscordUtils.exchangeCode(code);
// const request = await fetch("https://discord.com/api/users/@me", {
// headers: {
// authorization: `${tokenType} ${accessToken}`,
// },
// });
// const result = await request.json();
const tokenResult = await DiscordUtils.exchangeCode(code);
session.set("connected", "ok");
const request = await fetch("https://discord.com/api/users/@me", {
headers: {
authorization: `${tokenResult.token_type} ${tokenResult.access_token}`,
},
});
const result = await request.json();
return jsonResponse(200, result);
});

app.get("/api/login/sessionStatus", (req) => {
const session: Session = new Session(req);
const connected = session.get("connected");
const id = session.id;
return jsonResponse(200, { id, connected });
});
1 change: 1 addition & 0 deletions web-back/mod.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
import "./sessions.ts";
import "./lore/[name].ts";
import "./login/index.ts";
51 changes: 51 additions & 0 deletions web-back/sessions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { MiddlewareType, Request } from "aqua";
import { nanoid } from "nanoid";
import app from "./app.ts";

app.register(async (req) => {
if (Session.isSessionInvalid(req)) {
console.log("Invalid session", req.cookies["session"]);
console.log("a", req.headers.cookie);
console.log("b", req.cookies);
req.cookies["session"] = await nanoid(10);
}
return req;
}, MiddlewareType.Incoming);

app.register((req, res) => {
if (!res.cookies) {
res.cookies = {};
}
if (!res.cookies["session"]) {
res.cookies["session"] = req.cookies["session"];
}
return res;
}, MiddlewareType.Outgoing);
/**
* Memory-based session system.
*/
export default class Session {
public id: string;
private static storage: Record<string, Record<string, string>> = {};
constructor(req: Request) {
this.id = req.cookies["session"];
if (!this.id) {
throw new Error("Session id is not defined");
}
if (!Session.storage[this.id]) {
Session.storage[this.id] = {};
}
}

public static isSessionInvalid(req: Request): boolean {
const sessionId: string = req.cookies["session"] || "";
return !sessionId.match(/^[A-Za-z0-9_-]{10}$/);
}

set(key: string, value: string): void {
Session.storage[this.id][key] = value;
}
get(key: string): string {
return Session.storage[this.id][key];
}
}

0 comments on commit 9b7ea5d

Please sign in to comment.