Example #1
0
def index(headers, body, data):
  if headers['request-method'] == 'GET':
    createTokens(dbFile)
    areTokensCreated = True
    
    t = getTokenFromDatabase(dbFile)
    print t
    tokenIsBeingUsed(dbFile, t)
    return render_template('login.html', body=body, data=data, token=t), 200, {}
  else:
    msg = ''
    return render_template('error.html', body=body, data=data, msg=msg), 405, {}
Example #2
0
def logout(headers, body, data):
    cookie = str(headers['http-cookie']).replace('sessionid=', '')
    if not cookie_check(cookie):
        return render_template('html/home.html',
                               body=body,
                               data=data,
                               headers=headers,
                               message='Zostales wylogowany!'), 200, {}
    disable_cookie(cookie)
    return render_template('html/redirect.html',
                           body=body,
                           data=data,
                           headers=headers,
                           message='Trwa wylogowywanie...'), 200, {}
Example #3
0
def postNote(headers, body, data):
  request_method = headers['request-method']

  global areTokensCreated
  if areTokensCreated is False:
      createTokens(dbFile)
      areTokensCreated = True

  global session
  if ('user' in session) and (headers['remote-addr'] == session['ip']):

    if request_method == 'GET':
      print '\nget w notes '
      t = getTokenFromDatabase(dbFile)
      print t
      tokenIsBeingUsed(dbFile, t)
      notes = getNotesFromDatabase(dbFile)

      return render_template('notes.html', body=body, data=data, 
                              notes=notes, username=session['user'], token=t), 200, {}

    elif request_method == 'POST':
      if 'secretIn' in data:
        print '\npost w notes ----> otrzymalem token'
        print data['secretIn']
        if tokenIsUsed(dbFile, data['secretIn']) is False:
          msg = 'You are a hacker.'
          return render_template('error.html', msg=msg), 400, {}

      if len(data) == 0:
        msg = 'You can\'t post an empty note.'
        return render_template('error.html', body=body, data=data, msg=msg), 400, {}

      note = cgi.escape(str(data['noteTextarea']), quote=True)

      try:
        addNoteToDatabase(note, session['user'], dbFile)
      except Exception, e:
        print '\nthere is sth fishy going on. %s\n' % str(e)
        return render_template('error.html', body=body, data=data), 500, {}

      notes = getNotesFromDatabase(dbFile)
      print notes

      t = getTokenFromDatabase(dbFile)
      print t
      tokenIsBeingUsed(dbFile, t)
      return render_template('notes.html', body=body, data=data, 
                              notes=notes, username=session['user'], token=t), 200, {}
Example #4
0
def recovery(headers, body, data):
    question_tuple = questions()
    return render_template('recovery.html',
                           headers=headers,
                           body=body,
                           data=data,
                           questions=question_tuple), 200, {}
Example #5
0
def signup(headers, body, data):
    question_tuple = questions()
    return render_template('signup.html',
                           headers=headers,
                           body=body,
                           data=data,
                           questions=question_tuple), 200, {}
Example #6
0
def insert_new_passwd(headers, body, data):
    db, cursor = pysql.database_connect()

    token = str((AuthCookieFactory()).get_from_headers(headers).get_token())
    if token is None:
        return render_template(
            'unauthorised_request.html',
            body=body,
            data=data,
            message='Anauthorised try to change password!'), 200, {}
    cursor.execute('''SELECT login FROM cookie WHERE token=%s''', token)
    login = str(cursor.fetchone()[0])
    passwd = str(data['pw']) if 'pw' in data else ''
    passwd_r = str(data['pw-x']) if 'pw-x' in data else ''

    salt = uuid.uuid4().hex
    salt_bytes = salt.encode('utf-8')
    if passwd == passwd_r:
        strength, improvements = passwordmeter.test(passwd)
        if strength < 0.3:
            return render_template(
                'passwordchange.html',
                body=body,
                data=data,
                login=login,
                message='Your password is too weak!'), 200, {}
        for i in range(3):
            pw_bytes = passwd.encode('utf-8')
            passwd = hashlib.sha512(pw_bytes + salt_bytes).hexdigest()
        cursor.execute(
            '''UPDATE users SET password= %s, salt= %s WHERE login= %s''',
            (passwd, salt, login))
        db.commit()
        db.close()
        IP, time = pysql.print_ip(login)
        return render_template(
            'mainpage.html',
            body=body,
            data=data,
            IP=IP,
            time=time,
            message='You successfully changed your password!'), 200, {}
    else:
        return render_template('passwordchange.html',
                               body=body,
                               data=data,
                               message='Passwords are not match!'), 200, {}
