Skip to content
Snippets Groups Projects
Verified Commit 37e922ab authored by Andrej Ramašeuski's avatar Andrej Ramašeuski
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
Pipeline #5977 passed
**
!lib
!script
!cpanfile
!openapi.yaml
!iapi.conf
image: docker:20.10.9
variables:
DOCKER_TLS_CERTDIR: "/certs"
IMAGE_VER: 0.1.0
services:
- docker:20.10.9-dind
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
build:
stage: build
script:
- docker pull $CI_REGISTRY_IMAGE:latest || true
- docker build --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$IMAGE_VER --tag $CI_REGISTRY_IMAGE:latest .
- docker push $CI_REGISTRY_IMAGE:$IMAGE_VER
- docker push $CI_REGISTRY_IMAGE:latest
FROM debian:bullseye-slim
RUN apt-get update && apt-get install -y \
wget \
cpanminus \
build-essential \
libcrypt-openssl-rsa-perl \
libdigest-sha-perl \
libmodule-build-tiny-perl \
libio-socket-ssl-perl \
libyaml-perl \
libyaml-dev
# libnet-ssleay-perl \
RUN cpanm \
Mojolicious \
Mojo::Redis \
Mojo::JWT \
Mojolicious::Plugin::OpenAPI
ADD . /opt/cf2022
WORKDIR /opt/cf2022
USER nobody
EXPOSE 3000
CMD /opt/cf2022/script/cf2022 daemon -c 3000
LICENSE 0 → 100644
The "Artistic License"
Preamble
The intent of this document is to state the conditions under which a
Package may be copied, such that the Copyright Holder maintains some
semblance of artistic control over the development of the package,
while giving the users of the package the right to use and distribute
the Package in a more-or-less customary fashion, plus the right to make
reasonable modifications.
Definitions:
"Package" refers to the collection of files distributed by the
Copyright Holder, and derivatives of that collection of files
created through textual modification.
"Standard Version" refers to such a Package if it has not been
modified, or has been modified in accordance with the wishes
of the Copyright Holder as specified below.
"Copyright Holder" is whoever is named in the copyright or
copyrights for the package.
"You" is you, if you're thinking about copying or distributing
this Package.
"Reasonable copying fee" is whatever you can justify on the
basis of media cost, duplication charges, time of people involved,
and so on. (You will not be required to justify it to the
Copyright Holder, but only to the computing community at large
as a market that must bear the fee.)
"Freely Available" means that no fee is charged for the item
itself, though there may be fees involved in handling the item.
It also means that recipients of the item may redistribute it
under the same conditions they received it.
1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.
2. You may apply bug fixes, portability fixes and other modifications
derived from the Public Domain or from the Copyright Holder. A Package
modified in such a way shall still be considered the Standard Version.
3. You may otherwise modify your copy of this Package in any way, provided
that you insert a prominent notice in each changed file stating how and
when you changed that file, and provided that you do at least ONE of the
following:
a) place your modifications in the Public Domain or otherwise make them
Freely Available, such as by posting said modifications to Usenet or
an equivalent medium, or placing the modifications on a major archive
site such as uunet.uu.net, or by allowing the Copyright Holder to include
your modifications in the Standard Version of the Package.
b) use the modified Package only within your corporation or organization.
c) rename any non-standard executables so the names do not conflict
with standard executables, which must also be provided, and provide
a separate manual page for each non-standard executable that clearly
documents how it differs from the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
4. You may distribute the programs of this Package in object code or
executable form, provided that you do at least ONE of the following:
a) distribute a Standard Version of the executables and library files,
together with instructions (in the manual page or equivalent) on where
to get the Standard Version.
b) accompany the distribution with the machine-readable source of
the Package with your modifications.
c) give non-standard executables non-standard names, and clearly
document the differences in manual pages (or equivalent), together
with instructions on where to get the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
5. You may charge a reasonable copying fee for any distribution of this
Package. You may charge any fee you choose for support of this
Package. You may not charge a fee for this Package itself. However,
you may distribute this Package in aggregate with other (possibly
commercial) programs as part of a larger (possibly commercial) software
distribution provided that you do not advertise this Package as a
product of your own. You may embed this Package's interpreter within
an executable of yours (by linking); this shall be construed as a mere
form of aggregation, provided that the complete Standard Version of the
interpreter is so embedded.
6. The scripts and library files supplied as input to or produced as
output from the programs of this Package do not automatically fall
under the copyright of this Package, but belong to whoever generated
them, and may be sold commercially, and may be aggregated with this
Package. If such scripts or library files are aggregated with this
Package via the so-called "undump" or "unexec" methods of producing a
binary executable image, then distribution of such an image shall
neither be construed as a distribution of this Package nor shall it
fall under the restrictions of Paragraphs 3 and 4, provided that you do
not represent such an executable image as a Standard Version of this
Package.
7. C subroutines (or comparably compiled subroutines in other
languages) supplied by you and linked into this Package in order to
emulate subroutines and variables of the language defined by this
Package shall not be considered part of this Package, but are the
equivalent of input as in Paragraph 6, provided these subroutines do
not change the language in any way that would cause it to fail the
regression tests for the language.
8. Aggregation of this Package with a commercial distribution is always
permitted provided that the use of this Package is embedded; that is,
when no overt attempt is made to make this Package's interfaces visible
to the end user of the commercial distribution. Such use shall not be
construed as a distribution of this Package.
9. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.
10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The End
{
secrets => ['14283e549647774b17d10e1d75bcf16c2969673e'],
oauth_url => 'https://auth.pirati.cz/auth/realms/pirati',
pretix_api => 'https://pretix.pir-test.eu/api/v1',
pretix_token => 'rxr4dcx9jnyv50jfd8xdamxjwo3j89503y3upiy1830hpv76is9zqd80c27r5gjk',
pretix_organizer => 'pirati',
pretix_event => 'cf2022',
}
version: '3.3'
services:
app:
image: cf2022
ports:
- 3000:3000
environment:
MOJO_REVERSE_PROXY: 1
MOJO_MODE: development
CFG_PRETIX_API: https://pretix.pir-test.eu/api/v1
CFG_PRETIX_TOKEN: rxr4dcx9jnyv50jfd8xdamxjwo3j89503y3upiy1830hpv76is9zqd80c27r5gjk
CFG_REDIS: redis://redis
volumes:
- ".:/opt/cf2022"
redis:
image: redis:alpine
package CF2022;
use Mojo::Base 'Mojolicious';
use Mojo::Redis;
# This method will run once at server start
sub startup {
my $self = shift;
my $cfg = $self->plugin('Config' => { file => 'cf2022.conf'} );
$self->helper( cfg => sub { return $cfg; } );
# Konfigurace z ENV ma prednost
KEY:
foreach my $key ( keys %ENV ) {
if ( $key =~ /^CFG_(.+)/i ) {
$cfg->{lc($1)} = $ENV{$key};
}
}
# Redis
# my $redis = Mojo::Redis->new( $cfg->{redis} );
# $self->helper( redis => sub { return $redis; } );
$self->plugin('CF2022::Helpers::Core');
$self->plugin('CF2022::Helpers::Auth');
$self->plugin("OpenAPI" => {
url => $self->home . '/openapi.yaml',
schema => 'v3',
plugins => [qw(+SpecRenderer +Cors +Security)],
render_specification => 1,
render_specification_for_paths => 1,
default_response_codes => [400, 401, 403, 404, 429, 500, 501],
});
$self->defaults(
openapi_cors_allowed_origins => ['*']
);
# Router
my $r = $self->routes;
$r->get('/')->to(cb => sub { shift->redirect_to('/api.html');});
}
1;
package CF2022::Controller::Lists;
use Mojo::Base 'Mojolicious::Controller';
use Mojo::UserAgent;
sub options {
my $c = shift->openapi->valid_input or return;
my $args = $c->validation->output;
my @options = ();
my $url = sprintf ('%s/organizers/%s/events/%s/',
$c->config->{pretix_api},
$c->config->{pretix_organizer},
$c->config->{pretix_event},
);
if ( $args->{type} eq 'variations' ) {
$url .= 'items/' . $args->{product_id} . '/variations/';
}
elsif ( $args->{type} eq 'questions' ) {
$url .= 'questions/';
}
my $ua = Mojo::UserAgent->new;
my $records = $ua->get( $url, {
Authorization => 'Token ' . $c->config->{pretix_token}
} )->result->json;
RECORD:
foreach my $record ( @{ $records->{results} } ) {
if ( $args->{type} eq 'questions' ) {
next RECORD if $record->{hidden};
push @options, {
value => $record->{id},
label => $record->{question}{en},
price => 0,
};
}
elsif ( $args->{type} eq 'variations' ) {
next RECORD if $record->{hidden};
push @options, {
value => $record->{id},
label => $record->{value}{en},
price => $record->{price} + 0,
};
}
}
$c->render(openapi => \@options);
}
1;
package CF2022::Helpers::Auth;
use base 'Mojolicious::Plugin';
use Mojo::UserAgent;
use Mojo::JWT;
use feature 'signatures';
no warnings qw{ experimental::signatures };
use constant KEY_FORMAT => "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----";
use constant REGIONS => qr{^(jhc|jhm|kvk|lbk|msk|olk|pak|pha|plk|stc|ulk|vys|zlk|khk):(f|regp)$};
sub register ( $class, $self, $conf) {
my $ua = Mojo::UserAgent->new();
my ( $jwt, $groups);
$self->helper( jwt => sub {
if ( ! $jwt ) {
if ( $self->cfg->{test} && $self->cfg->{test_auth_jwt_secret}) {
$jwt = Mojo::JWT->new(
secret => $self->cfg->{test_auth_jwt_secret}
);
return $jwt;
}
my $res;
eval { $res = $ua->get( $self->cfg->{oauth_url} )->result; };
if (! $@ && $res->is_success) {
$jwt = Mojo::JWT->new(
public => sprintf( KEY_FORMAT, $res->json->{public_key} )
);
}
}
return $jwt;
});
$self->helper( oauth_groups => sub ( $c ) {
if ( ! $groups ) {
my $res;
eval { $res = $ua->get( $self->cfg->{groups_url} )->result; };
if (! $@ && $res->is_success) {
my $json = $res->json;
$groups = { map { $_->{code} => $_->{name} } @{ $json } };
}
}
return $groups;
});
$self->helper( oauth_token => sub ( $c, $token='' ) {
$c->stash->{token} //= $token;
return $c->stash->{token};
});
$self->helper( oauth_claims => sub ( $c ) {
if ( ! $c->stash->{claims}) {
return undef if ! ($c->jwt && $c->oauth_token);
my $claims;
eval { $claims = $c->jwt->decode( $c->oauth_token ); };
if ( $@ ) {
$c->app->log->warn("Invalid token ($@)");
}
$c->stash->{claims} = $claims;
}
return $c->stash->{claims};
});
$self->helper( oauth_main_group_name => sub ( $c ) {
my $claims = $c->oauth_claims // return;
GROUP:
foreach my $group ( sort @{ $claims->{groups} } ) {
return $c->oauth_groups->{ $group } if $group =~ REGIONS;
}
});
$self->helper( user => sub ( $c ) {
my $claims = $c->oauth_claims // return undef;
if ( ! $c->stash->{user} ) {
$c->stash->{user} = {
uuid => $claims->{sub},
username => $claims->{preferred_username},
name => $claims->{name},
# groups => $claims->{groups},
main_group_name => $c->oauth_main_group_name(),
};
}
return $c->stash->{user};
});
}
1;
__END__
package CF2022::Helpers::Core;
use base 'Mojolicious::Plugin';
use feature 'signatures';
no warnings qw{ experimental::signatures } ;
use YAML;
use Mojo::JWT;
sub register ($class, $self, $conf) {
$self->helper(error => sub ($c, $status, $msg) {
if ( ref $msg eq 'ARRAY' ) {
$errors = $msg;
}
elsif ( ref $msg eq 'HASH' ) {
$errors = [ $msg ];
}
else {
$errors = [{
message => $msg,
path => $c->stash('openapi.path'),
}];
}
$c->stash(
status => $status,
openapi => {
status => $status,
errors => $errors,
},
);
return undef;
});
$self->helper( trace => sub( $c, $data='' ) {
$data = Dump $data if ref $data;
$c->app->log->debug($data);
});
$self->helper( spec_filter => sub ($c, $data, $class) {
if (my $def =$c->openapi->spec("/components/schemas/$class")) {
my $filtered = {};
KEY:
foreach my $key ( keys %{ $def->{properties} } ) {
my $value = $data->{$key};
my $nullable = 0;
my $types = $def->{properties}{$key}{type};
if ( ref $types eq 'ARRAY' ) {
TYPE:
foreach my $type ( @{ $types } ) {
$nullable = 1, last if $type eq 'null';
}
}
$filtered->{$key} = $value;
}
$data = $filtered;
}
return $data;
});
}
1;
openapi: 3.0.3
info:
version: "2.0"
title: CF 2022
description: CF 2022
license:
name: Artistic License 2.0
url: https://www.perlfoundation.org/artistic-license-20.html
contact:
name: Andrej Ramašeuski
email: andrej.ramaseuski@pirati.cz
url: https://pardubicky.pirati.cz/lide/andrej-ramaseuski/
servers:
- url: https://cf2022.pirati.cz/api
description: Production server
- url: https://cf2022.pir-test.eu/api
description: Developement server
- url: http://127.0.0.1:3000/api
description: Local server
components:
schemas:
Response:
type: object
properties:
request_id:
type: string
response:
type: string
Option:
type: object
properties:
value:
type: string
label:
type: string
price:
type: integer
paths:
/options/{type}/:
get:
x-mojo-to: lists#options
tags:
- options
summary: "Options"
operationId: getOptions
parameters:
- name: type
in: path
description: List ID
required: true
schema:
type: string
enum: ['variations', 'questions']
- name: product_id
in: query
description: Product ID for variations
required: false
schema:
type: integer
responses:
200:
description: Options list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Option'
openapi: 3.0.3
info:
version: "2.0"
title: CF 2022
description: CF 2022
license:
name: Artistic License 2.0
url: https://www.perlfoundation.org/artistic-license-20.html
contact:
name: Andrej Ramašeuski
email: andrej.ramaseuski@pirati.cz
url: https://pardubicky.pirati.cz/lide/andrej-ramaseuski/
servers:
- url: https://cf2022.pirati.cz/api
description: Production server
- url: https://cf2022.pir-test.eu/api
description: Developement server
- url: http://127.0.0.1:3000/api
description: Local server
components:
schemas:
Response:
type: object
properties:
request_id:
type: string
response:
type: string
Option:
type: object
properties:
value:
type: string
label:
type: string
price:
type: string
paths:
/options:
get:
x-mojo-to: lists#options
tags:
- options
summary: "Options"
operationId: getOptions
parameters:
- name: list
in: query
description: List ID
type: string
required: true
enum: ['lunch', 'questions']
responses:
200:
description: Options list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Option'
/orders:
post:
x-mojo-to: orders#create
tags:
- orders
summary: "Vytvorit registraci"
operationId: createOrder
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
type:
type: integer
enum: [1, 2, 3]
example: 1
token:
type: string
name:
type: string
maxLength: 128
example: 'Ivan Bartoš'
email:
type: string
maxLength: 128
example: 'ivan.bartos@pirati.cz'
organization:
type: string
example: 'ČTK'
lunch:
type: integer
example: 2
party:
type: array
items:
type: integer
responses:
type: array
items:
$ref: '#/components/schemas/Response'
example:
- question_id: 1
response: XXXXX
- question_id: 2
response: ZZZZZ
notes:
type: string
required:
- type
- name
- email
responses:
201:
description: Order created
content:
application/json:
schema:
type: object
properties:
url:
type: string
description: Tickets url
status (potrebuje platbu) - 'n', jinak 'p'
email
payment_provider "manual" ? "free"
positions
[
]
iPOST /api/v1/organizers/bigevents/events/sampleconf/orders/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
{
"email": "dummy@example.org",
"locale": "en",
"sales_channel": "web",
"fees": [
{
"fee_type": "payment",
"value": "0.25",
"description": "",
"internal_type": "",
"tax_rule": 2
}
],
"payment_provider": "banktransfer",
"invoice_address": {
"is_business": false,
"company": "Sample company",
"name_parts": {"full_name": "John Doe"},
"street": "Sesam Street 12",
"zipcode": "12345",
"city": "Sample City",
"country": "UK",
"state": "",
"internal_reference": "",
"vat_id": ""
},
"positions": [
{
"positionid": 1,
"item": 1,
"variation": null,
"price": "23.00",
"attendee_name_parts": {
"full_name": "Peter"
},
"attendee_email": null,
"addon_to": null,
"answers": [
{
"question": 1,
"answer": "23",
"options": []
}
],
"subevent": null
}
]
}
#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::File qw(curfile);
use lib curfile->dirname->sibling('lib')->to_string;
use Mojolicious::Commands;
# Start command line interface for application
Mojolicious::Commands->start_app('CF2022');
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment