Skip to content

Commit

Permalink
Add allow CORS to /api fetch only routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasamato committed Apr 14, 2021
1 parent e81360c commit 5edde27
Show file tree
Hide file tree
Showing 7 changed files with 207 additions and 42 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
.pub-cache/
.pub/
/build/
.pubspec.lock
pubspec.lock

# Environments
.env
Expand Down
36 changes: 36 additions & 0 deletions Dockerfile-api-only
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
FROM python:3.9-slim-buster

ENV AUDIT_WEBHOOK=""
ENV DISCORD_CLIENT_ID=00000000000
ENV DISCORD_CLIENT_SECRET="your_discord_client_secret"
ENV DISCORD_REDIRECT_URI="https://piracy.moe/user/callback/"
ENV DISCORD_BOT_TOKEN="your_discord_bot_token"

VOLUME ["/config"]
EXPOSE 8080
HEALTHCHECK CMD curl --fail http://localhost:8080 || exit 1

LABEL org.opencontainers.image.vendor="/r/animepiracy" \
org.opencontainers.image.url="https://piracy.moe" \
org.opencontainers.image.description="Webserver of piracy.moe Index" \
org.opencontainers.image.title="Index" \
maintainer="Community of /r/animepiracy"

# copy python requirements beforehand for improved building caching
COPY api/requirements.txt .

# install nginx and needed python packages
RUN apt-get update -y && \
apt-get install --no-install-recommends -y nginx makepasswd wget && \
apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/* && \
pip install --no-cache-dir -r requirements.txt

# replace default nginx conf
COPY nginx.conf /etc/nginx/conf.d/default.conf

WORKDIR /app
COPY api .

# sed is for replacing windows newline
CMD sed -i 's/\r$//' start.sh && sh start.sh
7 changes: 7 additions & 0 deletions api/queries.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import logging
import os

from flask import jsonify, Blueprint

Expand All @@ -14,6 +15,12 @@ def health():
return "Ok"


@bp.after_request
def apply_caching(response):
response.headers["Access-Control-Allow-Origin"] = "*"
return response


# ------------------------------------------------------------------------------
# tables endpoint
# ------------------------------------------------------------------------------
Expand Down
112 changes: 112 additions & 0 deletions lib/api.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import 'dart:convert';

import 'package:http/http.dart' as http;

// for debugging only, on prod everything will be relative, meaning domain = ""
var domain = "http://localhost:8080";

class Tab {
final int id;
String name;
String description;
List<int> tables;

Tab(this.id, this.name, this.description);

factory Tab.fromJson(Map<String, dynamic> json) {
return Tab(json["id"], json["name"], json["description"]);
}

static Future<Tab> fetch(int id) async {
return http.get(Uri.parse(domain + '/api/tabs/' + id.toString())).then(
(resp) {
if (resp.statusCode == 200) {
return Tab.fromJson(jsonDecode(resp.body));
}
throw Exception('Failed to load Tab');
},
onError: (e) {
print('Request failed: $e');
},
);
}
}

class Table {
final int id;
String name;
String description;
int tabId;

// data should be fetched via /api/tables/<id>/data
List<int> data;

// columns should be fetched via /api/tables/<id>/columns
List<int> columns;

Table({
this.id,
this.name,
this.description,
this.tabId,
this.data,
this.columns,
});

factory Table.fromJson(Map<String, dynamic> json) {
return Table(
id: json["id"],
name: json["name"],
description: json["description"],
tabId: json["tab_id"],
data: json["data"],
columns: json["columns"],
);
}

static Future<Table> fetch(int id) async {
return http.get(Uri.parse(domain + '/api/tables/' + id.toString())).then(
(resp) {
if (resp.statusCode == 200) {
return Table.fromJson(jsonDecode(resp.body));
}
throw Exception('Failed to load Table');
},
onError: (e) {
print('Request failed: $e');
},
);
}
}

class Column {
final int id;
String name;
String description;
String columnType;

Column({this.id, this.name, this.description, this.columnType});

factory Column.fromJson(Map<String, dynamic> json) {
return Column(
id: json["id"],
name: json["name"],
description: json["description"],
columnType: json["column_type"],
);
}

static Future<Column> fetch(int id) async {
return http.get(Uri.parse(domain + '/api/columns/' + id.toString())).then(
(resp) {
if (resp.statusCode == 200) {
return Column.fromJson(jsonDecode(resp.body));
}
throw Exception('Failed to load Column');
},
onError: (e) {
print('Request failed: $e');
},
);
}
}
87 changes: 48 additions & 39 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,25 +1,38 @@
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:index/api.dart' as api;

var domain = "http://localhost:8080";

void main() {
runApp(MyApp());
var url = Uri.parse(domain + '/api/health');
print("url is $url");
http.get(url).then((value) {
print('Response status: ${value.statusCode}');
print('Response body: ${value.body}');
}, onError: (e) {
print('Request failed: $e');
});
runApp(App());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: '/r/animepiracy Index',
theme: ThemeData(
// todo: someone actually designs this, check the docs out:
// https://flutter.dev/docs/cookbook/design/themes
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
home: LandingPage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
class LandingPage extends StatefulWidget {
LandingPage({Key key, this.title}) : super(key: key);

// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
Expand All @@ -33,55 +46,26 @@ class MyHomePage extends StatefulWidget {
final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
_LandingPageState createState() => _LandingPageState();
}

class _MyHomePageState extends State<MyHomePage> {
class _LandingPageState extends State<LandingPage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
Expand All @@ -98,7 +82,32 @@ class _MyHomePageState extends State<MyHomePage> {
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}

class TabPage extends StatefulWidget {
final int id;

const TabPage({Key key, this.id}) : super(key: key);

@override
_TabPageState createState() => _TabPageState();
}

class _TabPageState extends State<TabPage> {
late Future<api.Tab> tab;

@override
void initState() {
super.initState();
tab = api.Tab.fetch(widget.id);
}

@override
Widget build(BuildContext context) {
// TODO: implement build
throw UnimplementedError();
}
}
3 changes: 2 additions & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: index_web
name: index
description: Flutter UI of /r/animepiracy Index

# The following line prevents the package from being accidentally published to
Expand Down Expand Up @@ -28,6 +28,7 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^0.13.1

dev_dependencies:
flutter_test:
Expand Down
2 changes: 1 addition & 1 deletion test/widget_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import 'package:index_web/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
await tester.pumpWidget(App());

// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
Expand Down

0 comments on commit 5edde27

Please sign in to comment.