Example #7
0
def logout(headers, body, data):
  request_method = headers['request-method']

  if request_method == 'GET':
    global session
    session = {}
    t = getTokenFromDatabase(dbFile)
    return render_template('login.html', body=body, data=data, token=t), 200, {}
Example #8
0
def redirect_main(headers, body, data, login):
    IP, time = pysql.print_ip(login)
    return render_template('mainpage.html',
                           headers=headers,
                           body=body,
                           data=data,
                           IP=IP,
                           time=time), 200, {}
Example #9
0
def redirect(headers, body, data, message='Taka strona nie istnieje!'):
    cookie = str(headers['http-cookie']).replace('sessionid=', '')
    return render_template('html/redirect.html',
                           body=body,
                           data=data,
                           headers=headers,
                           message=message), 200, {
                               'Set-Cookie': cookie
                           }
def addsnippet(headers, body, data):
    #login = str(data['login']) if 'login' in data else ''
    # password = str(data['password']) if 'password' in data else ''
    cookie = str(headers['http-cookie']).replace('sessionid=', '')
    if not cookie_check(cookie):
        return redirect(headers=headers,
                        body=body,
                        data=data,
                        message="Nieautoryzowana proba dodania snippet'a!")

    snippet_content = str(data['snippet']) if 'snippet' in data else ''
    title = str(data['title']) if 'title' in data else ''

    if (title == '' or snippet_content == ''):
        return render_template('html/addsnippet.html',
                               body=body,
                               data=data,
                               headers=headers,
                               cookie=cookie), 200, {}
    elif len(title) > 60:
        return render_template(
            'html/addsnippet.html',
            body=body,
            data=data,
            headers=headers,
            cookie=cookie,
            message="Maksymalna dlugosc nazwy snippet'a to 24 znaki!"
        ), 200, {}
    elif len(snippet_content) > 9999:
        return render_template(
            'html/addsnippet.html',
            body=body,
            data=data,
            headers=headers,
            cookie=cookie,
            message="Dodany przez Ciebie plik jest zbyt dlugi!"), 200, {}

    add_snippet(title, snippet_content, cookie)
    return redirect(headers=headers,
                    body=body,
                    data=data,
                    message='Snippet zostal dodany!')
Example #11
0
def put_snippet(headers, body, data):
    db, cursor = pysql.database_connect()
    time = pysql.datetime_mysql()
    snippet = str(data['snippet']) if 'snippet' in data else ''
    title = str(data['title']) if 'title' in data else ''
    snippet = unidecode(snippet)  # decode non-standard letters
    if not check_title(title):
        return render_template(
            'new_snippet.html',
            headers=headers,
            body=body,
            data=data,
            message='Title can only contain letters or digits!'), 200, {}
    if len(title) > 40:
        return render_template('new_snippet.html',
                               headers=headers,
                               body=body,
                               data=data,
                               message='Title is too long!'), 200, {}
    if len(snippet) > 1000:
        return render_template('new_snippet.html',
                               headers=headers,
                               body=body,
                               data=data,
                               message='Snippet is too long!'), 200, {}
    token = str((AuthCookieFactory()).get_from_headers(headers).get_token())
    cursor.execute('''SELECT login FROM cookie WHERE token=%s''', token)
    login = str(cursor.fetchone()[0])
    cursor.execute(
        '''INSERT INTO snippets(login, datetime, title, snippet) VALUES(%s, %s, %s, %s)''',
        (login, time, title, snippet))
    db.commit()
    db.close()
    IP, time = pysql.print_ip(login)
    return render_template('mainpage.html',
                           headers=headers,
                           body=body,
                           data=data,
                           IP=IP,
                           time=time), 200, {}
