Skip to content

Commit

Permalink
Clear out gitea access in the frontend
Browse files Browse the repository at this point in the history
Only ednpoints needed for rendering projects is left.
  • Loading branch information
AbdulrhmnGhanem committed Feb 16, 2023
1 parent b6b81b6 commit ef06d92
Show file tree
Hide file tree
Showing 3 changed files with 0 additions and 376 deletions.
246 changes: 0 additions & 246 deletions frontend/src/utils/giteaApi.js
Original file line number Diff line number Diff line change
@@ -1,143 +1,9 @@
import platformPath from 'path'
import getConfig from 'next/config'
import { formatAsGiteaRepoName } from './index'

const giteaApiUrl = `${getConfig().publicRuntimeConfig.KITSPACE_GITEA_URL}/api/v1`
const credentials = 'include'
const mode = 'cors'
const headers = { 'Content-Type': 'application/json' }

/**
* Create a new Gitea repo
* @param name {string}
* @param description {string}
* @param apiToken {string}
* @returns {Promise<string>}
*/
export const createRepo = async (name, description, apiToken) => {
const endpoint = `${giteaApiUrl}/user/repos`
const giteaOptions = {
name: formatAsGiteaRepoName(name),
description,
repo_template: '',
issue_labels: '',
gitignores: '',
readme: 'Default',
auto_init: true,
private: false,
default_branch: 'master',
}
const res = await fetch(endpoint, {
method: 'POST',
credentials,
mode,
headers: {
...headers,
Authorization: `token ${apiToken}`,
},
body: JSON.stringify(giteaOptions),
})

const body = await res.json()

return res.ok ? body.full_name : ''
}

/**
* Get the repo name from its url
* @param url
* @returns {string}
* @example
* // returns 'ulx3s'
* urlToName('https://github.com/emard/ulx3s/')
*/
const urlToName = url => {
const urlObj = new URL(url)
return platformPath.basename(
urlObj.pathname,
platformPath.extname(urlObj.pathname),
)
}

/**
* Get the git service from the url.
* The supported services in the api are `github`, `gitea`, `gitlab`, and `git`. See https://try.gitea.io/api/swagger#/repository/repoMigrate
* @param {string} url
* @returns {'github' | 'gitlab' | 'gitea' | 'git'} the service type.
*/
export const getGitServiceFromUrl = url => {
const hostName = new URL(url).hostname

switch (hostName) {
case 'github.com':
return 'github'
case 'gitlab.com':
return 'gitlab'
case 'try.gitea.io':
return 'gitea'
default:
return 'git'
}
}

/**
* Mirror an existing remote git repo to a Gitea repo
* @param remoteRepo {string} url of the remote repo
* @param uid {string}
* @param apiToken {string}
* @param repoName {string=}
* @returns {Promise<Response>}
*/
export const mirrorRepo = async (remoteRepo, uid, apiToken, repoName) => {
repoName = repoName || urlToName(remoteRepo)
const service = getGitServiceFromUrl(remoteRepo)
const endpoint = `${giteaApiUrl}/repos/migrate`
const giteaOptions = {
clone_addr: remoteRepo,
uid,
repo_name: repoName,
mirror: true,
wiki: false,
private: false,
pull_requests: false,
releases: true,
issues: false,
service,
}

return fetch(endpoint, {
method: 'POST',
mode,
credentials: 'include',
headers: {
...headers,
Authorization: `token ${apiToken}`,
},
body: JSON.stringify(giteaOptions),
})
}

/**
* Delete the corresponding gitea repo for a project.
* @param repo {string}
* @param apiToken {string}
* @returns {Promise<boolean>}
*/
export const deleteRepo = async (repo, apiToken) => {
const endpoint = `${giteaApiUrl}/repos/${repo}`
const res = await fetch(endpoint, {
method: 'DELETE',
mode,
credentials,
headers: {
...headers,
Authorization: `token ${apiToken}`,
},
})

return res.ok
}

/**
* Get repo details
* @param fullname
Expand Down Expand Up @@ -165,22 +31,6 @@ export const repoExists = async fullname => {

return repo != null
}
/**
*
* @param {string} username
* @param {string} repoName
* @param {boolean} isValidProjectName
* @returns
*/
export const isUsableProjectName = async (
username,
repoName,
isValidProjectName,
) => {
// Check if the new name will also cause a conflict.
const repoFullName = `${username}/${formatAsGiteaRepoName(repoName)}`
return isValidProjectName && !(await repoExists(repoFullName))
}

/**
* Check if a user exist
Expand Down Expand Up @@ -242,99 +92,3 @@ export const canCommit = async (repo, username, apiToken) => {
const repoOwner = repo.split('/')[0]
return repoOwner === username || isCollaborator(repo, username, apiToken)
}

/**
* Search all repos
* @param q{string=}: search query, leave undefined to return all repos
* @param sort{string}
* @param order{string}
* @returns {Promise<[Object]>}
*/

