Gogs SSH keys support

This commit is contained in:
Geoffrey Frogeye 2016-12-10 21:44:21 +01:00
parent f308830095
commit b7b2ab744a

View file

@ -311,6 +311,63 @@ function argAssert($arg, $data, $args) {
return false;
}
// Hooks
//
function gogsRequest($route, $meth = 'GET', $data = null) {
global $GOGS_API;
global $GOGS_TOKEN;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GOGS_API.'/'.$route);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: token '.$GOGS_TOKEN));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $meth);
if ($data) {
$textdata = '';
foreach ($data as $key => $value) {
$textdata .= '&'.$key.'='.urlencode($value);
}
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, ltrim($textdata, '&'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$raw = curl_exec($ch);
curl_close($ch);
return json_decode($raw);
}
function updateGogsKeys($keys) {
global $GOGS_API;
global $GOGS_TOKEN;
global $SSH_KEY_REGEX;
if (isset($GOGS_API) && isset($GOGS_TOKEN)) {
$existing = gogsRequest('user/keys');
$toDelete = [];
foreach ($existing as $ekey) {
$toDelete[$ekey->id] = $ekey->key;
}
foreach (explode("\n", $keys) as $key) {
$found = false;
foreach ($toDelete as $id => $ekey) {
if ($key == $ekey) {
unset($toDelete[$id]);
$found = true;
break;
}
}
if (!$found) {
gogsRequest('user/keys', 'POST', array(
"title" => ltrim(preg_replace($SSH_KEY_REGEX, '', $key)),
"key" => $key
));
}
}
foreach ($toDelete as $id => $ekey) {
gogsRequest('user/keys/'.$id, 'DELETE');
}
}
}
switch ($route[0]) {
case 'machine':
case 'network':
@ -513,8 +570,12 @@ case 'akey':
file_put_contents('akey/'.$networkName.'.authorized_keys', getKeys($networkName ? $network : null));
file_put_contents('akey/'.$networkName.'.authorized_keys.sha256', $sign);
if ($networkName == 'gogs') {
updateGogsKeys(getKeys($network));
}
http_response_code(201);
logActivity('Updated key '.$networkName);
logActivity('Updated akeys '.$networkName);
} else {
http_response_code(404);
die("Unknown network\n");