Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CRISTAL-381: Make the github backend supported #687

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ interface AuthenticationManager {
/**
* Starts the authentication process.
*/
start(): void;
start(): Promise<void>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the signature changes, we need to update the since for this method


/**
* Handle the callback.
Expand Down
54 changes: 54 additions & 0 deletions core/authentication/authentication-github/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "@xwiki/cristal-authentication-github",
"version": "0.14.0",
"license": "LGPL 2.1",
"author": "XWiki Org Community <[email protected]>",
"homepage": "https://cristal.xwiki.org/",
"repository": {
"type": "git",
"directory": "/core/authentication/authentication-github",
"url": "https://github.com/xwiki-contrib/cristal/"
},
"bugs": {
"url": "https://jira.xwiki.org/projects/CRISTAL/"
},
"type": "module",
"exports": {
".": "./src/index.ts"
},
"main": "./src/index.ts",
"scripts": {
"build": "tsc --project tsconfig.json && vite build",
"clean": "rimraf dist",
"lint": "eslint \"./src/**/*.{ts,tsx,vue}\" --max-warnings=0",
"test": "vitest --run"
},
"dependencies": {
"@xwiki/cristal-api": "workspace:*",
"@xwiki/cristal-authentication-api": "workspace:*",
"axios": "1.7.9",
"inversify": "6.2.1",
"js-cookie": "3.0.5"
},
"peerDependencies": {
"reflect-metadata": "0.2.2"
},
"devDependencies": {
"@types/js-cookie": "3.0.6",
"@xwiki/cristal-dev-config": "workspace:*",
"reflect-metadata": "0.2.2",
"typescript": "5.7.3",
"vite": "6.0.11"
},
"publishConfig": {
"exports": {
".": {
"import": "./dist/index.es.js",
"require": "./dist/index.umd.js",
"types": "./dist/index.d.ts"
}
},
"main": "./dist/index.es.js",
"types": "./dist/index.d.ts"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
/*
* See the LICENSE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import { AuthenticationManager } from "@xwiki/cristal-authentication-api";
import axios from "axios";
import { inject, injectable } from "inversify";
import Cookies from "js-cookie";
import type { CristalApp, WikiConfig } from "@xwiki/cristal-api";
import type { UserDetails } from "@xwiki/cristal-authentication-api";
import type { CookieAttributes } from "js-cookie";

/**
* {@link AuthenticationManager} for the GitHub backend.
*
* @since 0.15
*/
@injectable()
export class GitHubAuthenticationManager implements AuthenticationManager {
constructor(
@inject<CristalApp>("CristalApp") private cristalApp: CristalApp,
) {}

private readonly localStorageDeviceCode = "authentication.device_code";

private readonly localStorageUserCode = "authentication.user_code";

private readonly localStorageExpiresIn = "authentication.expires_in";

private readonly localStorageInterval = "authentication.interval";

private readonly tokenTypeCookieKeyPrefix = "tokenType";

private readonly accessTokenCookieKeyPrefix = "accessToken";

async start(): Promise<void> {
const authorizationUrl = new URL("http://localhost:15682/device-login");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this URL be defined in the configuration?


const response = await fetch(authorizationUrl);
const jsonResponse: {
device_code: string;
user_code: string;
expires_in: number;
interval: number;
} = await response.json();

window.localStorage.setItem(
"currentConfigName",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are all the string constants defined in fields but not this one?

this.cristalApp.getWikiConfig().name,
);

window.localStorage.setItem(
this.localStorageDeviceCode,
jsonResponse.device_code,
);
window.localStorage.setItem(
this.localStorageUserCode,
jsonResponse.user_code,
);
window.localStorage.setItem(
this.localStorageExpiresIn,
jsonResponse.expires_in.toString(),
);
window.localStorage.setItem(
this.localStorageInterval,
jsonResponse.interval.toString(),
);
}

async callback(): Promise<void> {
const verificationUrl = new URL("http://localhost:15682/device-verify");
verificationUrl.searchParams.set(
"device_code",
window.localStorage.getItem(this.localStorageDeviceCode)!,
);
const configName = window.localStorage.getItem("currentConfigName")!;
const cookiesOptions: CookieAttributes = {
secure: true,
sameSite: "strict",
};

// We need to add a little more delay when polling, otherwise GitHub complains.
const interval: number =
parseInt(window.localStorage.getItem(this.localStorageInterval)!) * 1000 +
500;
let expiresIn: number =
parseInt(window.localStorage.getItem(this.localStorageExpiresIn)!) * 1000;

const intervalId = setInterval(async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block deserves an explanation, and possible to be isolated in a private method, feels hard to understand without carefully reading the code.

fetch(verificationUrl).then(async (response) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

await is preferable over then in async methods

const jsonResponse: {
error?: string;
access_token?: string;
token_type?: string;
} = await response.json();
if (!jsonResponse.error) {
Cookies.set(
this.getAccessTokenCookieKey(configName),
jsonResponse.access_token!,
cookiesOptions,
);
Cookies.set(
this.getTokenTypeCookieKey(configName),
jsonResponse.token_type!,
cookiesOptions,
);
window.location.reload();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this working on electron?

clearInterval(intervalId);
} else if (expiresIn <= 0) {
clearInterval(intervalId);
}
expiresIn -= interval;
});
}, interval);
}