Example #12
0
def auth(headers, body, data):
    login = str(data['name']) if 'name' in data else ''
    passwd = str(data['pw']) if 'name' in data else ''
    # ip = str(headers['http-x-forwarded-for']) if 'http-x-forwarded-for' in headers else 'PROXY'
    ip = str(headers['remote-addr'])
    if check_auth(login, passwd, ip):
        if ban_ip(login):
            IP, time = pysql.print_ip(login)
            db, cursor = pysql.database_connect()
            cookie = (AuthCookieFactory()).generate()
            cursor.execute('INSERT INTO cookie(login, token) VALUES(%s, %s)',
                           (login, cookie.get_token()))
            db.commit()
            db.close()
            return render_template('mainpage.html',
                                   headers=headers,
                                   body=body,
                                   data=data,
                                   IP=IP,
                                   time=time), 200, {
                                       'Set-Cookie': cookie.return_cookie()
                                   }
        else:
            snippets = get_all_snipets()
            return render_template(
                'index.html',
                body=body,
                data=data,
                snippets=snippets,
                message='Too many wrong attemts to log in! You\'ve banned!')
    else:
        snippets = get_all_snipets()
        return render_template(
            'index.html',
            headers=headers,
            body=body,
            data=data,
            snippets=snippets,
            message='Login or password is incorrect'), 200, {}
Example #13
0
def home(headers, body, data):
    login = str(data['login']) if 'login' in data else ''
    password = str(data['password']) if 'password' in data else ''
    cookie = str(headers['http-cookie']).replace('sessionid=', '')
    # if (login == '') and (password == ''):
    if cookie_check(cookie):
        dbfile = '/home/wolonkia/vial/genbase.db'
        conn = sqlite3.connect(dbfile)
        cursor = conn.cursor()
        cursor.execute('SELECT title, login, time FROM snippets ORDER BY time')
        snippets_result = cursor.fetchall()
        snippets_values = []
        for row in snippets_result:
            snippets_values.append({'title': str(row[0]), 'login': str(row[1]), 'date': str(row[2])})
        cursor.execute('SELECT login FROM users WHERE cookie = ?;', (cookie,))
        login = str(cursor.fetchone()[0])
        print login
        cursor.execute('SELECT ip FROM logs WHERE login = ? ORDER BY date_time DESC', (login,))
        fetch = cursor.fetchall()
        if len(fetch) >= 2:
            if str(fetch[0][0]) != str(fetch[1][0]):
                return render_template('html/home.html', body=body, data=data, headers=headers,
                                       snippets_values=snippets_values,
                                       message='Wykryto nowe polaczenie do Twojego konta z ip: ' + str(
                                           fetch[1][0])), 200, {}
        return render_template('html/home.html', body=body, data=data, headers=headers,
                               snippets_values=snippets_values,
                               message="Witaj '" + login + "'"), 200, {}

    dbfile = '/home/wolonkia/vial/genbase.db'
    conn = sqlite3.connect(dbfile)
    cursor = conn.cursor()
    cursor.execute('SELECT title, login, time FROM snippets ORDER BY time')
    snippets_result = cursor.fetchall()
    snippets_values = []
    for row in snippets_result:
        snippets_values.append({'title': str(row[0]), 'login': str(row[1]), 'date': str(row[2])})
    return render_template('html/home.html', body=body, data=data, headers=headers, snippets_values=snippets_values,
                           message='Witaj na stronie!'), 200, {'Set-Cookie': cookie}
