Skip to content

Commit

Permalink
get Coterm working again!
Browse files Browse the repository at this point in the history
  • Loading branch information
ericwang401 committed Dec 1, 2023
1 parent d5908d2 commit bafb77b
Show file tree
Hide file tree
Showing 30 changed files with 829 additions and 290 deletions.
35 changes: 28 additions & 7 deletions app/Http/Controllers/Admin/CotermController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
namespace Convoy\Http\Controllers\Admin;

use Convoy\Http\Controllers\ApiController;
use Convoy\Http\Requests\Admin\Coterms\DeleteCotermRequest;
use Convoy\Http\Requests\Admin\Coterms\StoreCotermRequest;
use Convoy\Http\Requests\Admin\Coterms\UpdateAttachedNodesRequest;
use Convoy\Http\Requests\Admin\Coterms\UpdateCotermRequest;
use Convoy\Models\Coterm;
use Convoy\Models\Filters\FiltersCoterm;
use Convoy\Models\Filters\FiltersNode;
use Convoy\Models\Node;
use Convoy\Services\Coterm\CotermTokenCreationService;
use Convoy\Transformers\Admin\CotermTransformer;
use Convoy\Transformers\Admin\NodeTransformer;
Expand Down Expand Up @@ -48,20 +50,31 @@ public function show(Coterm $coterm)

public function store(StoreCotermRequest $request)
{
$coterm = Coterm::create($request->safe()->except('node_ids'));
$creds = $this->cotermTokenCreator->handle();
$coterm = Coterm::create([
...$request->safe()->except('node_ids'),
...$creds,
]);
if ($request->node_ids !== null) {
$coterm->nodes()->attach($request->node_ids);
Node::whereIn('id', $request->node_ids)->whereNull('coterm_id')->update(
['coterm_id' => $coterm->id],
);
}
$coterm->loadCount(['nodes']);

return fractal($coterm, new CotermTransformer())->respond();
return fractal($coterm, new CotermTransformer(includeToken: true))->respond();
}

public function update(UpdateCotermRequest $request, Coterm $coterm)
{
$coterm->update($request->validated());
if ($request->node_ids !== null) {
$coterm->nodes()->sync($request->node_ids);
Node::whereIn('id', $request->node_ids)->whereNull('coterm_id')->update(
['coterm_id' => $coterm->id],
);
Node::where('coterm_id', $coterm->id)->whereNotIn('id', $request->node_ids)->update(
['coterm_id' => null],
);
}
$coterm->loadCount(['nodes']);

Expand All @@ -86,7 +99,12 @@ public function getAttachedNodes(Request $request, Coterm $coterm)

public function updateAttachedNodes(UpdateAttachedNodesRequest $request, Coterm $coterm)
{
$coterm->nodes()->sync($request->node_ids);
Node::whereIn('id', $request->node_ids)->whereNull('coterm_id')->update(
['coterm_id' => $coterm->id],
);
Node::where('coterm_id', $coterm->id)->whereNotIn('id', $request->node_ids)->update(
['coterm_id' => null],
);
$coterm->loadCount(['nodes']);

return fractal($coterm, new CotermTransformer())->respond();
Expand All @@ -100,11 +118,14 @@ public function resetCotermToken(Coterm $coterm)
'token' => $creds['token'],
]);

return fractal($coterm, new CotermTransformer())->parseIncludes('token')->respond();
return fractal($coterm, new CotermTransformer(includeToken: true))->parseIncludes('token')
->respond();
}

