Commits

ronald martinez committed 7eadaf8 Merge

ok

Comments (0)

Files changed (6)

Empty file removed.

 import datetime
 import hashlib
 import flask
+from functools import wraps
 
 app = flask.Flask(__name__)
 app.debug = True
 
 DATABASE_FILE = 'm4cf1'
 #WAIT_FOR_TOKEN = 30000
+<<<<<<< HEAD
 WAIT_FOR_TOKEN = 10000  # 10 seconds
+=======
+WAIT_FOR_TOKEN = 15000  # 10 seconds
+>>>>>>> dev
 
 
-class database(object):
+class Database(object):
 
     db = None
 
 
     def set(self, k, v):
         self.db[k] = v
-        self.close()
 
     def close(self):
         self.db.close()
 
 
-def clock():
+def generate_clock(clock=None):
 
-    base_datetime = datetime.datetime.strptime(
-        str(datetime.datetime.now())[:19],
-        '%Y-%m-%d %H:%M:%S'
-    )
+    if not clock:
 
-    return str(base_datetime).replace(
-            '-', '').replace(' ', '').replace(':', '')[:-2] + '00'
+        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):
+    else:
 
-    ziff = hashlib. sha224(seed).hexdigest()
-    return ''.join([x for x in ziff if x.isdigit()][:6])
+        time = datetime.datetime.strptime(clock,
+            '%Y%m%d%H%M%S') + datetime.timedelta(seconds=60)
 
+        time = str(time).replace(
+            '-', '').replace(' ', '').replace(':', '')
 
-@app.route('/token')
-def token():
+        return time
 
-    code = None
-    email = flask.session.get('email')
 
-    if not email:
-        return flask.redirect(flask.url_for('login'))
-    else:
+def generate_code(seed):
 
-        _database = database()
-        seed = _database.get(email)
-        _database.close()
+    ziff = hashlib. sha224(seed).hexdigest()
+    return ''.join([x for x in ziff if x.isdigit()][:6])
 
-        code = generate_code(seed)
 
-        time_db = datetime.datetime.strptime(seed[-14:],
-            '%Y%m%d%H%M%S')
+def generate_seed(clock, master_seed=None):
 
-        seconds = (datetime.datetime.now() - time_db).seconds
-        seconds = 30 - seconds
+    if not master_seed:
+        master_seed = str(uuid.uuid4()).replace('-', '')
+    return master_seed + clock
 
-        print 'time_db', time_db
-        print 'seconds', seconds
-        seconds = seconds * 1000
-        print 'seconds', seconds
 
-        seconds = WAIT_FOR_TOKEN
+def autehnticated(f):
+    @wraps(f)
+    def decorated(*args, **kwargs):
+        if not flask.session.get('email'):
 
-    return flask.render_template(
-        'token.html',
-        code=code,
-        wait_for_token=WAIT_FOR_TOKEN,
-        seconds=seconds
-    )
+            return flask.redirect(flask.url_for('login'))
+
+            #flask.abort(403)
+        return f(*args, **kwargs)
+    return decorated
 
 
 @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.redirect(flask.url_for('get_token'))
 
     return flask.render_template(
-        'index.html',
-        code=code
+        'index.html'
     )
 
 
 def login():
 
     if flask.request.method == 'POST':
-        email = flask.request.form.get('email')
-        _database = database()
-
-        if not _database.get(email):
 
+<<<<<<< HEAD
             seed = str(uuid.uuid4()).replace('-', '') + clock()
             _database.set(email, seed)
+=======
+        db = Database()
+        email = flask.request.form.get('email')
+        exists_email = db.get(email)
+        db.close()
+>>>>>>> dev
 
-        _database.close()
-        flask.session['email'] = email
-        return flask.redirect(flask.url_for('token'))
+        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('/get_code', methods=['GET'])
-def get_code():
+@app.route('/logout')
+def logout():
 
-    code = None
-    email = flask.session.get('email')
+    flask.session.pop('email', None)
+    return flask.redirect(flask.url_for('login'))
 
-    if email:
 
-        _database = database()
-        seed = _database.get(email)
+@app.route('/get_token')
+@autehnticated
+def get_token():
 
+<<<<<<< HEAD
         print "*" * 50
         print 'SEED', seed
         print "*" * 50
+=======
+    db = Database()
+>>>>>>> dev
 
-        base = seed[0:-14]
-        time = seed[-14:]
-        time_db = datetime.datetime.strptime(time,
-            '%Y%m%d%H%M%S')
+    email = flask.session.get('email')
+    seed = db.get(email)
+    db.close()
 
-        seconds = (datetime.datetime.now() - time_db).seconds
-        #seconds = 30 - seconds
+    return flask.render_template(
+        'token.html',
+        code=generate_code(seed),
+        wait_for_token=WAIT_FOR_TOKEN,
+        email=email
+    )
 
+
+<<<<<<< HEAD
         time = datetime.datetime.strptime(time,
             '%Y%m%d%H%M%S') + datetime.timedelta(seconds=60)
+=======
+@app.route('/get_token_each_time', methods=['GET'])
+@autehnticated
+def get_token_each_time():
 
-        time = str(time).replace(
-            '-', '').replace(' ', '').replace(':', '')
+    db = Database()
+>>>>>>> dev
+
+    email = flask.session.get('email')
+    master_seed = db.get(email)
+    base = master_seed[0:-14]
+    time = master_seed[-14:]
 
-        new_seed = base + time
-        code = generate_code(new_seed)
-        _database.set(email, new_seed)
-        _database.close()
+    seed = generate_seed(generate_clock(time), base)
+    db.set(email, seed)
+    db.close()
 
-    return flask.jsonify(value=code)
+    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')
 
-        _database = database()
+        db = Database()
 
-        if not _database.get(email) or not code:
+        if not db.get(email) or not code:
             status_code = 3
 
         else:
-            seed = _database.get(email)
+            seed = db.get(email)
 
             if code == generate_code(seed):
                 status_code = 1
             else:
                 status_code = 2
 
-        _database.close()
+        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
     )
 

templates/header.html

 
 
-<table width="300px" border="0" align="right">
+<table width="400px" border="0" align="right">
     <tr>
         <td align="right">
-            <a href="/login">Login</a>&nbsp;|&nbsp;
-            <a href="/check">Check Token</a>&nbsp;|&nbsp;
-            <a href="/token">Token</a>
+
+            {% 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>

templates/index.html

 
 </head>
 <body>
-
-
-</head>
-<body>
-
     {% include 'header.html' %}
-
-
 </body>
 </html>

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>
+

templates/token.html

 <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
 <script>
     function get_code(){
-        $.getJSON('/get_code', function(data) {
-            $("#code").html(data['value'])
+        $.getJSON('/get_token_each_time', function(data) {
+            $("#code").html(data['code'])
         });
         setTimeout(get_code, {{ wait_for_token }});
     }
 
-    setTimeout(get_code, {{ seconds }});
+    setTimeout(get_code, {{ wait_for_token }});
 </script>
 </head>
 <body>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.