async getUserDetails(): Promise<UserDetails> {
const userinfoUrl = "https://api.github.com/user";
const data = {
headers: {
Authorization: await this.getAuthorizationHeader(),
},
};
const {
data: { html_url, name, avatar_url },
} = await axios.get(userinfoUrl, data);

return { profile: html_url, name, avatar: avatar_url };
}

async logout(): Promise<void> {
// Logout is not supported through GitHub's API.
// The best we can do is to remove the stored cookies.
Cookies.remove(this.getTokenTypeCookieKey());
Cookies.remove(this.getAccessTokenCookieKey());
}

async getAuthorizationHeader(): Promise<string | undefined> {
const isAuthenticated = await this.isAuthenticated();
if (isAuthenticated) {
return `${this.getTokenType()} ${Cookies.get(this.getAccessTokenCookieKey())}`;
}
}

async isAuthenticated(): Promise<boolean> {
return (
this.getTokenType() !== undefined && this.getAccessToken() !== undefined
);
}

private getTokenType() {
return Cookies.get(this.getTokenTypeCookieKey());
}

private getAccessToken() {
return Cookies.get(this.getAccessTokenCookieKey());
}

private getAccessTokenCookieKey(configName?: string) {
const config = this.resolveConfig(configName);
return `${this.accessTokenCookieKeyPrefix}-${config?.baseURL}`;
}

private getTokenTypeCookieKey(configName?: string) {
const baseURL = this.resolveConfig(configName).baseURL;
return `${this.tokenTypeCookieKeyPrefix}-${baseURL}`;
}

private resolveConfig(configName?: string): WikiConfig {
if (configName !== undefined) {
return this.cristalApp.getAvailableConfigurations().get(configName)!;
} else {
return this.cristalApp.getWikiConfig();
}
}
}
33 changes: 33 additions & 0 deletions core/authentication/authentication-github/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* See the LICENSE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import { GitHubAuthenticationManager } from "./GitHubAuthenticationManager";
import type { AuthenticationManager } from "@xwiki/cristal-authentication-api";
import type { Container } from "inversify";

export class ComponentInit {
constructor(container: Container) {
container
.bind<AuthenticationManager>("AuthenticationManager")
.to(GitHubAuthenticationManager)
.inSingletonScope()
.whenTargetNamed("GitHub");
}
}
16 changes: 16 additions & 0 deletions core/authentication/authentication-github/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"resolveJsonModule": true
},
"extends": "../../../tsconfig.json",
"include": [
"./src/index.ts",
"./src/**/*"
],
"exclude": [
"**/*.spec.ts",
"**/*.test.ts"
]
}
4 changes: 4 additions & 0 deletions core/authentication/authentication-github/tsdoc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
"extends": ["../../../tsdoc.json"]
}
23 changes: 23 additions & 0 deletions core/authentication/authentication-github/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* See the LICENSE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import { generateConfig } from "../../../vite.config";

export default generateConfig(import.meta.url);
25 changes: 25 additions & 0 deletions core/authentication/authentication-github/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* See the LICENSE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import localConfig from "./vite.config";
import { mergeConfig } from "vitest/config";
import defaultConfig from "@xwiki/cristal-dev-config/vitest-vue.config";

export default mergeConfig(defaultConfig, localConfig);
1 change: 1 addition & 0 deletions core/authentication/authentication-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@xwiki/cristal-browser-api": "workspace:*",
"@xwiki/cristal-icons": "workspace:*",
"@xwiki/cristal-uiextension-api": "workspace:*",
"@xwiki/cristal-uiextension-default": "workspace:*",
"inversify": "6.2.1",
"vue": "3.5.13",
"vue-i18n": "11.1.0"
Expand Down
Loading
Loading