public function destroy(Coterm $coterm)
public function destroy(DeleteCotermRequest $request, Coterm $coterm)
{
$coterm->delete();

return $this->returnNoContent();
}
}
4 changes: 3 additions & 1 deletion app/Http/Controllers/Admin/Nodes/NodeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ public function index(Request $request)
->allowedFilters(
[AllowedFilter::exact('id'), 'name', 'fqdn', AllowedFilter::exact(
'location_id',
), AllowedFilter::custom(
), AllowedFilter::exact(
'coterm_id',
)->nullable(), AllowedFilter::custom(
'*',
new FiltersNode(),
)],
Expand Down
10 changes: 6 additions & 4 deletions app/Http/Controllers/Client/Servers/ServerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,14 @@ public function updateState(Server $server, SendPowerCommandRequest $request)

public function createConsoleSession(CreateConsoleSessionRequest $request, Server $server)
{
if ($server->node->coterm_enabled) {
$server->node->loadMissing('coterm');

if ($coterm = $server->node->coterm) {
return new JsonResponse([
'data' => [
'is_tls_enabled' => $server->node->coterm_tls_enabled,
'fqdn' => $server->node->coterm_fqdn,
'port' => $server->node->coterm_port,
'is_tls_enabled' => $coterm->is_tls_enabled,
'fqdn' => $coterm->fqdn,
'port' => $coterm->port,
'token' => $this->cotermJWTService->handle(
$server, $request->user(), $request->enum('type', ConsoleType::class),
)
Expand Down
27 changes: 13 additions & 14 deletions app/Http/Middleware/Coterm/CotermAuthenticate.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

namespace Convoy\Http\Middleware\Coterm;

use Convoy\Models\Node;
use Illuminate\Http\Request;
use Convoy\Models\Coterm;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;

class CotermAuthenticate
{
Expand All @@ -27,31 +27,30 @@ public function handle(Request $request, \Closure $next): mixed
}

if (is_null($bearer = $request->bearerToken())) {
throw new HttpException(401, 'Access to this endpoint must include an Authorization header.', null, ['WWW-Authenticate' => 'Bearer']);
throw new HttpException(
401, 'Access to this endpoint must include an Authorization header.', null,
['WWW-Authenticate' => 'Bearer'],
);
}

$parts = explode('|', $bearer);
// Ensure that all the correct parts are provided in the header.
if (count($parts) !== 2 || empty($parts[0]) || empty($parts[1])) {
throw new BadRequestHttpException('The Authorization header provided was not in a valid format.');
throw new BadRequestHttpException(
'The Authorization header provided was not in a valid format.',
);
}

try {
$node = Node::where('coterm_token_id', $parts[0])->firstOrFail();

if (!$node->coterm_enabled) {
throw new HttpException(401);
}

if (hash_equals($node->coterm_token, $parts[1])) {
$request->attributes->set('node', $node);
$coterm = Coterm::where('token_id', $parts[0])->firstOrFail();

if (hash_equals($coterm->token, $parts[1])) {
return $next($request);
}
} catch (ModelNotFoundException) {
// Do nothing, we don't want to expose a node not existing at all.
}

throw new HttpException(401);
throw new HttpException(401);
}
}
4 changes: 3 additions & 1 deletion app/Http/Requests/Admin/Coterms/StoreCotermRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

namespace Convoy\Http\Requests\Admin\Coterms;

use Convoy\Http\Requests\BaseApiRequest;
use Convoy\Rules\Fqdn;
use Convoy\Models\Coterm;
use Illuminate\Support\Arr;
use Convoy\Http\Requests\BaseApiRequest;

class StoreCotermRequest extends BaseApiRequest
{
public function rules(): array
{
$rules = Coterm::getRules();
$rules['fqdn'][] = Fqdn::make();

return [
...Arr::only($rules, ['name', 'is_tls_enabled', 'fqdn', 'port']),
Expand Down
6 changes: 5 additions & 1 deletion app/Models/Coterm.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Convoy\Casts\NullableEncrypter;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Coterm extends Model
{
Expand Down Expand Up @@ -39,4 +38,9 @@ public function nodes(): HasMany
{
return $this->hasMany(Node::class);
}

public function getRouteKeyName(): string
{
return 'id';
}
}
19 changes: 10 additions & 9 deletions app/Transformers/Admin/CotermTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,26 @@

class CotermTransformer extends TransformerAbstract
{
protected array $availableIncludes = ['token'];
public function __construct(private bool $includeToken = false)
{
}

public function transform(Coterm $coterm): array
{
return [
$transformed = [
'id' => (int)$coterm->id,
'name' => $coterm->name,
'is_tls_enabled' => (boolean)$coterm->is_tls_enabled,
'fqdn' => $coterm->fqdn,
'port' => (int)$coterm->port,
'nodes_count' => (int)$coterm->nodes_count,
];
}

public function includeToken(Coterm $coterm): array
{
return [
'token_id' => $coterm->token_id,
'token' => $coterm->token,
];
if ($this->includeToken) {
$transformed['token_id'] = $coterm->token_id;
$transformed['token'] = $coterm->token;
}

return $transformed;
}
}
2 changes: 1 addition & 1 deletion resources/scripts/api/admin/coterms/deleteCoterm.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import http from '@/api/http'

const deleteCoterm = (id: string) => http.delete(`/admin/coterms/${id}`)
const deleteCoterm = (id: string) => http.delete(`/api/admin/coterms/${id}`)

export default deleteCoterm
13 changes: 13 additions & 0 deletions resources/scripts/api/admin/coterms/getCoterm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { rawDataToCoterm } from '@/api/admin/coterms/getCoterms'
import http from '@/api/http'


const getCoterm = async (id: number) => {
const {
data: { data },
} = await http.get(`/api/admin/coterms/${id}`)

return rawDataToCoterm(data)
}

export default getCoterm
3 changes: 2 additions & 1 deletion resources/scripts/api/admin/coterms/resetCotermToken.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { rawDataToCoterm } from '@/api/admin/coterms/getCoterms'
import http from '@/api/http'


const resetCotermToken = async (id: number) => {
const {
data: { data },
} = await http.post(`/api/admin/coterm/${id}/settings/reset-coterm-token`)
} = await http.post(`/api/admin/coterms/${id}/reset-coterm-token`)

return rawDataToCoterm(data)
}
Expand Down
2 changes: 1 addition & 1 deletion resources/scripts/api/admin/coterms/updateCoterm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const updateCoterm = async (
) => {
const {
data: { data },
} = await http.put(`/admin/coterms/${id}`, {
} = await http.put(`/api/admin/coterms/${id}`, {
name,
is_tls_enabled: isTlsEnabled,
fqdn,
Expand Down
21 changes: 21 additions & 0 deletions resources/scripts/api/admin/coterms/useAttachedNodes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import useSWR from 'swr'

import getAttachedNodes, {
QueryParams,
} from '@/api/admin/coterms/getAttachedNodes'


const useAttachedNodes = (
id: number,
{ page, query, ...params }: QueryParams
) => {
return useSWR(['admin.coterms.attachedNodes', id, page, query], () =>
getAttachedNodes(id, {
page,
query,
...params,
})
)
}

export default useAttachedNodes
20 changes: 20 additions & 0 deletions resources/scripts/api/admin/coterms/useCotermSWR.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Optimistic } from '@/lib/swr'
import { useParams } from 'react-router-dom'
import useSWR, { Key, SWRResponse } from 'swr'

import getCoterm from '@/api/admin/coterms/getCoterm'
import { Coterm } from '@/api/admin/coterms/getCoterms'


export const getKey = (id: number): Key => ['admin.coterms', id]

const useCotermSWR = () => {
const { cotermId } = useParams()
const id = parseInt(cotermId!)

return useSWR<Coterm>(getKey(id), () => getCoterm(id), {
revalidateOnMount: false,
}) as Optimistic<SWRResponse<Coterm, any>>
}

export default useCotermSWR
5 changes: 4 additions & 1 deletion resources/scripts/api/admin/nodes/getNodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,24 @@ export const rawDataToNode = (data: any): Node => ({
export type NodeResponse = PaginatedResult<Node>

export interface QueryParams {
query?: string
query?: string | null
cotermId?: number | null
id?: number | number[] | string | string[]
page?: number
perPage?: number
}

const getNodes = async ({
query,
cotermId,
id,
perPage = 50,
...params
}: QueryParams): Promise<NodeResponse> => {
const { data } = await http.get('/api/admin/nodes', {
params: {
'filter[*]': query,
'filter[coterm_id]': cotermId === null ? '' : cotermId,
'filter[id]': id
? Array.isArray(id)
? id.join(',')
Expand Down
13 changes: 0 additions & 13 deletions resources/scripts/api/admin/nodes/settings/resetCotermToken.ts

This file was deleted.

Loading

0 comments on commit bafb77b

Please sign in to comment.