package BurguillosInfo::Controller::ConquerTeam; use v5.34.1; use strict; use warnings; use utf8; use Mojo::Base 'Mojolicious::Controller', '-signatures'; use UUID::URandom qw/create_uuid_string/; use JSON; use BurguillosInfo::Schema; sub get ($self) { my $user = $self->current_user; if ( !defined $user ) { return $self->render( status => 401, json => { error => 'You must be logged to fetch a team.', } ); } my $uuid = $self->param('uuid'); my $resultset = BurguillosInfo::Schema->Schema->resultset('ConquerTeam'); my @teams = $resultset->search( { 'uuid' => $uuid, } ); if ( scalar @teams <= 0 ) { return $self->render( status => 404, json => { error => 'This team does not exist.', } ); } my $team = $teams[0]; return $self->render( json => $team ); } sub getSelfTeam ($self) { my $user = $self->current_user; if ( !defined $user ) { return $self->render( status => 401, json => { error => 'You must be logged to fetch your Team.', } ); } my $resultset = BurguillosInfo::Schema->Schema->resultset('ConquerTeam'); my @teams = $resultset->search( { 'players.uuid' => $user->uuid }, { join => 'players', } ); if ( scalar @teams <= 0 ) { return $self->render( json => undef ); } my $team = $teams[0]; return $self->render( json => $team ); } sub _expectJson ($self) { my $input; eval { $input = $self->req->json; }; if ($@) { say STDERR $@; $self->_renderError( 400, 'Se esperaba JSON.' ); return; } return $input; } sub put ($self) { my $user = $self->current_user; if ( !defined $user ) { return $self->render( status => 401, json => { error => 'No estás autenticado.', } ); } if ( !$user->is_admin ) { return $self->render( status => 403, json => { error => 'No tienes permiso para hacer eso.', } ); } my $input = $self->_expectJson; if ( !defined $input ) { return; } my $name = $input->{name}; my $description = $input->{description}; my $color = $input->{color}; if ( !defined $name || length $name < 5 ) { return $self->render( status => 400, json => { error => 'Número incorrecto de carácteres en el nombre del equipo..', } ); } if ( !defined $description ) { return $self->render( status => 400, json => { error => 'La descripción puede estar vacía, ' . 'pero debe existir, si ves este error ' . 'desde la aplicación es un error de programación.', } ); } my $color_regex_char = qr/[0-9a-fA-F]/; if ( !defined $color || $color !~ /^#(?:${color_regex_char}{6}|${color_regex_char}{3})$/ ) { return $self->render( status => 400, json => { error => 'Formato de color invalido', } ); } my $uuid_team = create_uuid_string(); my $team; eval { $team = BurguillosInfo::Schema->Schema->resultset('ConquerTeam')->new( { uuid => $uuid_team, description => $description, name => $name, color => $color, } ); $team->insert; }; if ($@) { warn $@; return $self->render( status => 500, json => { error => 'El servidor no pudo almacenar el equipo, reporta este error.', } ); } return $self->render( status => 200, json => $team->serialize, ); } 1;