def api_add_like(current_user): try: id_sight = request.args['id_sight'] new_like = Likes(id_user=current_user.id_user, id_sight=id_sight, value=1) session.add(new_like) session.commit() return jsonify({ 'message': None, 'data': None, 'status': 'success' }), 200 except exc.IntegrityError: session.rollback() return jsonify({ 'message': 'Duplicate', 'data': None, 'status': 'error' }), 400 except Exception: session.rollback() return jsonify({ 'message': 'Unexpected error', 'data': None, 'status': 'error' }), 400
def user_login(): form = LoginForm() if request.method == 'POST': if form.validate() == False: flash('All fields are required') return render_template('login/login.html', form=form) else: # get a reference to the user model user = session.query(User).filter( User.email == form.email.data).one_or_none() if (not user or not bcrypt.checkpw(form.password.data.encode(), user.password_hash)): # provide user feedback flash('The email or password entered was not correct') return redirect(url_for('login.user_login')) else: user.authenticated = True try: # update datebase session.add(user) session.commit() # store user in session login_user(user, remember=True) # provide the user feedback flash('Welcome back %s' % user.name) return redirect(url_for('category.allCategories')) except: session.rollback() # provide the user feedback flash('Could not login') return redirect(url_for('login.user_login')) else: # Todo: implement session token for security state = get_rand_string() login_session['state'] = state # populate an oauth credentials dictionary to be used for client side # oauth github_creds = get_credentials_for('oauth', 'github') oauth = {'github_client_id': github_creds['client_id']} return render_template('login/login.html', form=form, state=state, oauth=oauth)
def newCategory(): params = request.form # ensure name key and name value if 'name' in params.keys(): name = params['name'] category = Category(name=name, type=name, depth=0) else: return json.dumps({'error': 'missing name parameter'}), 422 try: # attach category to user if current_user.is_authenticated: category.user_id = current_user.id # add new category to the database session.add(category) session.commit() return json.dumps(category.serialize) except: session.rollback() return json.dumps({'error': 'failed to create a category'}), 400
def superuser(): """Create superuser""" admin = User() admin.email = "root" admin.password = "******" admin.name = "root" session.add(admin) session.commit()
def api_create_country(): print(request.args) if 'name' in request.args: new_count = Country(name=request.args['name']) try: session.add(new_count) session.commit() except exc.IntegrityError: session.rollback() return jsonify({'message': 'Duplicate value', 'data': None, 'status': 'error'}), 400 return jsonify({'message': None, 'data': None, 'status': 'success'}), 200
def editItem(category_id, item_id): # grab a reference to the category and item models category = session.query(Category).filter(Category.id == category_id).one() item = session.query(Item).filter(Item.id == item_id).one() # restrict access if item doesn't belong to user if (not current_user.is_authenticated and item.user_id or (current_user.is_authenticated and not current_user.id == item.user_id)): # send feedback to the user flash('You do not have permission to edit that item') return redirect(url_for( 'category.allCategories', current_category_id=category_id)) if request.method == 'GET': # serve up edit form return render_template('item/edit.html', item=item, category=category) if request.method == 'POST': try: params = request.form # update item model from form params item.name = params['name'] if len(params['name']) > 0 else item.name item.details = params['details'] if len(params['details']) > 0 else item.details image = request.files['image'] if 'image' in request.files.keys() else None # save image asset and set image_name property for the item if image and image.filename != item.image_name and allowed_file(image.filename, app.config): image_name = (get_rand_string() + '.').join([str(x) for x in secure_filename(image.filename).split('.')]) path = os.path.join(app.config['IMAGE_FOLDER'], image_name) image.save(path) item.image_name = image_name # update item in the database session.add(item) session.commit() # send feedback to the user flash("%s updated!" % item.name) return redirect(url_for( "category.allCategories", current_category_id=category_id)) except: session.rollback() raise
def insert(self, data): # exist, vehicle = self.check_exist(data=data) # if exist: # return self.update(data=data, object_id=vehicle.port_id) # else: try: vehicle = self._parse_vehicle(data=data, vehicle=None) session.add(vehicle) session.commit() return vehicle except Exception as e: print(e.__str__()) session.rollback() return None
def api_create_user(): data = request.args.to_dict(flat=True) hashed_password = generate_password_hash(data['password'], method='sha256') try: new_user = Users(public_id=str(uuid.uuid4()), name=data['name'], password=hashed_password,) new_user.id_role = 3 session.add(new_user) session.commit() return jsonify({'message': None, 'data': None, 'status': 'success'}), 201 except Exception as e: session.rollback() return jsonify({'message': 'Unexpected error', 'data': None, 'status': 'error'}), 400
def insert(self, data): # exist, port = self.check_exist(data=data) # if exist: # return port #self.update(data=data, object_id=port.port_id) # else: try: port = self._parse_port(data=data, port=None) session.add(port) session.commit() return port except Exception as e: print(e.__str__()) session.rollback() return None
def insert(self, data): # exist, region = self.check_exist(data=data) # if exist: # return region #self.update(data=data, object_id=region.port_id) # else: try: region = self._parse_region(data=data, region=None) session.add(region) session.commit() return region except Exception as e: print(e.__str__()) session.rollback() return None
def api_create_sights(): try: args = request.args.to_dict(flat=True) try: args['urls'] = args['urls'].split(',') except KeyError as e: print(e) new_sight = Sights(**args) session.add(new_sight) session.commit() except exc.IntegrityError as e: session.rollback() return jsonify({'message': 'Duplicate value' + e.args[0], 'data': None, 'status': 'error'}), 400 return jsonify({'message': None, 'data': None, 'status': 'success'}), 200
def api_create_town(): if 'name' in request.args: try: new_town = Town(name=request.args['name'], id_country=request.args['id_country']) session.add(new_town) session.commit() except exc.IntegrityError: session.rollback() return jsonify({ 'message': 'Duplicate value', 'data': None, 'status': 'error' }), 400 return jsonify({'message': None, 'data': None, 'status': 'success'}), 201
def createItem(category_id): # grab a reference to the category model category = session.query(Category).filter(Category.id == category_id).one() # render the item creation form if request.method == 'GET': return render_template('item/index.html', category=category) if request.method == 'POST': try: params = request.form # create an item object from form params item = Item( type=category.name, name=params['name'], details=params['details']) # attach a user to an item if current_user.is_authenticated: item.user_id = current_user.id if 'image' in request.files.keys(): image = request.files['image'] # save image asset and set image_name property for the item if image and allowed_file(image.filename, app.config): image_name = (get_rand_string() + '.').join([str(x) for x in secure_filename(image.filename).split('.')]) path = os.path.join(app.config['IMAGE_FOLDER'], image_name) image.save(path) item.image_name = image_name # connect item to its category item.item_children.append(category) # add item to database session.add(item) session.commit() # send feedback to the user flash("%s created!" % item.name) return redirect(url_for( "category.allCategories", current_category_id=category_id)) except: session.rollback() raise
def logout(): user = current_user user.authenticated = False try: session.add(user) session.commit() logout_user() # provide the user feedback flash('Successfuly logged out!') return redirect(url_for('category.allCategories')) except: session.rollback() raise
def user_signup(): form = LoginForm() if request.method == 'GET': state = get_rand_string() login_session['state'] = state # populate an oauth credentials dictionary to be used for client side # oauth github_creds = get_credentials_for('oauth', 'github') oauth = {'github_client_id': github_creds['client_id']} return render_template('login/signup.html', oauth=oauth, form=form, state=state) elif request.method == 'POST': if form.validate() == False: flash('All fields are required') return render_template('login/signup.html', form=form) else: # generate a password hash from the users' password pw_hash = bcrypt.hashpw(form.password.data.encode(), bcrypt.gensalt()) email = form.email.data # check to make sure user doesn't already exist try: prev_user = session.query(User).filter( User.email == email).one_or_none() if not prev_user: # create a new user user = User(email=email, password_hash=pw_hash, authenticated=True) # add user to the database session.add(user) session.commit() # store user in session login_user(user, remember=True) # provide the user feedback flash('Welcome %s' % user.name) return redirect(url_for('category.allCategories')) else: # notify that a user has already been created with that # email flash('A user already exists with that email') return redirect(url_for('login.user_signup')) except: session.rollback() raise
def githubConnect(): state = request.args.get('state') # ensure state is the same if not state == login_session['state']: # provide the user feedback flash('failed to authenticate using github') return redirect(url_for('login.user_login')) # get githubs temporary code ... session_code = request.args.get('code') # ... and POST it back to github try: github_creds = get_credentials_for('oauth', 'github') payload = { 'client_id': github_creds['client_id'], 'client_secret': github_creds['client_secret'], 'code': session_code, 'accept': 'json' } result = urlparse.parse_qs( requests.get('https://github.com/login/oauth/access_token', params=payload).text) if 'error' in result: # let developer know why oath failed print('%s - while trying to authenticate: ' % result['error']) # provide the user feedback flash('failed to authenticate using github') return redirect(url_for('login.user_login')) # get scope of user allowed data scopes = result['scope'] has_user_email_scope = True if 'user:email' in scopes else False if not has_user_email_scope: # provide the user feedback flash('You must provide email access to create an account') return redirect(url_for('login.user_login')) # get access token from github oauth response access_token = result['access_token'] payload = {'access_token': access_token} # fetch user private email user_email = (requests.get('https://api.github.com/user/emails', params=payload).json())[0]['email'] # get reference to user model user = (session.query(User).filter( User.email == user_email).one_or_none()) if not user: # fetch user information user_info = requests.get('https://api.github.com/user', params=payload).json() # create a user # get name firstname = user_info['name'].split(' ')[0] picture_url = user_info['avatar_url'] email = user_email user = User(firstname=firstname, picture_url=picture_url, email=email) user.authenticated = True # update datebase session.add(user) session.commit() # store user in session login_user(user, remember=True) # provide the user feedback flash('Welcome back %s' % user.name) return redirect(url_for('category.allCategories')) except: raise # provide the user feedback flash('failed to authenticate using github') return redirect(url_for('login.user_login'))