summaryrefslogtreecommitdiffstats
path: root/nfsw/auth.py
blob: f7156d050074fa9a4128ffa42e587d903ec426e2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import functools

import os

from flask import (
    Blueprint, flash, g, redirect, render_template, request,
    session, url_for
)
from werkzeug.security import (
    check_password_hash, generate_password_hash
)

from nfsw.db import get_db


bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('start', methods=('GET', 'POST'))
def auth():
    if request.method == 'POST':
        username = request.form['username']

        password = None
        if 'password' in request.form:
            password = request.form['password']

        if not username:
            return {
                'status': 'error',
                'msg': 'Name is required',
                'fields': ['username']
            }
        elif username and password:
            return login(username, password)

        else:
            return register(username)

    return render_template('auth/index.html')


def login(username, password):
    db = get_db()

    user = db.execute('SELECT * FROM user WHERE username=?', (username,)
    ).fetchone()

    if user is None:
        return {
            'status': 'error',
            'msg': 'User not found',
            'fields': ['username']
        }

    if not check_password_hash(user['password'], password):
        return {
            'status': 'error',
            'msg': 'Password is incorrect',
            'fields': ['password']
        }

    session.clear()
    session['user_id'] = user['id']

    return {
        'status': 'ok',
        'url': url_for('hello')
    }


def register(username):
    db = get_db()

    if db.execute('SELECT id FROM user where username=?', (username,)
    ).fetchone() is not None:
        return {
            'status': 'pass',
            'msg': 'Looks you\'ve registered before!'
            + ' Gimme your password. Pretty please.'
        }

    password = os.urandom(4).hex()

    r = db.execute('INSERT INTO user (username, password) VALUES (?, ?)',
               (username, generate_password_hash(password)))
    db.commit()

    print(r.fetchone)
    print(password)

    session.clear()
    session['newuser'] = True

    return {
        'status': 'ok',
        'url': url_for('hello')
    }