Example #14
0
def insert_new_password(headers, body, data):
    login = str(data['name']) if 'name' in data else ''
    passwd = str(data['pw']) if 'pw' in data else ''
    passwd_r = str(data['pw-x']) if 'pw-x' in data else ''

    salt = uuid.uuid4().hex
    salt_bytes = salt.encode('utf-8')
    if passwd == passwd_r:
        strength, improvements = passwordmeter.test(passwd)
        if strength < 0.3:
            return render_template(
                'passwordchange.html',
                body=body,
                data=data,
                login=login,
                message='Your password is too weak!'), 200, {}
        for i in range(3):
            pw_bytes = passwd.encode('utf-8')
            passwd = hashlib.sha512(pw_bytes + salt_bytes).hexdigest()
        db, cursor = pysql.database_connect()
        cursor.execute(
            '''UPDATE users SET password= %s, salt= %s WHERE login= %s''',
            (passwd, salt, login))
        db.commit()
        db.close()
        snippets = get_all_snipets()
        return render_template(
            'index.html',
            body=body,
            data=data,
            snippets=snippets,
            message='You successfully changed your password!'), 200, {}
    else:
        return render_template('passwordchange.html',
                               body=body,
                               data=data,
                               login=login,
                               message='Passwords are not match!'), 200, {}
Example #15
0
def forgot_password(headers, body, data):
    login = str(data['name']) if 'name' in data else ''
    a = str(data['answer']) if 'answer' in data else ''

    db, cursor = pysql.database_connect()
    cursor.execute('''SELECT * from users WHERE login = %s ''', login)

    if cursor.fetchone() is not None:
        cursor.execute('''SELECT answer FROM users WHERE login = %s''', login)
        answerdb = str(cursor.fetchone()[0])
        cursor.execute('SELECT salt FROM users WHERE login = %s', login)
        salt = str(cursor.fetchone()[0])
        salt_bytes = salt.encode('utf-8')
        db.close()
        for i in range(3):
            a_bytes = a.encode('utf-8')
            a = hashlib.sha512(a_bytes + salt_bytes).hexdigest()
        if answerdb == a:
            return render_template('passwordchange.html',
                                   body=body,
                                   data=data,
                                   login=login), 200, {}
        else:
            questions_tuple = questions()
            return render_template('recovery.html',
                                   body=body,
                                   data=data,
                                   message='Wrong answer!',
                                   questions=questions_tuple), 200, {}
    else:
        db.close()
        questions_tuple = questions()
        return render_template('recovery.html',
                               body=body,
                               data=data,
                               message='Wrong answer!',
                               questions=questions_tuple), 200, {}
Example #16
0
def changePass(headers, body, data):
  request_method = headers['request-method']

  global areTokensCreated
  if areTokensCreated is False:
      createTokens(dbFile)
      areTokensCreated = True

  global session
  if ('user' in session) and (headers['remote-addr'] == session['ip']):

    if request_method == 'GET':
      print 'get w change pass'
      t = getTokenFromDatabase(dbFile)
      print t
      tokenIsBeingUsed(dbFile, t)
      return render_template('settings.html', body=body, data=data, 
                              username=session['user'], token=t), 200, {}

    elif request_method == 'POST':
      if 'secretIn' in data:
        print 'post w notes ----> otrzymalem token'
        print data['secretIn']
        if tokenIsUsed(dbFile, data['secretIn']) is False:
          msg = 'You are a hacker.'
          return render_template('error.html', msg=msg), 400, {}

      if len(data) < 3: # <--------------------------------------------------------------------- to do ????
        msg = 'All fields must be filled.'
        return render_template('error.html', body=body, data=data, msg=msg), 400, {}

      oldpass = cgi.escape(str(data['oldPass']), quote=True)

      if isPasswordCorrect(session['user'], oldpass, dbFile):
        newpass = cgi.escape(str(data['newPass']), quote=True)
        newpass2 = cgi.escape(str(data['newPass2']), quote=True)

        changePassword(session['user'], newpass, dbFile)

        session = {}
        t = getTokenFromDatabase(dbFile)
        print t
        tokenIsBeingUsed(dbFile, t)
        return render_template('login.html', body=body, data=data, token=t), 200, {}
      else:
        msg = 'Invalid password.'
        return render_template('error.html', body=body, data=data, msg=msg), 400, {}

  else:
    session = {}
    t = getTokenFromDatabase(dbFile)
    print t
    tokenIsBeingUsed(dbFile, t)
    return render_template('login.html', body=body, data=data, token=t), 200, {}
