Commits

ronald martinez  committed 698ff1d

ok

  • Participants
  • Parent commits c2ef99e

Comments (0)

Files changed (8)

File requirements.txt

+Flask==0.9
+Jinja2==2.6
+Werkzeug==0.8.3
+wsgiref==0.1.2
+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()

File templates/check.html

+<!DOCTYPE html>
+<html>
+    <head>
+        <style>
+table.imagetable {
+	font-family: verdana,arial,sans-serif;
+	font-size:11px;
+	color:#333333;
+	border-width: 1px;
+	border-color: #999999;
+	border-collapse: collapse;
+}
+table.imagetable th {
+	background:#b5cfd2 url('cell-blue.jpg');
+	border-width: 1px;
+	padding: 8px;
+	border-style: solid;
+	border-color: #999999;
+}
+table.imagetable td {
+	background:#dcddc0 url('cell-grey.jpg');
+	border-width: 1px;
+	padding: 8px;
+	border-style: solid;
+	border-color: #999999;
+}
+</style>
+</head>
+<body>
+
+
+{% if status_code %}
+    {% if status_code == 1 %}
+        OK
+    {% elif status_code == 3 %}
+        No email or code
+    {% elif status_code == 2 %}
+        Invañido codigo
+    {% endif %}
+{% endif %}
+
+<form method="post">
+    {% include 'header.html' %}
+    <table class="imagetable" align="center">
+        <tr>
+            <th>Email</th>
+            <td><input type="text" name="email"></td>
+        </tr>
+        <tr>
+            <th>C&oacute;digo</th>
+            <td><input type="text" name="code"></td>
+        </tr>
+        <tr>
+            <td colspan="2" align="center"><input type="submit" size="100" value="Check Code"></td>
+        </tr>
+    </table>
+
+</form>
+
+</body>
+</html>

File templates/header.html

+
+
+<table width="400px" border="0" align="right">
+    <tr>
+        <td align="right">
+
+            {% if email %}
+                <b>{{ email }}</b>
+                <a href="/logout">Logout</a>&nbsp;|&nbsp;
+                <a href="/get_token">Get Token</a>
+            {% else %}
+                <a href="/login">Login</a>&nbsp;|&nbsp;
+                <a href="/register">Register</a>
+            {% endif %}
+
+            &nbsp;|&nbsp; <a href="/check">Check Token</a>
+        </td>
+    </tr>
+</table>
+

File templates/index.html

+<!DOCTYPE html>
+<html>
+<head>
+
+</head>
+<body>
+    {% include 'header.html' %}
+</body>
+</html>

File templates/login.html

+<!DOCTYPE html>
+<html>
+    <head>
+        <style>
+table.imagetable {
+	font-family: verdana,arial,sans-serif;
+	font-size:11px;
+	color:#333333;
+	border-width: 1px;
+	border-color: #999999;
+	border-collapse: collapse;
+}
+table.imagetable th {
+	background:#b5cfd2 url('cell-blue.jpg');
+	border-width: 1px;
+	padding: 8px;
+	border-style: solid;
+	border-color: #999999;
+}
+table.imagetable td {
+	background:#dcddc0 url('cell-grey.jpg');
+	border-width: 1px;
+	padding: 8px;
+	border-style: solid;
+	border-color: #999999;
+}
+</style>
+</head>
+<body>
+
+    {% include 'header.html' %}
+
+<form method="post">
+    <table class="imagetable" align="center">
+    <tr>
+        <th>Email</th>
+        <td><input type="text" name="email"></td>
+    </tr>
+    <tr>
+        <td colspan="2" align="center"><input type="submit" size="100" value="Login"></td>
+    </tr>
+</form>
+
+</body>
+</html>

File templates/register.html

+<!DOCTYPE html>
+<html>
+    <head>
+        <style>
+table.imagetable {
+	font-family: verdana,arial,sans-serif;
+	font-size:11px;
+	color:#333333;
+	border-width: 1px;
+	border-color: #999999;
+	border-collapse: collapse;
+}
+table.imagetable th {
+	background:#b5cfd2 url('cell-blue.jpg');
+	border-width: 1px;
+	padding: 8px;
+	border-style: solid;
+	border-color: #999999;
+}
+table.imagetable td {
+	background:#dcddc0 url('cell-grey.jpg');
+	border-width: 1px;
+	padding: 8px;
+	border-style: solid;
+	border-color: #999999;
+}
+</style>
+</head>
+<body>
+
+
+{% if status_code %}
+    {% if status_code == 1 %}
+        Fill data
+    {% elif status_code == 2 %}
+        exists email
+    {% endif %}
+{% endif %}
+
+<form method="post">
+    {% include 'header.html' %}
+    <table class="imagetable" align="center">
+        <tr>
+            <th>Email</th>
+            <td><input type="text" name="email"></td>
+        </tr>
+        <tr>
+            <th>Name</th>
+            <td><input type="text" name="name"></td>
+        </tr>
+        <tr>
+            <td colspan="2" align="center"><input type="submit" size="100" value="Save User"></td>
+        </tr>
+    </table>
+
+</form>
+
+</body>
+</html>
+

File templates/token.html

+<!DOCTYPE html>
+<html>
+<head>
+<style>
+div.ex
+{
+margin-left:auto;
+margin-right:auto;
+background-color:#b0e0e6;
+font-size: 100px;
+width:320px;
+padding:12px;
+border:15px solid gray;
+}
+</style>
+</head>
+<body>
+<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
+<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
+<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
+<script>
+    function get_code(){
+        $.getJSON('/get_token_each_time', function(data) {
+            $("#code").html(data['code'])
+        });
+        setTimeout(get_code, {{ wait_for_token }});
+    }
+
+    setTimeout(get_code, {{ wait_for_token }});
+</script>
+</head>
+<body>
+    {% include 'header.html' %}
+    <div id="code" class="">{{ code }}</div>
+</body>
+</html>
+