def try_login(username, password): if username is None or password is None: raise InvalidRequestData('Invalid username or password (empty).') conn = get_connection() cursor = conn.cursor() cursor.execute('SELECT password FROM auth WHERE user = ?', (username, )) result = cursor.fetchone() conn.close() return check_password(password, result[0])
def api_login(error=None): content = request.get_json(silent=True) username = content.get('username') password = content.get('password') if auth.try_login(username, password): new_token = auth.generate_token(username) response = {'status': 'success', 'token': new_token} return jsonify(**response) else: raise InvalidRequestData('Invalid username or password (mismatched).')
def generate_token(username): if username is None: raise InvalidRequestData('Invalid username.') conn = get_connection() cursor = conn.cursor() new_token = str(uuid.with_timestamp(utctime())) cursor.execute('UPDATE auth SET token = ? WHERE user = ?', (new_token, username)) conn.commit() conn.close() return new_token
def validate_token(token): if token is None: raise InvalidRequestData('Invalid token.') conn = get_connection() cursor = conn.cursor() cursor.execute('SELECT user FROM auth WHERE token = ?', (token, )) found_one = cursor.fetchone() conn.commit() conn.close() if found_one is not None: return found_one[0] return None
def add_recurrence(): """API: adds an occurrence to the recurrence schedule.""" content = request.get_json(silent=True) day_id = content['day_id'] hour = content['hour'] minute = content['minute'] if not scheduling.add_occurrence(day_id, hour, minute): raise InvalidRequestData('Cannot add a duplicate occurrence') response = {'status': 'success'} return jsonify(**response)
def intercept_login(): """Intercepts every request and checks if the user is logged in.""" if 'username' not in session and request.endpoint is not None and request.endpoint != 'login' and request.endpoint != 'api_login' and request.endpoint != 'static': if request.headers.get('token') is None: return redirect(url_for('login')) else: api_user = auth.validate_token(request.headers.get('token')) if api_user is None: raise InvalidRequestData('Invalid authentication token.') return # Sessions last for 30 minutes before having to login again session.permanent = True app.permanent_session_lifetime = timedelta(minutes=30) return
def add_onetime_occurrence(error=None): """API: the modal for adding a one-time occurrence to the schedule.""" if request.method == 'POST': content = request.get_json(silent=True) year = content['year'] month = content['month'] day = content['day'] hour = content['hour'] minute = content['minute'] if not scheduling.add_onetime_occurrence(year, month, day, hour, minute): raise InvalidRequestData('Cannot add a duplicate occurrence.') response = {'status': 'success'} return jsonify(**response) else: return render_template('onetimemodal.j2', error_message=error)