Example #17
0
def signup(headers, body, data):
  request_method = headers['request-method']
  global areTokensCreated
  if areTokensCreated is False:
      createTokens(dbFile)
      areTokensCreated = True

  if request_method == 'GET':
    t = getTokenFromDatabase(dbFile)
    tokenIsBeingUsed(dbFile, t)
    print t
    print '\nget w signup'
    return render_template('signup.html', body=body, data=data, token=t), 200, {}

  elif request_method == 'POST':
    if 'secretIn' in data:
      print 'post w signup --> secret\n'
      print data['secretIn']
      if tokenIsUsed(dbFile, data['secretIn']) is False:
        msg = 'You are a hacker.'
        return render_template('error.html', msg=msg), 400, {}

    if len(data) < 3:
      msg = 'All fields must be filled.'
      return render_template('error.html', body=body, data=data, msg=msg), 400, {}

    l = cgi.escape(str(data['inputLogin']), quote=True)
    p = cgi.escape(str(data['inputPass']), quote=True)
    p2 = cgi.escape(str(data['inputPass2']), quote=True)

    login = ''.join(ch for ch in l if ch.isalnum())
    password = ''.join(ch for ch in p if ch in allowedCharacters)
    password2 = ''.join(ch for ch in p2 if ch in allowedCharacters)

    if isUserInDatabase(login, dbFile) is True:
      msg = 'Invalid login.'
      return render_template('error.html', body=body, data=data, msg=msg), 400, {}

    if password != password2:
      msg = 'Invalid password.'
      return render_template('error.html', body=body, data=data, msg=msg), 400, {}

    else:
      addToDatabase(login, password, dbFile)
      t = getTokenFromDatabase(dbFile)
      print t
      tokenIsBeingUsed(dbFile, t)
      return render_template('login.html', body=body, data=data, token=t), 200, {}
Example #18
0
def view(headers, body, data, snippet_title):
    snippet_title = str(snippet_title)
    dbfile = '/home/wolonkia/vial/genbase.db'
    conn = sqlite3.connect(dbfile)
    cursor = conn.cursor()
    cursor.execute('SELECT login FROM snippets WHERE title = ?;',
                   (snippet_title, ))
    login = cursor.fetchone()

    if login is None:
        return redirect(headers,
                        body=body,
                        data=data,
                        message='Podany plik nie istnieje!'), 200, {}
    #snippet_path = 'od.iem.pw.edu.pl:2552/static/snippets/' + str(snippet_title) + '.snippet'
    snippet_title = str(snippet_title) + '.snippet'
    return render_template('html/view.html',
                           body=body,
                           data=data,
                           headers=headers,
                           snippet_title=snippet_title), 200, {}
Example #19
0
def editpassword(headers, body, data):
    login = str(data['login']) if 'login' in data else ''
    oldpassword = str(data['oldpassword']) if 'oldpassword' in data else ''
    password = str(data['password']) if 'password' in data else ''
    repassword = str(data['repassword']) if 'repassword' in data else ''
    if (login == '') and (password == ''):
        cookie = str(headers['http-cookie']).replace('sessionid=', '')
        if not cookie_check(cookie):
            return render_template(
                'html/signin.html',
                body=body,
                data=data,
                headers=headers,
                message='Musisz sie zalogowac aby zmienic haslo!'), 200, {}
        dbfile = '/home/wolonkia/vial/genbase.db'
        conn = sqlite3.connect(dbfile)
        cursor = conn.cursor()
        cursor.execute('SELECT login FROM users WHERE cookie = ?;', (cookie, ))
        login = str(cursor.fetchone()[0])
        cursor.execute('SELECT password FROM users WHERE login = ?;',
                       (login, ))
        oldpassword = str(cursor.fetchone()[0])

        if oldpassword == password:
            update_password(login, password)
            # expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
            # cookie = 'sessionid=' + cookie + '; expires=' + expires  # + " ; secure"
            return render_template(
                'html/home.html',
                body=body,
                data=data,
                headers=headers,
                message='Haslo zostalo zmienione pomyslnie!'), 200, {}
    if (oldpassword == '') or (repassword == ''):
        return render_template('html/editpassword.html',
                               body=body,
                               data=data,
                               headers=headers), 200, {}
        if password_length(password):
            return render_template(
                'html/editpassword.html',
                body=body,
                data=data,
                headers=headers,
                message='Wymagana dlugosc hasla od 4 do 24 znakow!'), 200, {}
        if not same_passwords(password, repassword):
            return render_template(
                'html/editpassword.html',
                body=body,
                data=data,
                headers=headers,
                message='Podane hasla nie sa identyczne!'), 200, {}
        if entropy(password) < 45.0:
            return render_template(
                'html/editpassword.html',
                body=body,
                data=data,
                headers=headers,
                message='Haslo jest zbyt slabe, jego entropia: ' +
                str(round(entropy(password), 2))), 200, {}
        return render_template('html/home.html',
                               body=body,
                               data=data,
                               headers=headers), 200, {}

        # return render_template('html/editpassword.html', body=body, data=data, headers=headers), 200, {}
    return render_template('html/home.html',
                           body=body,
                           data=data,
                           headers=headers,
                           message='Witaj na stronie!'), 200, {}
