Source

hash-m4cf1 / server.py

Full commit
import dbm
import uuid
import datetime
import hashlib
import flask

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 = 10000  # 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
        self.close()

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


def 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'


def generate_code(seed):

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


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

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

    if not email:
        return flask.redirect(flask.url_for('login'))
    else:

        _database = database()
        seed = _database.get(email)
        _database.close()

        code = generate_code(seed)

        time_db = datetime.datetime.strptime(seed[-14:],
            '%Y%m%d%H%M%S')

        seconds = (datetime.datetime.now() - time_db).seconds
        seconds = 30 - seconds

        print 'time_db', time_db
        print 'seconds', seconds
        seconds = seconds * 1000
        print 'seconds', seconds

        seconds = WAIT_FOR_TOKEN

    return flask.render_template(
        'token.html',
        code=code,
        wait_for_token=WAIT_FOR_TOKEN,
        seconds=seconds
    )


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

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

    if email:
        _database = database()
        seed = _database.get(email)
        _database.close()
        code = generate_code(seed)

    return flask.render_template(
        'index.html',
        code=code
    )


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

    if flask.request.method == 'POST':
        email = flask.request.form.get('email')
        _database = database()

        if not _database.get(email):

            seed = str(uuid.uuid4()).replace('-', '') + clock()
            _database.set(email, seed)

        _database.close()
        flask.session['email'] = email
        return flask.redirect(flask.url_for('token'))

    else:

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


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

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

    if email:

        _database = database()
        seed = _database.get(email)

        print "*" * 50
        print 'SEED', seed
        print "*" * 50

        base = seed[0:-14]
        time = seed[-14:]
        time_db = datetime.datetime.strptime(time,
            '%Y%m%d%H%M%S')

        seconds = (datetime.datetime.now() - time_db).seconds
        #seconds = 30 - seconds

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

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

        new_seed = base + time
        code = generate_code(new_seed)
        _database.set(email, new_seed)
        _database.close()

    return flask.jsonify(value=code)


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

    status_code = None

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

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

        _database = database()

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

        else:
            seed = _database.get(email)

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

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

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


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