def get_badges(): input_data = request.args page = request.args.get('filter[page]', 1, type=int) user = User.getUser(user_id=input_data.get('uid')) badges = db.session.query(Badges).filter_by(creator=user).paginate( page, app.config['POSTS_PER_PAGE'], False) return jsonify(UserBadges(many=True).dump(badges.items).data)
def upload_manual_data(): try: data = request.get_json()['data']['attributes'] except Exception: return ErrorResponse(PayloadNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() if not data.get('manual_data'): return ErrorResponse(ManualDataNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() uid = data.get('uid') manual_data = data.get('manual_data') fetch_user = User.getUser(user_id=uid) if fetch_user is None: return ErrorResponse( UserNotFound(uid).message, 422, { 'Content-Type': 'application/json' }).respond() try: csvName = saveAsCSV(csvData=manual_data) except Exception: return ErrorResponse(OperationNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() file_upload = File(filename=csvName, filetype='csv', uploader=fetch_user) file_upload.save_to_db() return jsonify(ManualFileSchema().dump(file_upload).data)
def upload_default(): try: data = request.get_json()['data']['attributes'] except Exception: return ErrorResponse(PayloadNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() uid = data.get('uid') image_name = data.get('defaultImage') + ".png" image_data = None with open( os.path.join(app.config.get('BASE_DIR'), 'badge_backgrounds', image_name), "rb") as image_file: image_data = base64.b64encode(image_file.read()) try: imageName = saveToImage(imageFile=image_data.decode('utf-8'), extension=".png") except Exception as e: print(e) return ErrorResponse(ImageNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() fetch_user = User.getUser(user_id=uid) file_upload = File(filename=imageName, filetype='image', uploader=fetch_user) file_upload.save_to_db() return jsonify(DefImageSchem().dump(file_upload).data)
def uploadImage(): try: data = request.get_json()['imgFile'] image = data['imgFile'] except Exception: return ErrorResponse(PayloadNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() extension = data['extension'] try: imageName = saveToImage(imageFile=image, extension=extension) except Exception: return ErrorResponse(ImageNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() uid = data['uid'] fetch_user = User.getUser(user_id=uid) if fetch_user is None: return ErrorResponse( UserNotFound(uid).message, 422, { 'Content-Type': 'application/json' }).respond() file_upload = File(filename=imageName, filetype='image', uploader=fetch_user) file_upload.save_to_db() return jsonify(ImageFileSchema().dump(file_upload).data)
def subscribe(): """ Subscribes an user and sends an email. Request Example: POST { email : 'email address' } """ data = request.get_json(force=True) email = data.get('email', None) criterion = [email, len(data) == 1] if not all(criterion): return make_response('Bad Request', 400) found = User.query.filter_by(email=email).first() if found is None: # Create email and send it msg = Message('Welcome to ChartBulls!', recipients=[email]) msg.html = render_template('email_templates/subscribed.html') mail.send(msg) # Add new user user = User(email) db.session.add(user) db.session.commit() return make_response(str(user.id), 201) else: return make_response('Duplicate', 400)
def evesso_authorized(): resp = evesso.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) if isinstance(resp, Exception): return 'Access denied: error=%s' % str(resp) session['evesso_token'] = (resp['access_token'], '') me = evesso.get("verify") user_data = me.data provider_id = "%r%r" % (user_data['CharacterID'], user_data['CharacterOwnerHash']) user = db.session.query(User).filter_by(provider_id=provider_id).filter_by( provider_name='eve').first() if not user: # noinspection PyArgumentList user = User.create(commit=False, provider_id=provider_id, provider_name='eve') user.character_id = user_data["CharacterID"] user.character_name = user_data["CharacterName"] user.save() user.login() return redirect(url_for("index"))
def test_new_user(): username = "******" password = "******" role = "admin" user = User.new_user(username, password, role) assert user.username == "test-new" assert user.check_password(password) assert user.json()["username"] == username assert user.role == role
def get(self, id): try: user = User.get_by_id(id) except AttributeError as e: return error(e, 400) except ValueError as e: return error(e, 404) return user.json()
def del_user_info(): usrid = request.args.get('uid', type=int) user = User().query.filter_by(userID=usrid).first() if user == None: return jsonify({'status': 'fail'}) else: db_app.session.delete(user) db_app.session.commit() return jsonify({'status': 'success'})
def create_game_room(data): """Create a game room""" # noinspection PyUnresolvedReferences sid = request.sid room = data.get("room", None) username = data.get("username", None) password = data.get("password", None) if all([room not in ROOMS, room is not None, username is not None]): admin = User(username=username, sid=sid) ROOMS[room] = Room(room=room, password=password, admin=admin) join_room(room) emit("room_created", { "room": ROOMS[room].json(), "user": admin.json() }, room=room) else: send("room_exists", room=sid)
def delete_user(): schema = DeleteUserSchema() input_data = request.get_json() data, err = schema.load(input_data) if err: return jsonify(err) user = User.getUser(user_id=data['uid']) temp_user = user user.delete_user() return jsonify(DeleteUserSchema().dump(temp_user).data)
def test_user_backref(setup): username = "******" session = Session.new_session(username) setup.session.add(session) setup.session.commit() user = User.get_by_username(username) ids = [session.id for session in user.sessions] assert session.id in ids
def createUser(): email, password, firstName, lastName = request.json.values() user = User(email=email, password=password, first_name=firstName, last_name=lastName) db.session.add(user) db.session.commit() login_user(user) return {"current_user_id": current_user.id}
def delete_user(userid): user = User.getUser(user_id=userid) if not user: return ErrorResponse(UserNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() user.deleted_at = datetime.datetime.utcnow() user.save_to_db() schema = AllUsersSchema() result = schema.dump(user) return jsonify(result.data)
def get_user_info(): args_dic = {} username = request.args.get('username') userid = request.args.get('uid', type=int) if username != None: args_dic['username'] = username if userid != None: args_dic['uid'] = userid official_users = User.get_user(args_dic) return jsonify({'data': official_users})
def get_user(self, user_id: str) -> User: with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() query = self.build_select_all_query( table=UsersTable.TABLE_NAME, identifiers=(UsersTable.Columns.USERNAME, )) output = cursor.execute(query, (user_id, )) result = output.fetchone() if not result: raise UserNotFoundError(user_id) return User(*result)
def is_valid(self): """ Check if Like is valid Returns: True if user and post exist and the user is not the owner of the post """ user = User.get_by_id(self.user.id()) post = Post.get_by_id(self.post.id()) if user and post and not (post.user.id() == user.key.id()): return True return False
def new_session(username, expire=None) -> 'Session': if expire == None: expire = datetime.now() + timedelta(hours=3) if type(expire) in (int, float): expire = datetime.fromtimestamp(expire) user = User.get_by_username(username) return Session( id=uuid4(), user=user, expire=expire, )
def verify_user_cookie(): """ Verifies the current user cookie Return: if current user id exist and hash cookie is verified """ if bool(request.cookies.get('user_id')): user_id = request.cookies.get('user_id').split('|')[0] key = User.get_by_id(long(user_id)) return bool(key) and hash_cookie(user_id) == request.cookies.get('user_id') return False
def create(self): """ REST creates method Returns: A JSON object of the user with out their password Raises: LoginException: if user is not logged in FormException: if user and password and invalid """ if is_login(): raise LoginException('already logged in', status_code=301) user = User.get_by_username(request.form.get('username')) if bool(user) and User.verify_password(user, request.form.get('password')): return login(user.key, user) else: error = { 'password': ['invalid username/password combination'] } raise FormException(message='invalid login', payload=error)
def put_user_info(): offid = request.args.get('uid', type=int) user = User().query.filter_by(userID=offid).first() if user == None: return jsonify({'status': 'fail'}) else: user.uName = request.form.get('username') user.gender = request.form.get('gender') user.address = request.form.get('address') user.tel = request.form.get('tel') userpsd = request.form.get('password') if userpsd != ' ': user.set_password(userpsd) db_app.session.commit() return jsonify({'status': 'success'})
def get_users_list(self, usernames: List[str]) -> List[User]: users = [] with sqlite3.connect(self._db_path) as connection: cursor = connection.cursor() query = self.build_select_all_list_query( table=UsersTable.TABLE_NAME, identifier=UsersTable.Columns.USERNAME, num=len(usernames)) output = cursor.execute(query, tuple(usernames)) for row in output: users.append(User(*row)) return users
def login(): form = LoginForm(request.form) if form.validate_on_submit(): user, authenticated = User.auth(db.session.query, form.userName.data, form.password.data) if authenticated: login_user(user, remember=True) print('Login successfully.') return redirect('/') else: print('Login failed.') return render_template('login.html', form=form, action=url_for('app.login'))
def create_user(username, email, password, firstname, surname): #Checks if uses exist user = User.query.filter_by(username=username).all() if len(user) != 0: print("User exists") return 0 hashed_password = generate_password_hash(password) user = User(username=username, email=email, password=hashed_password, firstname=firstname, surname=surname) db.session.add(user) db.session.commit()
def delete_sales(): args = request.args if 'email' in args.keys(): user = User.getUser(email=args['email']) if not user: return ErrorResponse(UserNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() user.siteAdmin = False permissions = Permissions.get_by_uid(user.id) permissions.isSales = False permissions.save_to_db() user.save_to_db() return jsonify(DeleteSales().dump(user).data)
def update_database(uid, imageName): fetch_user = User.getUser(user_id=uid) if fetch_user is None: return ErrorResponse(UserNotFound(uid).message, 422, {'Content-Type': 'application/json'}).respond() imagePath = os.path.join(app.config.get('BASE_DIR'), 'static', 'uploads', 'image') + '/' + imageName imageLink = fileUploader(imagePath, 'profile/images/' + imageName) fetch_user.photoURL = imageLink fetch_user.save_to_db() try: os.unlink(imagePath) except Exception: print('Unable to delete the temporary file') return fetch_user, imageLink
def create_quiz_services(request_data): params = convert(request_data) quiz_obj = quiz.Quiz(params) if 'questions' in params: questions = [quiz.Question(param) for param in params] else: questions = quiz.Question.query.filter_by(quiz_id=quiz_obj.id).all() if questions: quiz_obj.questions = questions if 'admin' in params: admin = User(params['admin']) else: admin = User.query.filter_by(id=quiz_obj.created_by).first() if admin: quiz_obj.admin = admin response = quiz_obj.create_or_update() if response: return response.__dict__
def create(self): """ REST create method Returns: A JSON object with new User information Raises: LoginException: if user is already logged in FormException: if user form data is invalid """ if is_login(): raise LoginException('already logged in', status_code=301) user = User(username=request.form.get('username'), password=request.form.get('password'), email=request.form.get('email')) if user.is_valid(): key = user.put() return login(key) else: raise FormException(message='invalid user data', payload=user.errors())
def post(self): args = self.parser.parse_args() username = args["username"] password = args["password"] role = args["role"] if role == None: role = "reader" if username == None or password == None: return error("Request must contain username and password.", 400) if not User.username_available(username): return error(f"Username '{username}' has been taken.", 400) try: user = User.new_user(username, password, role) db.session.add(user) db.session.commit() return user.json(), 201 except Exception as e: return error(str(e), 400)
def register_sales(): schema = SalesSchema() input_data = request.get_json()['data']['attributes'] if 'email' in input_data.keys(): user = User.getUser(email=input_data['email']) if 'salesStat' in input_data.keys(): permission = Permissions.get_by_uid(user.id) permission.isSales = input_data['salesStat'] permission.save_to_db() user.save_to_db() return jsonify(schema.dump(user).data) else: return ErrorResponse(JsonNotFound().message, 422, { 'Content-Type': 'application/json' }).respond()
def admin_add_usage(): try: data = request.get_json()['data'] print(data) except Exception: return ErrorResponse(JsonNotFound().message, 422, { 'Content-Type': 'application/json' }).respond() uid = data['uid'] allowed_usage = data['allowed_usage'] user = User.getUser(user_id=uid) user.allowed_usage = user.allowed_usage + allowed_usage db.session.commit() return jsonify(UserAllowedUsage().dump(user).data)
def debug_login(): if not current_app.debug: abort(404) form = DebugLoginForm(request.form) if form.validate(): provider_id = str(form.character_id) user = db.session.query(User).filter_by(provider_id=provider_id).filter_by( provider_name='debug').first() if not user: # noinspection PyArgumentList user = User.create(commit=False, provider_id=provider_id, provider_name='debug', admin=True) user.character_id = form.character_id user.character_name = form.character_name user.save() user.login() return redirect(url_for("index")) return render_template("login.html", form=form)
def authorized(): resp = twobad.authorized_response() if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error'], request.args['error_description'] ) if isinstance(resp, OAuthException): return 'Access denied: %r' % resp session['twobad_token'] = (resp['access_token'], '') me = twobad.get('me') if me.data["success"]: user_data = me.data["user"] user = db.session.query(User).filter_by(provider_id=user_data['user_id']).filter_by( provider_name='2bad').first() if not user: # noinspection PyArgumentList user = User.create(commit=False, provider_id=user_data['user_id'], provider_name='2bad') user.character_id = user_data["character_id"] user.character_name = user_data["username"] user.save() user.login() return redirect(url_for("index")) return jsonify(me.data)
def load_user(userid): return User.get_user_for_session(userid)