def authenticate(username, password): user = db.get_user_by_username(username) if (user and password_utils.verify_password(password.encode("utf-8"), user[2].encode('utf-8'))): return True, user[0] else: return False, None
def _view_game(game_id, init_path, game_edit_form=None, comment_form=None): """ Views existing game on given (comment) path. When there are errors with comment for instance of this one can be passed in and errors displayed. """ game = db.get_game(game_id) if not game: abort(404) # fetch games owner db.annotate(game) comments=list(db.get_comments_for_game(game_id)) for comment in comments: db.annotate(comment) # forms if not comment_form: comment_form = forms.CommentForm() user = db.get_user_by_username(session.get("username", None)) typeahead_players = [] if user and game.is_owner(user) and not game_edit_form: game_edit_form = forms.GameEditForm.form_factory(game.type)() # hint for inputting players names typeahead_players = dict([(player.name, player.rank) for player in db.get_players()]) print game.nodes return render_template("view_game.html", game=game, init_path=init_path, comments=comments, comment_paths=[(str(c["_id"]), c["path"]) for c in comments], comment_form=comment_form, typeahead_players=typeahead_players, game_edit_form=game_edit_form)
def upload_game(): """Loads game from url/file, stores in the DB and displays. Requires login.""" form = forms.SgfUploadForm() # this must be done explicitly # because for some reason request.files is not picked up by the wtf form if request.method == "POST" and "file" in request.files: form.file.data = request.files["file"] if request.method == "POST" and form.validate_on_submit(): if form.sgf: username = session["username"] user = db.get_user_by_username(username) if not user: abort(500) game, err = db.create_game(user._id, form.sgf, request.game_type) if not game: # attach the error to the form if form.url.data: form.url.errors = (err,) elif form.file.data: form.file.errors = (err,) return render_template("upload_game.html", menu_toggle_upload=True, form=form) return redirect(url_for("view_game", game_id=game._id)) else: abort(500) return render_template("upload_game.html", menu_toggle_upload=True, form=form)
def validate(self): if not Form.validate(self): return False user = db.get_user_by_username(self.username.data) if user is not None: self.username.errors.append("Username exists") return False return True
def crassword_get_config(): username = request.args.get('username') user = db.get_user_by_username(username) config = crassword_flask.get_config('login') if user: config['salt'] = user['salt_hex'] else: config['salt'] = crassword_flask.generate_decoy_salt(user['username']) return json.dumps(config)
def validate(self): if not Form.validate(self): return False self.user = db.get_user_by_username(self.username.data) if self.user is None: self.username.errors = ("Unknown username",) return False if not check_password_hash(self.user.passwd, self.password.data): self.password.errors = ("Invalid password",) return False return True
def post_update(game_id): """Posts game tree updates for given game. Requires login. Called via ajax.""" game = db.get_game(game_id) if not game: abort(404) username = session["username"] user = db.get_user_by_username(username) try: update_data = json.loads(request.form.get("update_data")) except: return jsonify(err="Invalid encoding.") if not db.sync_game_update(game, update_data, user): return jsonify(err="You don't have permission to perform this action.") return jsonify(err=None)
def edit_game(game_id): """Edit game meta information.""" game = db.get_game(game_id) if not game: abort(404) user = db.get_user_by_username(session["username"]) if not user: abort(500) # protection if not game.is_owner(user): app.logger.warning("Unauthorized game edit: user(%s) game(%s)" % (user.username, game._id)) abort(500) form = forms.GameEditForm.form_factory(game.type)(request.form) if form.validate_on_submit(): form.update_game(game) return redirect(url_for("view_game", game_id=game._id)) return _view_game(game._id, [], game_edit_form=form)
def auth_login(): data = request.get_json() conn = db.connect_database() user = db.get_user_by_username(conn, data['username']) if data['password'] == user['password']: access_token = generate_token(user['id']) if access_token: response = { 'message': 'You logged in successfully.', 'access_token': access_token.decode() } return jsonify(response), 200 else: response = { 'message': 'Invalid username or password, Please try again.' } return jsonify(response), 401
def delete_comment(): """Deletes comment identified by id in post data. Requires login. Called via ajax.""" username = session["username"] user = db.get_user_by_username(username) if not user: app.logger.warning("comment without user") abort(500) comment_id = request.form.get("comment_id", None) comment = db.get_comment(comment_id) if not comment: app.logger.warning("no comment for given id %s" % comment_id) abort(500) can_delete_comment = comment.is_owner(user) if not can_delete_comment: app.logger.warning("User %s tried to delete comment %s without permissions." % (user["_id"], comment["_id"])) abort(500) db.delete_comment(comment_id) return jsonify(err=None, comment_id = comment_id)
def register(): """creates a new user who will be allowed to access the database. Args: username (str): name of the user to be saved in the database. password (str): password of the user to be saved in the database. Returns: if all goes well: dict: {} Bool: True if something goes wrong: dict: Error message. Bool: False """ json = request.get_json() username = json.get('username') password = json.get('password') if not username: return jsonify({"msg": "Missing username parameter"}), 400 if not password: return jsonify({"msg": "Missing password parameter"}), 400 user, success = db.get_user_by_username(username) if not success: return { "msg": 'The server found an error that it could not handle' }, 500 if user: return {"msg": "username already exists"}, 409 hash_password = sha1(password.encode('utf-8')).hexdigest() if not db.create_new_user(username, hash_password): return { "msg": 'The server found an error that it could not handle' }, 500 return {}, 204
def login_user(): error = None print "form:", request.form username = request.form['username'] password = request.form['password'] if request.method != 'POST': error = "Invalid request method" if not username: error = "Username is required" elif not password: error = "Password is required" user = db.get_user_by_username(username) if user is None: error = "Incorrect username" elif password != user['password']: error = "Incorrect password" if error is not None: resp = { "status": "failure", "message": "Unable to log user in", "reason": error } return jsonify(resp) session.clear() session['user_id'] = user['user_id'] session['username'] = username resp = { "status": "success", "message": "User logged in", "user_id": user['user_id'] } return jsonify(resp)
def register_user(): error = None username = request.form['username'] password = request.form['password'] first_name = request.form.get('first_name') last_name = request.form.get('last_name') email = request.form.get('email') isEmployer = request.form.get('isEmployer') if request.method != 'POST': error = "Invalid request method" if not username: error = "Username is required" elif not password: error = "Password is required" elif db.user_exists(username): error = "Username {} is already registered".format(username) if error is None: db.create_user(username, password, first_name, last_name, email, isEmployer) resp = { "status": "success", "message": "Successfully registered user", "username": username } user = db.get_user_by_username(username) session['user_id'] = user['user_id'] session['username'] = username return jsonify(resp) resp = { "status": "failure", "messsage": "unable to regsiter user", "reason": error } return jsonify(resp)
def login(): """creates user login Routes: /login Args: username (str): name of the user. password (str): password value. Returns: if all goes well: dict: token if something goes wrong: dict: Error message """ json = request.get_json() username = json.get('username') password = json.get('password') if not username: return jsonify({"msg": "Missing username parameter"}), 400 if not password: return jsonify({"msg": "Missing password parameter"}), 400 current_user, success = db.get_user_by_username(username) if not success: return { "msg": 'The server found an error that it could not handle' }, 500 if not current_user: return {"msg": "user does not exist"}, 404 if not (sha1(password.encode('utf-8')).hexdigest() == current_user['password']): return {'msg': 'wrong credentials'}, 401 access_token = create_access_token(identity=username) return jsonify(access_token=access_token), 200
def post_comment(game_id): """Posts comment for given game and path. Requires login. Called via ajax.""" game = db.get_game(game_id) if not game: abort(404) form = forms.CommentForm(request.form) if form.validate_on_submit(): username = session["username"] user = db.get_user_by_username(username) if not user: app.logger.warning("comment without user") abort(500) comment = db.create_comment(user._id, game_id, form.short_path, form.comment.data) db.annotate(comment) can_delete_comment = comment.is_owner(user) comment_template = app.jinja_env.from_string( """ {%% from 'macros.html' import render_comment_in_game %%} {{ render_comment_in_game(comment, %s) }} """ % can_delete_comment) return jsonify(err=None, comment_id = str(comment["_id"]), comment_path=comment["path"], comment_html = comment_template.render(comment=comment)) return jsonify(err="Invalid comment.")
def view_user(username): """ Views existing user based on his username. Pagination is provided in query string via keys games_page, comments_page. """ user = db.get_user_by_username(username) if not user: abort(404) queries = dict(urlparse.parse_qsl(request.query_string)) games_page = int(queries.get("games_page", 1)) comments_page = int(queries.get("comments_page", 1)) # paginate games games_per_page = app.config["games_per_page_in_user_view"] games_from, games_to = (games_page - 1) * games_per_page, games_page * games_per_page games_cursor = db.get_games_for_user(user._id) num_all_games = games_cursor.count() games = list(games_cursor)[games_from:games_to] games_pagination = Pagination(games_per_page, games_page, num_all_games, lambda page: url_for("view_user", username=username, games_page=page, comments_page=comments_page)) for game in games: db.annotate(game) # paginate comments comments_per_page = app.config["comments_per_page_in_user_view"] comments_from, comments_to = (comments_page - 1) * comments_per_page, comments_page * comments_per_page comments_cursor = db.get_comments_for_user(user._id) num_all_comments = comments_cursor.count() comments = list(comments_cursor)[comments_from:comments_to] comments_pagination = Pagination(comments_per_page, comments_page, num_all_comments, lambda page: url_for("view_user", username=username, games_page=games_page, comments_page=page)) for comment in comments: db.annotate(comment) return render_template("view_user.html", user=user, games=games, comments=comments, games_pagination=games_pagination, comments_pagination=comments_pagination)
def authenticate(username, password): user = db.get_user_by_username(username) if (user and password_utils.verify_password(password, user[2])): return True, user[0] else: return False, None
#!/usr/bin/python3.7 import base import os import cgi import session import authentication import db from http import cookies http_cookies_str = os.environ.get('HTTP_COOKIE', '') get_all_cookies_object = cookies.SimpleCookie(http_cookies_str) username = get_all_cookies_object.get("username") params = cgi.FieldStorage() user = db.get_user_by_username(username) if not username: print('Location: change_pass_first.py') question_id = user[3] if user else None question = db.get_question_by_id(question_id) if question_id else None if os.environ["REQUEST_METHOD"].upper() == "GET": new_password = params.getvalue("password") answer = params.getvalue("answer") success = authentication.change_password(username, new_password, question_id, answer) if success: print('Location: login.py')
def create_game(): """Creates new game and lets the user edit it.""" user = db.get_user_by_username(session["username"]) game = db.create_new_game(user._id, request.game_type) return redirect(url_for("view_game", game_id = game._id))
def get_user_by_username(username): try: return db.get_user_by_username(username) except: return None
def get_user_by_username(username: str): user = db.get_user_by_username(username) if user: return UserInDB(**user)
def fetch_user_by_username(username): user = get_user_by_username(username) return User(user[1], None, user[0])