Example #20
0
def index(headers, body, data):
    snippets = get_all_snipets()
    return render_template('index.html',
                           headers=headers,
                           body=body,
                           snippets=snippets), 200, {}
Example #21
0
def register(headers, body, data):
    login = str(data['login']) if 'login' in data else ''
    password = str(data['password']) if 'password' in data else ''
    repassword = str(data['repassword']) if 'repassword' in data else ''
    # dbfile = '/home/wolonkia/vial/genbase.db'
    if (login == '') and (password == '') and (repassword == ''):
        return render_template('html/register.html',
                               body=body,
                               data=data,
                               headers=headers), 200, {}
    elif not login_length(login):
        return render_template(
            'html/register.html',
            body=body,
            data=data,
            headers=headers,
            message='Wymagana dlugosc loginu od 4 do 16. znakow!'), 200, {}
    elif not login_chars(login):
        return render_template(
            'html/register.html',
            body=body,
            data=data,
            headers=headers,
            message='Login zawiera niepoprawne znaki!'), 200, {}
    elif not login_exists(login):
        return render_template('html/register.html',
                               body=body,
                               data=data,
                               headers=headers,
                               message='Login juz zajety!'), 200, {}
    elif not password_length(password):
        return render_template(
            'html/register.html',
            body=body,
            data=data,
            headers=headers,
            message='Wymagana dlugosc hasla od 4 do 24 znakow!'), 200, {}
    elif not same_passwords(password, repassword):
        return render_template(
            'html/register.html',
            body=body,
            data=data,
            headers=headers,
            message='Podane hasla nie sa identyczne!'), 200, {}
    elif entropy(password) < 45.0:
        return render_template(
            'html/register.html',
            body=body,
            data=data,
            headers=headers,
            message='Haslo jest zbyt slabe, jego entropia: ' +
            str(round(entropy(password), 2))), 200, {}
    cookie = str(uuid.UUID(bytes=random_bytes(16)).hex)
    expires = (dt.datetime.utcnow() + dt.timedelta(minutes=20))
    add_user(login, password, cookie, expires.strftime("%Y-%m-%d %H:%M:%S"))
    # expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
    # cookie = 'sessionid=' + cookie + '; expires=' + expires  # + " ; secure"
    return render_template(
        'html/redirect.html',
        body=body,
        data=data,
        headers=headers,
        message='Rejestracja zakonczona pomyslnie!'), 200, {}
Example #22
0
      notes = getNotesFromDatabase(dbFile)
      print notes

      t = getTokenFromDatabase(dbFile)
      print t
      tokenIsBeingUsed(dbFile, t)
      return render_template('notes.html', body=body, data=data, 
                              notes=notes, username=session['user'], token=t), 200, {}

  else:
    session = {}
    t = getTokenFromDatabase(dbFile)
    print t
    tokenIsBeingUsed(dbFile, t)
    return render_template('login.html', body=body, data=data, token=t), 200, {}

def changePass(headers, body, data):
  request_method = headers['request-method']

  global areTokensCreated
  if areTokensCreated is False:
      createTokens(dbFile)
      areTokensCreated = True

  global session
  if ('user' in session) and (headers['remote-addr'] == session['ip']):

    if request_method == 'GET':
      print 'get w change pass'
      t = getTokenFromDatabase(dbFile)
