This repository was archived by the owner on Sep 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
feat: gitea backend #325
Merged
Merged
feat: gitea backend #325
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import { styled } from '@mui/material/styles'; | ||
| import React, { useCallback, useState } from 'react'; | ||
|
|
||
| import AuthenticationPage from '@staticcms/core/components/UI/AuthenticationPage'; | ||
| import Icon from '@staticcms/core/components/UI/Icon'; | ||
| import { NetlifyAuthenticator } from '@staticcms/core/lib/auth'; | ||
|
|
||
| import type { MouseEvent } from 'react'; | ||
| import type { AuthenticationPageProps, TranslatedProps } from '@staticcms/core/interface'; | ||
|
|
||
| const LoginButtonIcon = styled(Icon)` | ||
| margin-right: 18px; | ||
| `; | ||
|
|
||
| const GiteaAuthenticationPage = ({ | ||
| inProgress = false, | ||
| config, | ||
| base_url, | ||
| siteId, | ||
| authEndpoint, | ||
| onLogin, | ||
| t, | ||
| }: TranslatedProps<AuthenticationPageProps>) => { | ||
| const [loginError, setLoginError] = useState<string | null>(null); | ||
|
|
||
| const handleLogin = useCallback( | ||
| (e: MouseEvent<HTMLButtonElement>) => { | ||
| e.preventDefault(); | ||
| const cfg = { | ||
| base_url, | ||
| site_id: document.location.host.split(':')[0] === 'localhost' ? 'cms.netlify.com' : siteId, | ||
| auth_endpoint: authEndpoint, | ||
| }; | ||
| const auth = new NetlifyAuthenticator(cfg); | ||
|
|
||
| const { auth_scope: authScope = '' } = config.backend; | ||
|
|
||
| const scope = authScope || 'repo'; | ||
| auth.authenticate({ provider: 'gitea', scope }, (err, data) => { | ||
| if (err) { | ||
| setLoginError(err.toString()); | ||
| } else if (data) { | ||
| onLogin(data); | ||
| } | ||
| }); | ||
| }, | ||
| [authEndpoint, base_url, config.backend, onLogin, siteId], | ||
| ); | ||
|
|
||
| return ( | ||
| <AuthenticationPage | ||
| onLogin={handleLogin} | ||
| loginDisabled={inProgress} | ||
| loginErrorMessage={loginError} | ||
| logoUrl={config.logo_url} | ||
| siteUrl={config.site_url} | ||
| icon={<LoginButtonIcon type="gitea" />} | ||
| buttonContent={t('auth.loginWithGitea')} | ||
| t={t} | ||
| /> | ||
| ); | ||
| }; | ||
|
|
||
| export default GiteaAuthenticationPage; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,267 @@ | ||
| import { Base64 } from 'js-base64'; | ||
|
|
||
| import API from '../API'; | ||
|
|
||
| import type { Options } from '../API'; | ||
|
|
||
| describe('gitea API', () => { | ||
| beforeEach(() => { | ||
| jest.resetAllMocks(); | ||
|
|
||
| global.fetch = jest.fn().mockRejectedValue(new Error('should not call fetch inside tests')); | ||
| }); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| function mockAPI(api: API, responses: Record<string, (options: Options) => any>) { | ||
| api.request = jest.fn().mockImplementation((path, options = {}) => { | ||
| const normalizedPath = path.indexOf('?') !== -1 ? path.slice(0, path.indexOf('?')) : path; | ||
| const response = responses[normalizedPath]; | ||
| return typeof response === 'function' | ||
| ? Promise.resolve(response(options)) | ||
| : Promise.reject(new Error(`No response for path '${normalizedPath}'`)); | ||
| }); | ||
| } | ||
|
|
||
| describe('request', () => { | ||
| const fetch = jest.fn(); | ||
| beforeEach(() => { | ||
| global.fetch = fetch; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.resetAllMocks(); | ||
| }); | ||
|
|
||
| it('should fetch url with authorization header', async () => { | ||
| const api = new API({ branch: 'gh-pages', repo: 'my-repo', token: 'token' }); | ||
|
|
||
| fetch.mockResolvedValue({ | ||
| text: jest.fn().mockResolvedValue('some response'), | ||
| ok: true, | ||
| status: 200, | ||
| headers: { get: () => '' }, | ||
| }); | ||
| const result = await api.request('/some-path'); | ||
| expect(result).toEqual('some response'); | ||
| expect(fetch).toHaveBeenCalledTimes(1); | ||
| expect(fetch).toHaveBeenCalledWith('https://try.gitea.io/api/v1/some-path', { | ||
| cache: 'no-cache', | ||
| headers: { | ||
| Authorization: 'token token', | ||
| 'Content-Type': 'application/json; charset=utf-8', | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it('should throw error on not ok response', async () => { | ||
| const api = new API({ branch: 'gt-pages', repo: 'my-repo', token: 'token' }); | ||
|
|
||
| fetch.mockResolvedValue({ | ||
| text: jest.fn().mockResolvedValue({ message: 'some error' }), | ||
| ok: false, | ||
| status: 404, | ||
| headers: { get: () => '' }, | ||
| }); | ||
|
|
||
| await expect(api.request('some-path')).rejects.toThrow( | ||
| expect.objectContaining({ | ||
| message: 'some error', | ||
| name: 'API_ERROR', | ||
| status: 404, | ||
| api: 'Gitea', | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('should allow overriding requestHeaders to return a promise ', async () => { | ||
| const api = new API({ branch: 'gt-pages', repo: 'my-repo', token: 'token' }); | ||
|
|
||
| api.requestHeaders = jest.fn().mockResolvedValue({ | ||
| Authorization: 'promise-token', | ||
Check failureCode scanning / CodeQL Hard-coded credentials
The hard-coded value "promise-token" is used as [authorization header](1).
|
||
| 'Content-Type': 'application/json; charset=utf-8', | ||
| }); | ||
|
|
||
| fetch.mockResolvedValue({ | ||
| text: jest.fn().mockResolvedValue('some response'), | ||
| ok: true, | ||
| status: 200, | ||
| headers: { get: () => '' }, | ||
| }); | ||
| const result = await api.request('/some-path'); | ||
| expect(result).toEqual('some response'); | ||
| expect(fetch).toHaveBeenCalledTimes(1); | ||
| expect(fetch).toHaveBeenCalledWith('https://try.gitea.io/api/v1/some-path', { | ||
| cache: 'no-cache', | ||
| headers: { | ||
| Authorization: 'promise-token', | ||
Check failureCode scanning / CodeQL Hard-coded credentials
The hard-coded value "promise-token" is used as [authorization header](1).
|
||
| 'Content-Type': 'application/json; charset=utf-8', | ||
| }, | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('persistFiles', () => { | ||
| it('should create a new file', async () => { | ||
| const api = new API({ branch: 'master', repo: 'owner/repo' }); | ||
|
|
||
| const responses = { | ||
| '/repos/owner/repo/contents/content/posts/new-post.md': () => ({ | ||
| commit: { sha: 'new-sha' }, | ||
| }), | ||
| }; | ||
| mockAPI(api, responses); | ||
|
|
||
| const entry = { | ||
| dataFiles: [ | ||
| { | ||
| slug: 'entry', | ||
| sha: 'abc', | ||
| path: 'content/posts/new-post.md', | ||
| raw: 'content', | ||
| }, | ||
| ], | ||
| assets: [], | ||
| }; | ||
| await api.persistFiles(entry.dataFiles, entry.assets, { | ||
| commitMessage: 'commitMessage', | ||
| newEntry: true, | ||
| }); | ||
|
|
||
| expect(api.request).toHaveBeenCalledTimes(1); | ||
|
|
||
| expect((api.request as jest.Mock).mock.calls[0]).toEqual([ | ||
| '/repos/owner/repo/contents/content/posts/new-post.md', | ||
| { | ||
| method: 'POST', | ||
| body: JSON.stringify({ | ||
| branch: 'master', | ||
| content: Base64.encode(entry.dataFiles[0].raw), | ||
| message: 'commitMessage', | ||
| signoff: false, | ||
| }), | ||
| }, | ||
| ]); | ||
| }); | ||
| it('should get the file sha and update the file', async () => { | ||
| jest.clearAllMocks(); | ||
| const api = new API({ branch: 'master', repo: 'owner/repo' }); | ||
|
|
||
| const responses = { | ||
| '/repos/owner/repo/git/trees/master:content%2Fposts': () => { | ||
| return { tree: [{ path: 'update-post.md', sha: 'old-sha' }] }; | ||
| }, | ||
|
|
||
| '/repos/owner/repo/contents/content/posts/update-post.md': () => { | ||
| return { commit: { sha: 'updated-sha' } }; | ||
| }, | ||
| }; | ||
| mockAPI(api, responses); | ||
|
|
||
| const entry = { | ||
| dataFiles: [ | ||
| { | ||
| slug: 'entry', | ||
| sha: 'abc', | ||
| path: 'content/posts/update-post.md', | ||
| raw: 'content', | ||
| }, | ||
| ], | ||
| assets: [], | ||
| }; | ||
|
|
||
| await api.persistFiles(entry.dataFiles, entry.assets, { | ||
| commitMessage: 'commitMessage', | ||
| newEntry: false, | ||
| }); | ||
|
|
||
| expect(api.request).toHaveBeenCalledTimes(1); | ||
|
|
||
| expect((api.request as jest.Mock).mock.calls[0]).toEqual([ | ||
| '/repos/owner/repo/git/trees/master:content%2Fposts', | ||
| ]); | ||
| }); | ||
| }); | ||
|
|
||
| describe('listFiles', () => { | ||
| it('should get files by depth', async () => { | ||
| const api = new API({ branch: 'master', repo: 'owner/repo' }); | ||
|
|
||
| const tree = [ | ||
| { | ||
| path: 'post.md', | ||
| type: 'blob', | ||
| }, | ||
| { | ||
| path: 'dir1', | ||
| type: 'tree', | ||
| }, | ||
| { | ||
| path: 'dir1/nested-post.md', | ||
| type: 'blob', | ||
| }, | ||
| { | ||
| path: 'dir1/dir2', | ||
| type: 'tree', | ||
| }, | ||
| { | ||
| path: 'dir1/dir2/nested-post.md', | ||
| type: 'blob', | ||
| }, | ||
| ]; | ||
| api.request = jest.fn().mockResolvedValue({ tree }); | ||
|
|
||
| await expect(api.listFiles('posts', { depth: 1 })).resolves.toEqual([ | ||
| { | ||
| path: 'posts/post.md', | ||
| type: 'blob', | ||
| name: 'post.md', | ||
| }, | ||
| ]); | ||
| expect(api.request).toHaveBeenCalledTimes(1); | ||
| expect(api.request).toHaveBeenCalledWith('/repos/owner/repo/git/trees/master:posts', { | ||
| params: {}, | ||
| }); | ||
|
|
||
| jest.clearAllMocks(); | ||
| await expect(api.listFiles('posts', { depth: 2 })).resolves.toEqual([ | ||
| { | ||
| path: 'posts/post.md', | ||
| type: 'blob', | ||
| name: 'post.md', | ||
| }, | ||
| { | ||
| path: 'posts/dir1/nested-post.md', | ||
| type: 'blob', | ||
| name: 'nested-post.md', | ||
| }, | ||
| ]); | ||
| expect(api.request).toHaveBeenCalledTimes(1); | ||
| expect(api.request).toHaveBeenCalledWith('/repos/owner/repo/git/trees/master:posts', { | ||
| params: { recursive: 1 }, | ||
| }); | ||
|
|
||
| jest.clearAllMocks(); | ||
| await expect(api.listFiles('posts', { depth: 3 })).resolves.toEqual([ | ||
| { | ||
| path: 'posts/post.md', | ||
| type: 'blob', | ||
| name: 'post.md', | ||
| }, | ||
| { | ||
| path: 'posts/dir1/nested-post.md', | ||
| type: 'blob', | ||
| name: 'nested-post.md', | ||
| }, | ||
| { | ||
| path: 'posts/dir1/dir2/nested-post.md', | ||
| type: 'blob', | ||
| name: 'nested-post.md', | ||
| }, | ||
| ]); | ||
| expect(api.request).toHaveBeenCalledTimes(1); | ||
| expect(api.request).toHaveBeenCalledWith('/repos/owner/repo/git/trees/master:posts', { | ||
| params: { recursive: 1 }, | ||
| }); | ||
| }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Hard-coded credentials