updated code to latest version
This commit is contained in:
+45
-32
@@ -1,38 +1,51 @@
|
||||
from flask import Flask, request, jsonify
|
||||
import os
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, Request
|
||||
from dotenv import load_dotenv
|
||||
from ipaddress import ip_address, ip_network
|
||||
import logging
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
|
||||
load_dotenv()
|
||||
app = Flask(__name__)
|
||||
from utils import clone_repository
|
||||
|
||||
@app.before_request
|
||||
def check_authorized():
|
||||
"""
|
||||
Ensure request from allowed ip.
|
||||
"""
|
||||
# prepare variables
|
||||
assert 'ALLOWED_IP_RANGE' in os.environ
|
||||
allowed_ip_range = ip_network(os.getenv['ALLOWED_IP_RANGE'])
|
||||
requesting_ip = ip_address(request.remote_addr)
|
||||
# check that requesting ip is allowed
|
||||
if requesting_ip not in allowed_ip_range:
|
||||
logging.info(f'received request from unauthorised ip: {request.remote_addr}')
|
||||
return jsonify(status='forbidden'), 403
|
||||
logging.info(f'received request from {request.remote_addr}')
|
||||
class GiteaRequest(BaseModel):
|
||||
ref: str
|
||||
before: str
|
||||
after: str
|
||||
compare_url: str
|
||||
commits: List[dict]
|
||||
total_commits: int
|
||||
head_commit: dict
|
||||
repository: dict
|
||||
pusher: dict
|
||||
sender: dict
|
||||
|
||||
@app.before_request
|
||||
def check_media_type():
|
||||
"""
|
||||
Ensure correct Content-Type of request
|
||||
"""
|
||||
if not request.headers.get('Content-Type').lower().startswith('application/json'):
|
||||
logging.error(f'received request with wrong content type')
|
||||
return jsonify(status='unsupported media type'), 415
|
||||
|
||||
@app.route('/test', methods=['POST'])
|
||||
def test():
|
||||
logging.debug(request.get_json(force=True))
|
||||
return jsonify(status='success', sender=request.remote_addr)
|
||||
app = FastAPI()
|
||||
|
||||
@app.get('/')
|
||||
async def root():
|
||||
return '<h1>Welcome to Gitea Runsner</h1>'
|
||||
|
||||
@app.post('/test')
|
||||
async def test(request: Request):
|
||||
""" Test connection to server. """
|
||||
logging.debug('Content-Type: ', request.headers.get('content-type'))
|
||||
return {'status': 'success'}
|
||||
|
||||
@app.post('/event')
|
||||
def handle_event(request: GiteaRequest):
|
||||
""" Handle event from webhook. """
|
||||
# stop early if allowed
|
||||
commit_msg = request.head_commit['message']
|
||||
if commit_msg.lower().startswith('[skip ci]'):
|
||||
return {'status': 'received task'}
|
||||
# clone repository
|
||||
repo_url = request.repository['clone_url']
|
||||
local_repo_dir = clone_repository(repo_url)
|
||||
print('local_repo_dir: ', local_repo_dir)
|
||||
return {'status': 'success'}
|
||||
|
||||
if __name__ == '__main__':
|
||||
uvicorn.run(
|
||||
app=app,
|
||||
host='0.0.0.0'
|
||||
)
|
||||
Reference in New Issue
Block a user