nix-channel-redirect/nix_channel_server/app.py

64 lines
2.1 KiB
Python

#!/usr/bin/env python3
"""Selfprivacy nix channel server."""
import os
import requests
from flask import Flask, request, jsonify, redirect
from flask_restful import Api, Resource, reqparse
# Read the current nixos channel URL from file channel_url.txt
current_channel = open("channel_url.txt", "r").read().strip()
class Channel(Resource):
def get(self):
"""GET request returns the 301 redirect to the
current validated NixOS channel
"""
return redirect(current_channel, code=301)
def post(self):
"""POST a new channel, save it to file and update
current variable"""
parser = reqparse.RequestParser()
parser.add_argument('channel', type=str, required=True,
help="Channel URL is required")
args = parser.parse_args()
channel = args['channel']
# Save the new channel to file
with open("channel_url.txt", "w") as f:
f.write(channel)
# Update the current channel
current_channel = channel
return jsonify({"message": "Channel updated"})
class GetNewChannel(Resource):
def post(self):
r = requests.get("https://nixos.org/channels/nixos-22.05")
channel = r.url
# Save the new channel to file
with open("channel_url.txt", "w") as f:
f.write(channel)
# Update the current channel
current_channel = channel
return jsonify({"message": "Channel updated", "channel": channel})
def create_app():
app = Flask(__name__)
api = Api(app)
app.config['AUTH_KEY'] = os.environ.get('AUTH_KEY') or 'secret!'
@app.before_request
def before_request():
# If request is not GET, check if the auth key is correct
if request.method != 'GET':
if request.headers.get('Authorization') != app.config['AUTH_KEY']:
return jsonify({"message": "Invalid auth key"}), 401
api.add_resource(Channel, '/nixos-selfpricacy')
api.add_resource(GetNewChannel, '/nixos-selfpricacy/upgrade')
return app
if __name__ == '__main__':
app = create_app()
app.run(debug=False)