#!/usr/bin/env python
import os
import subprocess
from flask import Flask, abort, request, jsonify, g, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)

# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Cyber Security People go crazy all the time because they are overworked!!!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

# extensions
db = SQLAlchemy(app)
auth = HTTPBasicAuth()


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), index=True)
    password_hash = db.Column(db.String(128))

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)


@auth.verify_password
def verify_password(username, password):
    user = User.query.filter_by(username = username).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True


@app.route('/api/users', methods=['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)    # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)    # existing user
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return (jsonify({'username': user.username}), 201,
            {'Location': url_for('get_user', id=user.id, _external=True)})


@app.route('/api/users/<int:id>')
def get_user(id):
    user = User.query.get(id)
    if not user:
        abort(400)
    return jsonify({'username': user.username})


@app.route('/api/OpenFireWallPort')
@auth.login_required
def Add_IP_To_Rules():
    IPAddress = request.remote_addr
    iptables_command = ['sudo iptables -A INPUT -s ' + str(IPAddress) + ' -j ACCEPT' ]
    retcode = subprocess.call(iptables_command, shell=True)
    if retcode != 0:
            response = "Bad Request"
    else:
            response = "New Rule Created"
    return response

@app.route('/api/CloseFireWallPort')
@auth.login_required
def Delete_IP_From_Rules():
    IPAddress = request.remote_addr
    iptables_command = ['sudo iptables -D INPUT -s ' + str(IPAddress) + ' -j ACCEPT' ]
    retcode = subprocess.call(iptables_command, shell=True)
    if retcode != 0:
            response = "Bad Request"
    else:
            response = "Firewall Rule Deleted"
    return response

if __name__ == '__main__':
    if not os.path.exists('db.sqlite'):
        db.create_all()
    app.run(host='0.0.0.0', debug=True)