Example #23
0
def login(headers, body, data):
  request_method = headers['request-method']
  global areTokensCreated
  if areTokensCreated is False:
    createTokens(dbFile)
    areTokensCreated = True

  if request_method == 'GET':
    print '\nget w login'
    t = getTokenFromDatabase(dbFile)
    print t
    tokenIsBeingUsed(dbFile, t)
    return render_template('login.html', body=body, data=data, token=t), 200, {}
    
  elif request_method == 'POST':
    if 'secretIn' in data:
      print '\npost w login ----> otrzymalem token'
      print data['secretIn']
      if tokenIsUsed(dbFile, data['secretIn']) is False:
        msg = 'You are a hacker.'
        return render_template('error.html', msg=msg), 400, {}

    if len(data) < 2:
      msg = 'All fields must be filled.'
      return render_template('error.html', body=body, data=data, msg=msg), 400, {}

    l = cgi.escape(str(data['inputLogin']), quote=True) 
    p = cgi.escape(str(data['inputPass']), quote=True)

    login = ''.join(ch for ch in l if ch.isalnum())
    password = ''.join(ch for ch in p if ch in allowedCharacters)

    if isUserInDatabase(login, dbFile) is False:
      msg = 'Invalid login.'
      return render_template('error.html', body=body, data=data, msg=msg), 400, {}

    if isPasswordCorrect(login, password, dbFile) is True:
      global session
      session['user'] = login
      session['ip'] = headers['remote-addr']
      fails[headers['remote-addr']] = 0
      print '-----'
      print session
      print fails
      print '-----'

      notes = getNotesFromDatabase(dbFile)
      t = getTokenFromDatabase(dbFile)
      tokenIsBeingUsed(dbFile, t)
      return render_template('notes.html', body=body, data=data, notes=notes, token=t), 200, {}

    elif isPasswordCorrect(login, password, dbFile) is False:

      if headers['remote-addr'] in fails:
        fails[headers['remote-addr']] += 1
        if fails[headers['remote-addr']] > 3:
          time.sleep(2)
          fails[headers['remote-addr']] = 0
          return render_template('login.html', body=body, data=data, token=t), 200, {}
        else:
          msg = 'Invalid password.'
          return render_template('error.html', body=body, data=data, msg=msg), 400, {}
      else:
        fails[headers['remote-addr']] = 1
        msg = 'Invalid password.'
        return render_template('error.html', body=body, data=data, msg=msg), 400, {}
Example #24
0
def change_password_form(headers, body, data):
    return render_template('passwordchange_u.html',
                           headers=headers,
                           body=body,
                           data=data), 200, {}
Example #25
0
def new_snippet(headers, body, data):
    return render_template('new_snippet.html',
                           headers=headers,
                           body=body,
                           data=data), 200, {}
Example #26
0
def signup_db(headers, body, data):
    db, cursor = database_connect()
    login = str(data['name']) if 'name' in data else ''
    password = str(data['pw']) if 'pw' in data else ''
    password_conf = str(data['pwconf']) if 'pwconf' in data else ''
    answer = str(data['answer']) if 'answer' in data else ''

    cursor.execute('SELECT * FROM users WHERE login=%s', (login))
    questions_tuple = questions()
    if (cursor.fetchone()) is not None:
        return render_template(
            'signup.html',
            body=body,
            data=data,
            questions=questions_tuple,
            message='This login is already in use, please choose another one!'
        ), 200, {}
    if not check_login_char(login):
        return render_template(
            'signup.html',
            body=body,
            data=data,
            questions=questions_tuple,
            message='Login can only contains lowarcase letters!'), 200, {}
    if not check_login_length(login):
        return render_template('signup.html',
                               body=body,
                               data=data,
                               questions=questions_tuple,
                               message='Login is too long!'), 200, {}
    if not (password == password_conf):
        return render_template('signup.html',
                               body=body,
                               data=data,
                               questions=questions_tuple,
                               message='Passwords are not match!'), 200, {}
    strength, improvements = passwordmeter.test(password)

    if strength < 0.3:
        return render_template('signup.html',
                               body=body,
                               data=data,
                               questions=questions_tuple,
                               message='Your password is too weak!'), 200, {}
    create_user_folder(login)
    salt = uuid.uuid4().hex
    salt_bytes = salt.encode('utf-8')

    for i in range(3):
        answer_bytes = answer.encode('utf-8')
        pw_bytes = password.encode('utf-8')
        password = hashlib.sha512(pw_bytes + salt_bytes).hexdigest()
        answer = hashlib.sha512(answer_bytes + salt_bytes).hexdigest()
    cursor.execute(
        'INSERT INTO users(login, password, salt, answer) VALUES (%s, %s, %s, %s)',
        (login, password, salt, answer))
    db.commit()
    db.close()
    snippets = get_all_snipets()
    return render_template(
        'index.html',
        body=body,
        data=data,
        snippets=snippets,
        message='You successfully registered new user!'), 200, {}
