From 9e09dcea8485ea325c1b893d24af723d3f27559b Mon Sep 17 00:00:00 2001
From: b3yond <b3yond@riseup.net>
Date: Thu, 22 Mar 2018 11:22:28 +0100
Subject: [PATCH] fixed db init, fixed confirmation mails, added logout button

---
 db.py                 | 21 +++++++++++++++++----
 template/settings.tpl |  2 ++
 template/wrapper.tpl  |  2 +-
 ticketfrei-web.py     | 18 ++++++++++++------
 4 files changed, 32 insertions(+), 11 deletions(-)

diff --git a/db.py b/db.py
index 657b60b..d8e9a08 100644
--- a/db.py
+++ b/db.py
@@ -5,6 +5,9 @@ import jwt
 from os import path, urandom
 from pylibscrypt import scrypt_mcf, scrypt_mcf_check
 import sqlite3
+import pytoml as toml
+import sendmail
+import smtplib
 
 
 class DB(object):
@@ -15,9 +18,12 @@ class DB(object):
         self.conn = sqlite3.connect(dbfile)
         self.cur = self.conn.cursor()
         self.cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='user';")
-        if self.cur.fetchone()[0] != 'user':
+        if self.cur.fetchall() == []:
             self.create()
+            print("Initialized new sqlite database.")
         self.secret = urandom(32)
+        with open('config.toml') as configfile:
+            self.config = toml.load(configfile)
 
     def create(self):
         # init db
@@ -112,10 +118,10 @@ class DB(object):
                          (email, ))
         row = self.cur.fetchone()
         if not row:
-            return None
-        if not scrypt_mcf_check(row[1].decode('ascii').encode("utf-8"),
+            return None  # No user with this email
+        if not scrypt_mcf_check(row[1].encode("utf-8"),
                                 password.encode('utf-8')):
-            return None
+            return None  # Wrong passphrase
         return User(self, row[0])
 
     def by_email(self, email):
@@ -125,6 +131,13 @@ class DB(object):
             return None
         return User(self, row[0])
 
+    def send_confirmation_mail(self, confirm_link, email):
+        m = sendmail.Mailer(self.config)
+        try:
+            m.send("Complete your registration here: " + confirm_link, email, "[Ticketfrei] Confirm your account")
+        except smtplib.SMTPRecipientsRefused:
+            return "Please enter a valid E-Mail address."
+
     def close(self):
         self.conn.close()
 
diff --git a/template/settings.tpl b/template/settings.tpl
index aeb87eb..c77ec72 100644
--- a/template/settings.tpl
+++ b/template/settings.tpl
@@ -1,4 +1,6 @@
 % rebase('template/wrapper.tpl')
+<a href="/logout/"><button>Logout</button></a>
+
 <div id="enablebutton" style="float: right; padding: 2em;">asdf</div>
 
 <a class='button' style="padding: 1.5em;" href="/login/twitter">
diff --git a/template/wrapper.tpl b/template/wrapper.tpl
index cff6633..d8afb75 100644
--- a/template/wrapper.tpl
+++ b/template/wrapper.tpl
@@ -12,7 +12,7 @@
 </head>
 <body>
     <div id="content">
-        <img src="/static/img/ticketfrei_logo.png" alt="Ticketfrei" id="logo">
+        <a href="/"><img src="/static/img/ticketfrei_logo.png" alt="<h1>Ticketfrei</h1>" id="logo"></a>
         % if defined('error'):
         <div class="ui-widget">
             <div class="ui-state-error ui-corner-all" style="padding: 0.7em;">
diff --git a/ticketfrei-web.py b/ticketfrei-web.py
index c03428d..5d93371 100644
--- a/ticketfrei-web.py
+++ b/ticketfrei-web.py
@@ -6,9 +6,7 @@ from db import DBPlugin
 @get('/')
 @view('template/propaganda.tpl')
 def propaganda():
-    # clear auth cookie
-    response.set_cookie('uid', '', expires=0)
-
+    pass
 
 @post('/register', db='db')
 @view('template/register.tpl')
@@ -21,9 +19,9 @@ def register_post(db):
     if db.by_email(email):
         return dict(error='Email address already in use.')
     # send confirmation mail
-    # XXX
-    return dict(info='<a href="%s/../confirm/%s">Confirmation mail sent.</a>' %
-                (request.url, db.token(email, password)))
+    confirm_link = request.url + "/../confirm/" + db.token(email, password)
+    db.send_confirmation_mail(confirm_link, email)
+    return dict(info='Confirmation mail sent.')
 
 
 @get('/confirm/<token>', db='db')
@@ -31,6 +29,7 @@ def register_post(db):
 def confirm(db, token):
     # create db-entry
     if db.register(token):
+        # :todo show info "Account creation successful."
         return redirect('/settings')
     return dict(error='Account creation failed.')
 
@@ -60,6 +59,13 @@ def api_enable(user):
 def static(filename):
     return bottle.static_file(filename, root='static')
 
+@get('/logout/')
+def logout():
+    # clear auth cookie
+    response.set_cookie('uid', '', expires=0, path="/")
+    # :todo show info "Logout successful."
+    return redirect('/')
+
 
 bottle.install(DBPlugin('/'))
 bottle.run(host='localhost', port=8080)