Peace/lib/Peace/Controller/Application.pm

98 lines
2.5 KiB
Perl

package Peace::Controller::Application;
use Mojo::Base 'Mojolicious::Controller';
use v5.30.0;
use strict;
use warnings;
use Peace;
use Peace::Swagger;
use Peace::DB;
use Peace::DAO::Developer;
use Peace::Model::Application;
use Peace::DAO::Application;
sub developer_application_post {
my $self = shift;
my $json = $self->req->json;
my $peace = Peace->new;
my $config = $peace->peace_config;
my $dbh = Peace::DB->dbh( config => $config );
my $swagger = Peace::Swagger->new;
my $headers = $self->req->headers->to_hash;
unless ( defined $json ) {
$self->render( text => 'body is not a json', status => '400' );
return;
}
my $spec = $swagger->developer_application_post;
eval {
$swagger->validate_request(
json => $json,
stash => $self->stash,
headers => $headers,
spec => $spec,
);
};
if ($@) {
$self->render( text => $@, status => '400' );
return;
}
my $api_key = $headers->{api_key};
my $identifier = $self->stash->{identifier};
my $developer_dao = Peace::DAO::Developer->new( dbh => $dbh );
my $developer = $developer_dao->recover_by_identifier( identifier => $identifier );
unless (defined $developer || $developer->login($api_key)) {
$self->render( text => 'Incorrect user or password', status => 401 );
return;
}
unless ($developer->verified) {
$self->render( text => 'Developer is still not verified', status => 401 );
return;
}
my $application = Peace::Model::Application->new(%$json, verified => 0, developer => $developer);
my $application_dao = Peace::DAO::Application->new( dbh => $dbh );
eval {
$application_dao->create( application => $application );
};
if ($@) {
$self->render( status => 400, text => $@ );
return;
}
$self->render( json => $application->to_json() );
}
1;
=encoding utf8
=head1 NAME
Peace::Controller::Application - Application's http endpoint.
=head1 SYNOPSIS
# This object is used by mojolicious.
=head1 DESCRIPTION
Peace::Controller::Application allows to interact using
a json http api with the L<Peace::Model::Application> objects
in Peace.
=head1 METHODS
Peace::Controller::Developer implements the following methods:
=head2 developer_application_post
# To be used by mojolicious.
Creates a application in db with the data given by the user.
=head1 SEE ALSO
L<Peace::Model::Application>, L<Peace::DAO::Application>
=cut