Source

hash-m4cf1 / server.py

import dbm
import uuid
import datetime
import hashlib
import flask
from functools import wraps

app = flask.Flask(__name__)
app.debug = True
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

#filename = '/var/lib/openshift/8c4153892ceb43388ab5a17e692e7981/
#app-root/runtime/repo/wsgi/macfri'

DATABASE_FILE = 'm4cf1'
#WAIT_FOR_TOKEN = 30000
WAIT_FOR_TOKEN = 15000  # 10 seconds


class Database(object):

    db = None

    def __init__(self):
        self.db = dbm.open(DATABASE_FILE, 'c')

    def get(self, k):
        return self.db.get(k)

    def set(self, k, v):
        self.db[k] = v

    def close(self):
        self.db.close()


def generate_clock(clock=None):

    if not clock:

        base_datetime = datetime.datetime.strptime(
            str(datetime.datetime.now())[:19],
            '%Y-%m-%d %H:%M:%S'
        )

        return str(base_datetime).replace(
                '-', '').replace(' ', '').replace(':', '')[:-2] + '00'

    else:

        time = datetime.datetime.strptime(clock,
            '%Y%m%d%H%M%S') + datetime.timedelta(seconds=60)

        time = str(time).replace(
            '-', '').replace(' ', '').replace(':', '')

        return time


def generate_code(seed):

    ziff = hashlib. sha224(seed).hexdigest()
    return ''.join([x for x in ziff if x.isdigit()][:6])


def generate_seed(clock, master_seed=None):

    if not master_seed:
        master_seed = str(uuid.uuid4()).replace('-', '')
    return master_seed + clock


def autehnticated(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not flask.session.get('email'):

            return flask.redirect(flask.url_for('login'))

            #flask.abort(403)
        return f(*args, **kwargs)
    return decorated


@app.route('/')
def index():

    email = flask.session.get('email')

    if email:

        return flask.redirect(flask.url_for('get_token'))

    return flask.render_template(
        'index.html'
    )


@app.route('/login', methods=['POST', 'GET'])
def login():

    if flask.request.method == 'POST':

        db = Database()
        email = flask.request.form.get('email')
        exists_email = db.get(email)
        db.close()

        if not exists_email:
            return flask.redirect(flask.url_for('register'))
        else:
            flask.session['email'] = email
            return flask.redirect(flask.url_for('get_token'))

    else:
        return flask.render_template(
            'login.html',
        )


@app.route('/logout')
def logout():

    flask.session.pop('email', None)
    return flask.redirect(flask.url_for('login'))


@app.route('/get_token')
@autehnticated
def get_token():

    db = Database()

    email = flask.session.get('email')
    seed = db.get(email)
    db.close()

    return flask.render_template(
        'token.html',
        code=generate_code(seed),
        wait_for_token=WAIT_FOR_TOKEN,
        email=email
    )


@app.route('/get_token_each_time', methods=['GET'])
@autehnticated
def get_token_each_time():

    db = Database()

    email = flask.session.get('email')
    master_seed = db.get(email)
    base = master_seed[0:-14]
    time = master_seed[-14:]

    seed = generate_seed(generate_clock(time), base)
    db.set(email, seed)
    db.close()

    return flask.jsonify(code=generate_code(seed))


@app.route('/check', methods=['POST', 'GET'])
def check():

    email = flask.session.get('email')
    status_code = None

    if flask.request.method == 'POST':

        email = flask.request.form.get('email')
        code = flask.request.form.get('code')

        db = Database()

        if not db.get(email) or not code:
            status_code = 3

        else:
            seed = db.get(email)

            if code == generate_code(seed):
                status_code = 1
            else:
                status_code = 2

        db.close()
        app.logger.info('status_code: %s' % status_code)

    return flask.render_template(
        'check.html',
        status_code=status_code,
        email=email
    )


@app.route('/register', methods=['POST', 'GET'])
def register():

    status_code = None

    if flask.request.method == 'POST':

        email = flask.request.form.get('email')
        name = flask.request.form.get('name')

        if not email or not name:

            status_code = 1

        else:

            db = Database()

            if db.get(email):
                status_code = 2

            else:

                db.set(email, generate_seed(generate_clock()))
                db.set('%s_name' % email, name)

                flask.session['email'] = email
                db.close()
                return flask.redirect(flask.url_for('get_token'))

            db.close()

        app.logger.info('status_code: %s' % status_code)

    return flask.render_template(
        'register.html',
        status_code=status_code
    )


if __name__ == '__main__':
    app.run()