/**
* get a file in gitea repo
* @param {string} repo
* @param {string} path
* @returns
*/
export const getFile = async (repo, path) => {
const endpoint = `${giteaApiUrl}/repos/${repo}/contents/${path}`

const res = await fetch(endpoint, { method: 'GET', credentials, mode, headers })

return res.ok ? res.json() : {}
}

/**
* update existing file in gitea
* @param repo {string} full repo name, i.e., {user}/{repoName}
* @param path{string}
* @param content{string}: must be Base64 encoded
* @param user{object}
* @param apiToken{string}
* @returns {Promise<boolean>}
*/
export const updateFile = async (repo, path, content, user, apiToken) => {
const endpoint = `${giteaApiUrl}/repos/${repo}/contents/${path}`

const { sha } = await getFile(repo, path)
const reqBody = {
author: {
email: user.email,
name: user.login,
},
committer: {
email: user.email,
name: user.email,
},
// content must be Base64 encoded
content: btoa(content),
sha,
}

const res = await fetch(endpoint, {
method: 'PUT',
credentials,
mode,
headers: { ...headers, Authorization: `token ${apiToken}` },
body: JSON.stringify(reqBody),
})

return res.ok
}

/**
* Upload file to gitea
* @param repo {string} full repo name, i.e., {user}/{repoName}
* @param path{string}
* @param content{string}: must be Base64 encoded
* @param user{object}
* @param apiToken{string}
* @returns {Promise<boolean>}
*/
export const uploadFile = async (repo, path, content, user, apiToken) => {
const endpoint = `${giteaApiUrl}/repos/${repo}/contents/${path}`

const reqBody = {
author: {
email: user.email,
name: user.login,
},
committer: {
email: user.email,
name: user.email,
},
// content must be Base64 encoded
content: btoa(content),
}

const res = await fetch(endpoint, {
method: 'POST',
credentials,
mode,
headers: { ...headers, Authorization: `token ${apiToken}` },
body: JSON.stringify(reqBody),
})

return res.ok
}
79 changes: 0 additions & 79 deletions frontend/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,3 @@
import path from 'path'

/**
* Look in project files and choose a file name for the project from it.
* First it looks for known PCB CAD generate files,
* if none is found returns the first uploaded file.
* @param files{[]}
* @returns {string}
* @example
* // returns 'my-cool-project'
* slugifiedNameFromFiles([{name: 'f1.png', size: 1024, last_modified: {DATE}},
* {name: 'f2.md', size: 1024, last_modified: {DATE}},
* {name: 'my cool project.pro', size: 1024, last_modified: {DATE}}])
*/
export const slugifiedNameFromFiles = files => {
const FilesNames = files.map(f => f.name)
// TODO: make this look for all PCB software generated files not just KiCad projects
const kicadProject = FilesNames.find(f => f.endsWith('.pro'))
const projectWithExt = kicadProject || FilesNames[0]
return formatAsGiteaRepoName(projectWithExt)
}

/**
* Get the repo name from its url
* !if `url` is invalid the form validation would have caught it
* @param url
* @returns {string}
* @example
* // returns 'ulx3s'
* urlToName('https://github.com/emard/ulx3s/')
*/
export const urlToName = url => {
try {
url = new URL(url)
} catch {
return ''
}
return path.basename(url.pathname, path.extname(url.pathname))
}

/**
* Get the project name from the `path` object in `next.router`.
* @param projectPath
* @returns {string}
* @example
* // returns 'testUser/cool-project"
* projectNameFromPath('/testUser/cool-project')
* @example
* // returns 'testUser/cool-project"
* projectNameFromPath('/testUser/cool-project?create=true')
*/
export const projectNameFromPath = projectPath => {
const pathWithQuery = projectPath.split('/').slice(1).join('/')
// In case if there's a query string remove it
return pathWithQuery.split('?')[0]
}

/**
* Convert Megabytes to bytes
* @param megs{string}
* @example
* // returns 1048576
* MBytesToBytes('1M')
*/
export const MBytesToBytes = megs => {
const num = Number(megs.split('M')[0])

// 1 Megabyte = 1048576 Bytes.
return 1048576 * num
}

export function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
Expand Down Expand Up @@ -110,11 +39,3 @@ export function waitFor<T>(

return Promise.race([timer(), loop()])
}
/**
* format projectName name as a valid gitea repo name.
* This replaces any **non* (alphanumeric, -, _, and .) with a '-',
* see https://github.com/go-gitea/gitea/blob/b59b0cad0a550223f74add109ff13c0d2f4309f3/services/forms/repo_form.go#L35
* @param projectName {string}
*/
export const formatAsGiteaRepoName = projectName =>
projectName.replace(/[^\w\d-_.]/g, '-').slice(0, 100)
Loading

0 comments on commit ef06d92

Please sign in to comment.