Example #27
0
def index(environ):
    content = render_template("index.html", {})
    return Response(content, Status.OK)
Example #28
0
def hello(environ):
    content = render_template("hello.html", {})
    return Response(content, Status.OK)
Example #29
0
def signin(headers, body, data):
    login = str(data['login']) if 'login' in data else ''
    password = str(data['password']) if 'password' in data else ''
    cookie = str(headers['http-cookie']).replace('sessionid=', '')

    if (login == '') and (password == ''):
        if cookie_check(cookie):
            return render_template('html/home.html',
                                   body=body,
                                   data=data,
                                   headers=headers,
                                   message='Jestes juz zalogowany!'), 200, {}
        return render_template('html/signin.html',
                               body=body,
                               data=data,
                               headers=headers), 200, {}

    # login = str(data['login']) if 'login' in data else ''
    # password = str(data['password']) if 'password' in data else ''
    # dbfile = '/home/wolonkia/vial/genbase.db'
    # conn = sqlite3.connect(dbfile)
    # cursor = conn.cursor()

    # dbpassword = cursor.execute('SELECT password FROM users WHERE login = ?', (login,))
    # passwd = ''
    # for row in dbpassword:
    #    passwd = str(row[0])

    # salt = passwd[:20]
    # for i in range(3):
    #    password = salt.join(password)
    #    password = str((hashlib.sha1(password)).hexdigest())
    # password = salt + password

    # if (login == '') or (password == ''):
    #    cookie = str(headers['http-cookie']).replace('session_id=', '')
    #    if cookie_check(cookie):
    #        return redirect(headers=headers, body=body, data=data, message='Jestes juz zalogowany!')

    #    return render_template('html/signin.html', body=body, data=data, headers=headers), 200, {}

    elif allow_signin(login, headers):
        if authentication(login, password):
            cookie = str(uuid.UUID(bytes=random_bytes(16)).hex)
            expires = dt.datetime.now() + dt.timedelta(minutes=20)
            cookie_update(cookie, expires, login)
            expires = (
                dt.datetime.utcnow() +
                dt.timedelta(minutes=20)).strftime("%a, %d %b %Y %H:%M:%S GMT")
            cookie = 'sessionid=' + cookie + '; expires=' + expires + ";" + "secure"
            add_log(headers, data, True)
            return render_template('html/home.html',
                                   body=body,
                                   data=data,
                                   headers=headers,
                                   message='Zostales zalogowany!'), 200, {
                                       'Set-Cookie': cookie
                                   }
        add_log(headers, data, False)
        return render_template(
            'html/signin.html',
            body=body,
            data=data,
            headers=headers,
            message='Nieprawidlowe dane logowania!'), 200, {}
    add_log(headers, data, False)
    return render_template(
        'html/signin.html',
        body=body,
        data=data,
        headers=headers,
        message='Zbyt wiele blednych prob zalogowania!'), 200, {}
Example #30
0
def upload(headers, body, data):
    return render_template('upload.html', body=body, data=data), 200, {}
Example #31
0
def item(environ, item_id):
    content = render_template("item.html", {"item_id": item_id})
    return Response(content, Status.OK)