diff --git a/src/api.test.ts b/src/api.test.ts index 81f1fbd..34ae3c2 100644 --- a/src/api.test.ts +++ b/src/api.test.ts @@ -1,11 +1,23 @@ import Forgejo from "./api"; import authtoken from "../secrets/user1-accesstoken.json"; +const token = authtoken["sha1"]; +const username = authtoken["login"]; + test("use authentication without setting it ", () => { const api = new Forgejo("http://localhost:3000", "owner_user"); - const token = authtoken["sha1"] expect(() => api.getTokenAuth()).toThrow(); - api.setTokenAuth(token) - expect(api.getTokenAuth().getToken()).toBe(token) + api.setTokenAuth(token); + expect(api.getTokenAuth().getToken()).toBe(token); + let headers = api.getTokenAuthHeader(); + expect(headers.Authorization).toBe(`token ${token}`); +}); + +test("verify /user API ", async () => { + const api = new Forgejo("http://localhost:3000", "owner_user"); + api.setTokenAuth(token); + let user = await api.getUser(); + console.log(user); + expect(user["login"]).toBe(username); }); diff --git a/src/api.ts b/src/api.ts index 7242fd0..e560286 100644 --- a/src/api.ts +++ b/src/api.ts @@ -16,6 +16,7 @@ class Forgejo { */ constructor(url: string, username: string) { this.url = new URL(url); + console.log(this.url.toString()); this.username = username; } @@ -25,7 +26,6 @@ class Forgejo { */ setTokenAuth(token: string) { this.token = new Auth(token); - console.log(this.token.getToken()) } getTokenAuth(): Auth { @@ -37,7 +37,22 @@ class Forgejo { } getTokenAuthHeader() { - return { Authentication: `Bearer ${this.getTokenAuth().getToken()}` }; + return { Authorization: `token ${this.getTokenAuth().getToken()}` }; + } + + /** + * Get logged in user + */ + async getUser() { + this.url.pathname = "/api/v1/user"; + console.log(this.url.toString()); + let res = await fetch(this.url, { + method: "GET", + credentials: "include", + headers: this.getTokenAuthHeader(), + }); + console.log(`got res: ${res}`); + return await res.json(); } /**