def create_user(): """route /users returns - created user""" if request.get_json(): json = request.get_json() email = json.get('email') password = json.get('password') if email is None: return jsonify(error="email missing"), 400 if password is None: return jsonify(error="password missing"), 400 newUser = User() newUser.email = json['email'] newUser.password = json['password'] if json.get('first_name'): newUser.first_name = json.get('first_name') if json.get('last_name'): newUser.last_name = json.get('last_name') try: db_session.add(newUser) db_session.commit() except BaseException: return jsonify(error="Can't create User: <exception message>"), 400 return jsonify(User.last().to_dict()), 201 else: return jsonify(error="Wrong format"), 400
def post(): req_json = request.get_json() if not req_json: abort(400, 'Wrong format') email = req_json.get("email") password = req_json.get("password") if not email: abort(400, 'email missing') if not password: abort(400, 'password missing') new_obj = User(**req_json) if email_exists(email): abort(400, 'email already exists') db_session.add(new_obj) db_session.commit() del new_obj.__dict__['_password'] if 'first_name' not in new_obj.__dict__: new_obj.__dict__['first_name'] = None if 'last_name' not in new_obj.__dict__: new_obj.__dict__['last_name'] = None return jsonify(new_obj.to_json()), 201
def update_booking_email(request, sse): try: data = json.loads(request.data) if not data: return jsonify(error=True, message='request body is empty, check headers/data') booking_email = str(data['booking_email']).encode() check_email = db_session.query(Accounts).filter_by( booking_email=booking_email).first() if check_email: return jsonify(error=True, message='booking account email is already in use') you = db_session.query(Accounts).filter_by( id=user_session['account_id']).one() you.booking_email = booking_email db_session.add(you) db_session.commit() return jsonify(account=you.serialize, message='Booking Email Updated Successfully!') except Exception as err: print(err) return jsonify(error=True, errorMessage=str(err), message='error processing...')
def update_username(request, sse): try: data = json.loads(request.data) if not data: return jsonify(error=True, message='request body is empty, check headers/data') username = str(data['username']).encode() check_username = db_session.query(Accounts).filter_by( username=username).first() if check_username: return jsonify(error=True, message='username is already in use') you = db_session.query(Accounts).filter_by( id=user_session['account_id']).one() you.username = username db_session.add(you) db_session.commit() return jsonify(account=you.serialize, message='Username Updated Successfully!') except Exception as err: print(err) return jsonify(error=True, errorMessage=str(err), message='error processing...')
def update_product_1_1(bCode): if not request.json or 'storeid' not in request.json: abort(400) m = ProductsMasterlist.query.filter_by(barcode=bCode).first() if m is None: abort(400) if (logger.log_op(request.json)): if 'price' in request.json: if str(m.price) != request.json['price']: price_update = PriceHistory(m.barcode) db_session.add(price_update) db_session.commit() m.price = float(request.json['price']) if 'name' in request.json: m.name = request.json['name'] db_session.add(m) db_session.commit() p = None if 'units' in request.json: engine.execute( updateHelper(bCode, int(request.json['units']), int(request.json['storeid']))) else: engine.execute(updateHelper(bCode, 0, int(request.json['storeid']))) ps = ProductStore.query.filter_by(barcode=bCode).filter_by( storeid=request.json['storeid']).first() return make_response(jsonify({"mobilerp": ps.serialize}), 200) else: return make_response( jsonify({'mobilerp': 'Operacion duplicada, saltando'}), 428)
def send(self): """ 发送邮件 :return: """ ret_oper = False recvers = ";".join(self.mailto_list) try: smtp_server = smtplib.SMTP() smtp_server.connect(self.smtp_host, self.smtp_port) smtp_server.login(self.smtp_user, self.smtp_pwd) msg = MIMEText(self.content, "html", "utf-8") msg['Subject'] = self.subject msg['From'] = MAIL_SENDER msg['To'] = recvers smtp_server.sendmail(self.sender, recvers, msg.as_string()) ret_oper = True except Exception as e: pass finally: try: mail_log = EmailLog() mail_log.recver = ";".join(self.mailto_list) mail_log.subject = self.subject mail_log.content = self.content mail_log.status = EmailLog.STATUS_SEND_SUCCESS if ret_oper else EmailLog.STATUS_SEND_FAILURE db_session.add(mail_log) db_session.commit() except Exception as e: db_session.rollback() smtp_server.quit() return ret_oper
def handleUpdateProjectDataRecord(self): ''' 更新研究项目中的一行数据 :return: ''' _data_dict = self.postParams("*") if "pid" in _data_dict and "row_id" in _data_dict: try: project_id = int(_data_dict.get("pid", 0)) row_id = _data_dict.get("row_id", '') except Exception: project_id = 0 if project_id > 0 and '' != row_id: try: db_session.query(ProjectItem).filter(ProjectItem.proj_id==project_id).filter(ProjectItem.row_id==row_id).delete() for _d in _data_dict: if "pid" != _d and "row_id" != _d: pproperty_item = db_session.query(ProjectProperty).filter(ProjectProperty.label==_d).first() if pproperty_item is not None: p_item = ProjectItem() p_item.label = _d p_item.value = _data_dict[_d] p_item.row_id = row_id p_item.proj_id = project_id p_item.p_id = pproperty_item.id db_session.add(p_item) db_session.commit() self.changeResponse2Success() except Exception as e: db_session.rollback() self.setFailureReason(str(e)) else: self.setFailureReason('缺少关键参数!')
async def add(self, ctx: Context, item: str): author_id = ( db_session.query(User) .filter(User.user_uid == ctx.message.author.id) .first() .id ) if ( not db_session.query(BlockedKarma) .filter(BlockedKarma.topic == item.casefold()) .all() ): blacklist = BlockedKarma(topic=item.casefold(), user_id=author_id) db_session.add(blacklist) try: db_session.commit() await ctx.send(f"Added {item} to the karma blacklist. :pencil:") except (ScalarListException, SQLAlchemyError): db_session.rollback() await ctx.send( f"Something went wrong adding {item} to the karma blacklist. No change has occurred" ) else: await ctx.send( f"{item} is already in the karma blacklist. :page_with_curl:" )
def event_invite(request, event_id): ''' INPUT There needs to be a member object in the request, but this is not the Member being invited. The Member in the request is the User doing the inviting, and needs to be verified to make sure they have Permission to invite people. The Member being invited is contained in request.form['member']. The event, of course, comes from the URL. RESULT The specified Member is added to the Event's 'invited' relationship. It returns True if everything goes the same way. ''' # Grab the standard Group and Member so we know who and where the request is coming from. this_event = Event.query.get(event_id) inviting_member = Member.query.filter_by(user_id=current_user.user_id, group_id=this_event.group_id).first() # Check to make sure the inviting Member is a host. if this_event.is_host(inviting_member): # First, we need to update the Members who are invited. The form field returns a list of codenames. this_event.invited_members = [Member.query.filter_by(group_id=this_event.group_id, codename=membername).first() for membername in request.form['invited_members']] # Next, check if the invited Roles need updating. If the values are updated, make sure to call # the Event's update_invited_members_after_role_change() function. The current behavior is that # changing the Roles will reset the Member invitations to be accurate with the change -- No Exceptions. new_roles = [Role.query.get(role_id) for role_id in request.form['invited_roles']] if new_roles != this_event.invited_roles: this_event.update_invited_by_roles() db_session.add(this_event) db_session.commit() else: raise Exception("That Member can't invite someone, they're not a host!")
def handleAddProjectDataRecord(self): _data_dict = self.postParams("*") if "pid" in _data_dict: try: project_id = int(_data_dict.get('pid')) except Exception as e: project_id = 0 if project_id > 0: row_num = str(uuid1()) try: for _d in _data_dict: if "pid" != _d: pproperty_item = db_session.query(ProjectProperty).\ filter(ProjectProperty.label==_d).\ filter(ProjectProperty.p_id==project_id).first() if pproperty_item is not None: p_item = ProjectItem() p_item.label = _d p_item.value = _data_dict[_d] p_item.row_id = row_num p_item.proj_id = project_id p_item.p_id = pproperty_item.id db_session.add(p_item) db_session.commit() self.changeResponse2Success() except Exception as e: db_session.rollback() self.setFailureReason(str(e))
def edit_event(request, event_id): ''' INPUT Member object in the request to check permissions. Also an Event form in order to update the contents of this one. RESULT If all goes well, event is edited and returns True. Otherwise, an Exception. ''' # First, grab the event and its group. this_event = Event.query.get(event_id) this_group = Group.query.get(this_event.group_id) # Now, use the form parameters to update the Event. this_event.name = request.form['name'] this_event.start_time = request.form['start_time'] this_event.end_time = request.form['end_time'] this_event.location = request.form['location'] this_event.description = request.form['description'] this_event.visible_to_uninvited = request.form['visible_to_uninvited'] this_event.invited_can_invite = request.form['invited_can_invite'] # Nope, need to actively update both the hosting Roles and hosting Members. Then call a function on # the Event class, update_hosts_by_roles(), which updates the Members whenever the Roles change. this_event.hosting_members = [Member.query.get(member_id) for member_id in request['host_members']] new_hosting_roles = [Role.query.get(role_id) for role_id in request.form['host_roles']] if new_hosting_roles != this_event.hosting_roles: this_event.hosting_roles = new_hosting_roles this_event.update_hosts_by_roles() db_session.add(this_event) db_session.commit()
def create_comment(self, content, user, ip, commit=False): ref_name = get_remote_side(self, 'comments') cls = get_remote_side_class(self, 'comments') # verify that the user has not created any comment for this article within the last 30s # TODO: cache this shit last_comment = cls.query.filter_by(ip=hash(ip)).order_by(cls.date_created.desc()).first() if last_comment: time_diff = now_ms() - last_comment.date_created limit = self.comment_limit if time_diff < limit: raise ModelException( type='VALIDATION_FAILED', message=_(u'Please wait %(time)s seconds before sending new comment', time=int(round((limit-time_diff)/1000))) ) comment = cls() setattr(comment, ref_name, self.id) comment.user_id = user.id comment.content = content comment.ip = hash(ip) # also update the comment count cache.update_user_comment_count(self, user.id) db_session.add(comment) if commit: db_session.commit() return comment
def createNewUser(login, password, first_name, last_name, email, role_id, region_id): user = UserDao(login, hashlib.md5(password).hexdigest(), first_name, last_name, email, role_id, region_id) if role_id == RoleDao.get_role_id_by_name("Customer"): user.level_id = UserLevel.get_level_id_by_name("Standard") user.balance = 0 db_session.add(user) db_session.commit()
def mutate(root, info, name, price): product = ProductModel(name=name, price=price) db_session.add(product) db_session.commit() ok = True return CreateProduct(product=product, ok=ok)
def handleAddGeoUnit(self): """ 处理往地理坐标集合上添加坐标点的工作 :return: """ gid, geo_name, longitude, latitude, desc, area, high, map_type = \ self.postParams("gid", "geo_name", "longitude", "latitude", "desc", "area", "high", "map_type") if self.checkParamsAvailable(gid, geo_name, longitude, latitude, desc, area, high, map_type): try: current_user = UserIdentify.getCurrentUser() geo_unit = GeoPointUnit() geo_unit.group_id = gid geo_unit.name = geo_name geo_unit.longitude = longitude geo_unit.latitude = latitude geo_unit.desc = desc geo_unit.map_type = map_type if str(high).isdigit(): geo_unit.high = high else: geo_unit.high = 0 if str(area).isdigit(): geo_unit.area = area else: geo_unit.area = 0 geo_unit.u_id = current_user.get('uid', 0) db_session.add(geo_unit) db_session.commit() self.changeResponse2Success() except Exception as e: db_session.rollback() self.setFailureReason(str(e))
def insert_data(self, data): """ Will handle inserting data into the database """ try: # Check if book is in database, if so update else create try: book = db_session.query(Book).filter(Book.book_id == data.get('book_id')).one() except NoResultFound: book = Book() book.title = data.get('title') book.subtitle = data.get('subtitle') book.author = data.get('author') book.year = data.get('year') book.pages = data.get('pages') book.language = data.get('language') book.publisher = data.get('publisher') book.isbn = data.get('isbn') book.format = data.get('format') book.description = data.get('description') book.file_source = data.get('file_source') book.file_cover_source = data.get('file_cover_source') book.file_location = data.get('file_location') book.file_cover_location = data.get('file_cover_location') book.book_id = data.get('book_id') book.time_collected = data.get('time_collected') db_session.add(book) db_session.commit() # self.track_stat('rows_added_to_db', rows_affected) except Exception: db_session.rollback() logger.exception("Error adding to db {data}".format(data=data))
def sign_in(request): data = json.loads(request.data) print('--- data ---', data) if "email" not in data: return jsonify(error = True, message = "Email Address field is required") if "password" not in data: return jsonify(error = True, message = "Password field is required") email = cgi.escape( data['email'] ) password = cgi.escape( data['password'] ).encode('utf8') if not email or chamber.isValidEmail(email) != True: return jsonify(error = True, message = "Email Address must be in proper format") if not password: return jsonify(error = True, message = "Password must be at least 6 characters") you = db_session.query(Users).filter_by(email = email).first() if not you: return jsonify(error = True, message = "Invalid credentials") checkPassword = bcrypt.hashpw(password, you.password.encode('utf8')) if checkPassword != you.password: return jsonify(error = True, message = "Invalid credentials") you.last_loggedin = func.now() db_session.add(you) db_session.commit() user_session["session_id"] = chamber.uniqueValue() user_session["you_id"] = you.id return jsonify(message = "Signed In!")
def toggle_comment_like(request, sse, comment_id): comment = db_session.query(EventComments).filter_by(id=comment_id).first() if not comment: return jsonify(error=True, message='comment not found') like = db_session.query(CommentLikes) \ .filter_by(comment_id = comment_id) \ .filter_by(owner_id = user_session['account_id']) \ .first() if like: db_session.delete(like) check_notification = db_session.query(Notifications) \ .filter(Notifications.action == ACTION_TYPES['COMMENT_LIKE']) \ .filter(Notifications.target_type == TARGET_TYPES['COMMENT']) \ .filter(Notifications.target_id == like.comment_id) \ .filter(Notifications.from_id == user_session['account_id']) \ .filter(Notifications.account_id == like.comment_rel.owner_id) \ .first() if check_notification: db_session.delete(check_notification) db_session.commit() return jsonify(message='unliked', liked=False) else: like = CommentLikes(comment_id=comment_id, owner_id=user_session['account_id']) db_session.add(like) db_session.commit() if like.comment_rel.owner_id != user_session['account_id']: you = db_session.query(Accounts).filter_by( id=user_session['account_id']).one() message = you.username + ' liked your comment: ' + like.comment_rel.text new_notification = Notifications( action=ACTION_TYPES['COMMENT_LIKE'], target_type=TARGET_TYPES['COMMENT'], target_id=like.comment_id, from_id=user_session['account_id'], account_id=like.comment_rel.owner_id, message=message, link='/event/' + str(like.comment_rel.event_rel.id)) db_session.add(new_notification) db_session.commit() sse.publish( { "message": message, "for_id": like.comment_rel.owner_id }, type='action') return jsonify(message='liked', liked=True)
def update_account(request): data = json.loads(request.data) if request.data else None if not data: return jsonify(error = True, message = "request data not provided") if 'displayname' not in data: return jsonify(error = True, message = "displayname not provided in request data") if 'email' not in data: return jsonify(error = True, message = "email not provided in request data") displayname = cgi.escape( data['displayname'] ) email = cgi.escape( data['email'] ) if not displayname: return jsonify(error = True, message = "displayname must have value") you = db_session.query(Users).filter_by(id = user_session['you_id']).one() you.displayname = displayname if you.email != email: check_email = db_session.query(Users).filter_by(email = email).first() if check_email: return jsonify(error = True, message = "Email is already in use") you.email = email db_session.add(you) db_session.commit() return jsonify(message = "Account Updated!", you = you.serialize)
def create_user(): """ creates an user """ if request.get_json(): json = request.get_json() email = json.get('email') password = json.get('password') if email is None: return jsonify(error="email missing"), 400 if password is None: return jsonify(error="password missing"), 400 try: newUser = User() newUser.email = json['email'] newUser.password = json['password'] except: return jsonify(error="Can't create User: <exception message>"), 400 if json.get('first_name'): newUser.first_name = json['first_name'] if json.get('last_name'): newUser.last_name = json['last_name'] db_session.add(newUser) db_session.commit() created_user = User.last().to_dict() return jsonify(created_user), 201 else: return jsonify(error="Wrong format"), 400
async def add_filament(self, ctx: Context, *args: clean_content): # Check we have the bare minumum number of args if len(args) < 2: await ctx.send( "I need at least a filament name in quotes and the associated print profile." ) return # Make sure there are the right number of args for each input type if len(args) < 3 and not ctx.message.attachments: await ctx.send( "Please provide an image of the filament by an image link or attachment" ) # Do a quick check the folder(s) exist and make them if not self.print_images_dir.mkdir(parents=True, exist_ok=True) filament_name, filament_profile = args[:2] # Verify that the filament type is an expected type if not FilamentType.verify_type(str(filament_profile)): await ctx.send( f'Print profile "{filament_profile}" is not a valid profile. Currently accepted profiles are: `filamentum`, `prusament`.' ) image_file = Path(self.print_images_dir, get_valid_filename(filament_name)) # Get the image and save it to the filesystem if ctx.message.attachments: # Take the first attachment and save it image_attachment = ctx.message.attachments[0] filename = str(image_file) + "." + image_attachment.filename.split( ".")[-1] await image_attachment.save(filename) else: image_url = args[2] filename = str(image_file) + "." + str(image_url).split(".")[-1] # Save the file to disk r = requests.get(image_url, stream=True) if r.status_code == 200: with open(filename, "wb") as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) # Save the model to the database filament = FilamentType( name=str(filament_name), profile=str(filament_profile).casefold(), image_path=str(image_file), ) db_session.add(filament) try: db_session.commit() await ctx.send( f'"{filament_name}" added to the available filament list!') except (ScalarListException, SQLAlchemyError) as e: db_session.rollback() logging.exception(e) await ctx.send( f'Could not add "{filament_name}" due to an internal error.')
def put_data_resume_in_base(data_from_resumes_list, db_session): all_keywords = [] all_urls = [] for item in Keywords.query.all(): all_keywords.append(item.keyword) for item in Resume.query.all(): all_urls.append(item.url) for item in data_from_resumes_list: if item['url'] not in all_urls: all_urls.append(item['url']) resume = Resume(item['title'], item['gender'], item['age'], item['has_degree'], item['city'], str(item['keywords']), item['salary'], item['url']) db_session.add(resume) for keyword in item['keywords']: if keyword not in all_keywords: all_keywords.append(item['keywords']) k = Keywords(keyword.lower()) db_session.add(k) all_keywords.append(keyword.lower()) db_session.commit()
def mutate(root, info, productId, qty): order = OrderModel(qty=qty, productId=productId) db_session.add(order) db_session.commit() ok = True return CreateOrder(order=order, ok=ok)
def folders_add(user): if not user.admin: return error_response("not_admin", "You must be an administrator to " "add a folder") schema = { "type": "object", "properties": { "name": {"type": "string"} }, "required": ["name"] } error = validate_schema(request.json, schema) if error: return error folder = request.json if not folder.get("name").strip(): return error_response("input_validation_fail", "You must supply a name " "for this folder"); if Folder.query.filter(Folder.name==folder.get("name")).count(): return error_response("already_exists", "A folder with that name " "already exists") f = Folder(name=folder.get("name")) db_session.add(f) db_session.commit() return jsonify(success=True, folder_id=f.id)
def create_data(): Base.metadata.create_all(bind=engine) engineering = Department(name='Engineering') db_session.add(engineering) hr = Department(name='Human Resources') db_session.add(hr) peter = Employee(name='Peter', department=engineering, hobbies="['pool', 'sitting down']", results="{'code': 'A+', 'team work': 'C'}") db_session.add(peter) roy = Employee(name='Roy', department=engineering, hobbies="['football', 'mechanics']", results="{'code': 'B', 'team work': 'A'}") db_session.add(roy) tracy = Employee(name='Tracy', department=hr, hobbies="['smoking', 'guns']", results="{'code': 'A+', 'team work': 'B'}") db_session.add(tracy) db_session.commit() return jsonify({'status': 'ok'})
def register(): form: RegisterForm = RegisterForm(request.form) if request.method == "POST" and form.validate_on_submit(): username: str = form.username.data password: str = form.password.data password_confirm: str = form.password_confirm.data school_name: str = form.school.data if password != password_confirm: return render_template("forms/register.html", form=form, error="비밀번호를 다시 입력해주세요.") if User.query.filter(User.username == username).first() is not None: return render_template("forms/register.html", form=form, error="중복되는 아이디입니다.") school: School = School.query.filter( School.name == school_name).first() if school is None: school = School.generate(db_session, school_name) db_session.add( User(username=username, password=authenticator.hash(password), school=school)), db_session.commit() return redirect("/login") return render_template("forms/register.html", form=form)
async def parse(article, session, recursion_depth, from_page_id, limit_rd=1): async with SEMA: global URL task = [asyncio.ensure_future(fetch(URL.format(article), session))] response = await asyncio.gather(*task) data = html.fromstring(response[0]) anchors = data.xpath('//a[@title]') entities = [] for anchor in anchors: href = unquote(anchor.attrib['href']) # проверить, что урл начинается с /wiki, а также этот урл не повторяется в БД if not is_valid_ref( href, db_session ) or 'страница отсутствует' in anchor.attrib['title']: continue page = Page(url=URL.format(href), from_page_id=from_page_id) db_session.add(page) db_session.commit() db_session.refresh(page) entities.append((page.id, href)) # Если дошли до конца рекурсии, останавливаемся if recursion_depth > limit_rd: return # Создаем новый ивент-луп под полученные ссылки, и также рекурсивно запускаем эту функцию под них subtasks = [] for page_id, page_url in entities: subtasks.append( asyncio.ensure_future( parse(page_url, session, recursion_depth + 1, page_id))) await asyncio.gather(*subtasks)
def create_app_user_roles(): roles = [ {"name": "Guest", "description": "User that has not logged in and can only view public sheets."}, {"name": "Undergraduate", "description": "User that can import and view their own sheets with restrictions."}, {"name": "Graduate", "description": "User that can import and view their own sheets with no restrictions."}, {"name": "Teacher", "description": "User that can import and view their own sheets, plus add other users that will be able to view their sheets."}, {"name": "Super User", "description": "User with access to all app features."}, {"name": "Blocked", "description": "User is not allowed to access the App."} ] role_ids = {} for role in roles: role_entry = app_user_role( aur_role_name=role['name'], aur_role_description=role['description'], aur_created=datetime.utcnow(), aur_last_modified=datetime.utcnow() ) db_session.add(role_entry) db_session.flush() role_ids[role['name']] = role_entry.aur_id db_session.commit() return role_ids
async def on_message(message: Message): # If the message is by a bot thats not irc then ignore it if message.author.bot and message.author.id != CONFIG[ "UWCS_DISCORD_BRIDGE_BOT_ID"]: return user = db_session.query(User).filter( User.user_uid == message.author.id).first() if not user: user = User(user_uid=message.author.id, username=str(message.author)) db_session.add(user) else: user.last_seen = message.created_at # Commit the session so the user is available now try: db_session.commit() except (ScalarListException, SQLAlchemyError): db_session.rollback() # Something very wrong, but not way to reliably recover so abort return # Only log messages that were in a public channel if isinstance(message.channel, GuildChannel): # Log the message to the database logged_message = LoggedMessage( message_uid=message.id, message_content=message.clean_content, author=user.id, created_at=message.created_at, channel_name=message.channel.name, ) db_session.add(logged_message) try: db_session.commit() except (ScalarListException, SQLAlchemyError): db_session.rollback() return # Get all specified command prefixes for the bot command_prefixes = bot.command_prefix(bot, message) # Only process karma if the message was not a command (ie did not start with a command prefix) if True not in [ message.content.startswith(prefix) for prefix in command_prefixes ]: reply = process_karma(message, logged_message.id, db_session, CONFIG["KARMA_TIMEOUT"]) if reply: await message.channel.send(reply) # allow irc users to use commands by altering content to remove the nick before sending for command processing # note that clean_content is *not* altered and everything relies on this fact for it to work without having to go back and lookup the message in the db # if message.content.startswith("**<"): <-- FOR TESTING if message.author.id == CONFIG["UWCS_DISCORD_BRIDGE_BOT_ID"]: # Search for first "> " and strip the message from there (Since irc nicks cant have <, > in them idx = message.content.find(">** ") idx += 4 message.content = message.content[idx:] await bot.process_commands(message)
async def on_message(message): # bot should not respond to itself if message.author == client.user: return author = message.author.id user = db_session.query(User).filter(User.uid == author).first() if not user: new_user = User(uid=author, admin=0) db_session.add(new_user) db_session.commit() # if message is a command, we want to do something with it first_word = message.content.split()[0].lower() bot_username = client.user.name.lower() if (first_word in {"iris", f"<@!{client.user.id}>", bot_username} or (first_word.startswith('!') and first_word != "!" and first_word[1] not in '! ')): reply = process_commands(db_session, client, message) if reply != '': if isinstance(reply, str): reply = [reply] for r in reply: await message.channel.send(r) # otherwise, it might contain karma so we should parse it for karma else: changes = karma_parse(message) if len(changes) > 0: reply = karma_change(db_session, client, author, changes) await message.channel.send(reply)
def create_task(request): data = json.loads(request.data) if "taskname" not in data: return jsonify(error=True, message="Task Name field is required") taskname = cgi.escape(data['taskname']) if not taskname: return jsonify(error=True, message="Task Name field cannot be blank") taskduedate = None if "taskduedate" in data: if data['taskduedate']: date_obj = datetime.strptime(data['taskduedate'], "%Y-%m-%d") current = datetime.now() print(date_obj, current) if date_obj < current: return jsonify(error=True, message="Date cannot be today or in the past") else: taskduedate = date_obj parent_task_id = data[ 'parent_task_id'] if 'parent_task_id' in data else None new_task = Tasks(text = taskname, due_date = taskduedate, owner_id = user_session["you_id"]) \ if taskduedate else Tasks(text = taskname, owner_id = user_session["you_id"]) new_task.parent_task_id = parent_task_id db_session.add(new_task) db_session.commit() return jsonify(message="New Task Created!", new_task=new_task.serialize)
def register(self): if request.method == u'POST': client_key = self.generate_client_key() secret = self.generate_client_secret() # TODO: input sanitisation? name = request.form.get(u"name") description = request.form.get(u"description") callback = request.form.get(u"callback") pubkey = request.form.get(u"pubkey") # TODO: redirect? # TODO: pubkey upload # TODO: csrf info = { u"client_key": client_key, u"name": name, u"description": description, u"secret": secret, u"pubkey": pubkey } client = Client(**info) client.callbacks.append(Callback(callback)) client.resource_owner = g.user db_session.add(client) db_session.commit() return render_template(u"client.html", **info) else: clients = g.user.clients return render_template(u"register.html", clients=clients)
async def on_message(message: Message): # If the message is by a bot thats not irc then ignore it if message.author.bot and message.author.id != CONFIG['UWCS_DISCORD_BRIDGE_BOT_ID']: return user = db_session.query(User).filter(User.user_uid == message.author.id).first() if not user: user = User(user_uid=message.author.id, username=str(message.author)) db_session.add(user) else: user.last_seen = message.created_at # Commit the session so the user is available now db_session.commit() # Only log messages that were in a public channel if isinstance(message.channel, GuildChannel): # Log the message to the database logged_message = LoggedMessage(message_uid=message.id, message_content=message.clean_content, author=user.id, created_at=message.created_at, channel_name=message.channel.name) db_session.add(logged_message) db_session.commit() # Get all specified command prefixes for the bot command_prefixes = bot.command_prefix(bot, message) # Only process karma if the message was not a command (ie did not start with a command prefix) if True not in [message.content.startswith(prefix) for prefix in command_prefixes]: reply = process_karma(message, logged_message.id, db_session, CONFIG['KARMA_TIMEOUT']) if reply: await message.channel.send(reply) await bot.process_commands(message)
def add(): if request.form: department = DepartmentModel(name=request.form.get("department")) employee = EmployeeModel(name=request.form.get("name"),department=department) db_session.add(employee) db_session.commit() return render_template("addEmployee.html")
def insert_data(self, data): """ Will handle inserting data into the database """ try: db_session = DBSession() # Check if comic is in database, if so update else create try: comic = db_session.query(Comic).filter( Comic.comic_id == data.get('comic_id')).one() except NoResultFound: comic = Comic() comic.title = data.get('title') comic.alt = data.get('alt') comic.comic_id = data.get('comic_id') comic.source_file_location = data.get('source_file_location') comic.saved_file_location = data.get('saved_file_location') comic.posted_at = data.get('posted_at') comic.raw_json = data.get('raw_json') comic.time_collected = data.get('time_collected') comic.transcript = data.get('transcript') db_session.add(comic) db_session.commit() # self.track_stat('rows_added_to_db', rows_affected) except Exception: db_session.rollback() logger.exception("Error adding to db {data}".format(data=data))
def update_pass(_user, n_pass): user = User.query.filter_by(username=_user).first() hashed_pass = crypt.hash(n_pass) user.password = hashed_pass db_session.add(user) db_session.commit() return jsonify({'user': [user.serialize]})
def insert_data(self, data): """ Will handle inserting data into the database """ try: db_session = DBSession() # Check if whatif is in database, if so update else create try: whatif = db_session.query(Whatif).filter(Whatif.whatif_id == data.get('whatif_id')).one() except NoResultFound: whatif = Whatif() whatif.title = data.get('title') whatif.question = data.get('question') whatif.whatif_id = data.get('whatif_id') whatif.saved_file_location = data.get('saved_file_location') whatif.posted_at = data.get('posted_at') whatif.time_collected = data.get('time_collected') db_session.add(whatif) db_session.commit() except Exception: db_session.rollback() logger.exception("Error adding to db {data}".format(data=data))
def mutate(self, info, dept_no, dept_name): department = Departments(dept_no=dept_no, dept_name=dept_name) db_session.add(department) db_session.commit() return CreateDepartment(dept_no=department.dept_no, dept_name=department.dept_name)
def add_product_1_0(): if not request.json or 'barcode' not in request.json\ or 'units' not in request.json or 'price' not in request.json\ or 'name' not in request.json: abort(400) if not request.json['barcode'] or not request.json['name']\ or not request.json['units'] or not request.json['price']: abort(400) if (logger.log_op(request.json)): m = MasterList.query.filter_by(barcode=request.json['barcode']).first() if m is not None: abort(409, {"message": "Producto existente"}) m = ProductsMasterlist(request.json['barcode'], request.json['name'], request.json['price']) db_session.add(m) db_session.commit() p = Product(request.json['barcode'], request.json['units'], 1) db_session.add(p) db_session.commit() prod = ProductStore.query.filter_by( barcode=request.json['barcode']).filter_by(storeid=1).first() return make_response(jsonify({"mobilerp": prod.serialize}), 200) else: return make_response( jsonify({'mobilerp': 'Operacion duplicada, saltando'}), 428)
def handleRegister(self): """ 处理用户注册 :return: """ name, email, pwd = self.postParams('name', 'email', 'pwd') if self.checkParamsAvailable(email, pwd): exists_query = db_session.query(User).filter(User.email==email).exists() if not db_session.query(exists_query).scalar(): try: set_user = User() set_user.name = name set_user.email = email set_user.salt = User.genSalt() set_user.pwd = User.genPassword(pwd, set_user.salt) set_user.reg_ip = str(request.remote_addr) db_session.add(set_user) db_session.commit() self.changeResponse2Success() mailer = getMailSender() mailer.setMailtoList([email]) mailer.setSubject("感谢注册 [史前-在线定量研究工具]") _mail_content = render_template("noticer/email/_register.html", nickname=name) mailer.setContent(_mail_content) mailer.send() except Exception as e: db_session.rollback() self.setFailureReason(str(e)) else: self.setFailureReason("该邮箱已经被注册,请更换邮箱申请或尝试找回密码!")
def _save_session(self, hostname, user): """make_room(新規ゲーム), join_room(参加表明)のとき、会員のFQDNとIPアドレスを記録する。""" try: ipaddr = unicode(socket.gethostbyname(hostname)) except socket.gaierror: # DNSが引けないとかネット切断とか ipaddr = None db_session.add(Session(int(time.time()), hostname, ipaddr, user.id)) db_session.flush()
def create_book(): book = Book(request.form['title'], request.form['repo_url']) db_session.add(book) db_session.commit() book_for_user = BookForUser(book.id, g.user.id, request.form['branch']) db_session.add(book_for_user) db_session.commit() return redirect(url_for('index'))
def save_access_token(self, client_key, access_token, request_token, realm=None, secret=None): token = AccessToken(access_token, secret=secret, realm=realm) token.client = Client.query.filter_by(client_key=client_key).one() req_token = RequestToken.query.filter_by(token=request_token).one() token.resource_owner = req_token.resource_owner token.realm = req_token.realm db_session.add(token) db_session.commit()
def accounts_batch_update(user): schema = { "type": "array", "items": { "type": "object", "properties": { "account_id": {"type": "integer"}, "encrypted_account_data": { "type": "array", "items": { "type": "object", "properties": { "user_id": {"type": "integer"}, "password": {"type": "string"}, "account_metadata": {"type": "string"}, "encrypted_aes_key": {"type": "string"}, }, "required": ["user_id", "password", "encrypted_aes_key", "account_metadata"] } } }, "required": ["account_id", "encrypted_account_data"] } } error = validate_schema(request.json, schema) for account in request.json: encrypted_account_data = account["encrypted_account_data"] account_id = account["account_id"] a = Account.query.get(account_id) if not a: return error_response("item_not_found", "Account could not be found") if not a.folder.user_can_write(user): return error_response("insufficient_permissions", "You do not have " "write permission for this folder") for item in encrypted_account_data: AccountDataItem.query.filter( AccountDataItem.account_id == a.id).filter( AccountDataItem.user_id == item["user_id"]).delete() db_session.add(AccountDataItem( user_id=item["user_id"], account_id=a.id, password=item["password"], account_metadata=item["account_metadata"], encrypted_aes_key=item["encrypted_aes_key"], )) db_session.commit() return jsonify(success=True)
def add_order(user_id, date, status_id, delivery_id = None, total_price = None, assignee_id = None, preferable_delivery_date = None, delivery_date=None, gift= None, delivery_address = None, comment =None,order_number=None, discount=None): order = Order(user_id, date, status_id, delivery_id, total_price, assignee_id, preferable_delivery_date, delivery_date, gift,delivery_address,comment,order_number,discount) db_session.add(order) db_session.commit() db_session.refresh(order) return order.id
def make_room(users): owner, users = users_random_pop(users) gr = GeneralRecord(int(time.time()), u"#たまひよ", tama._pick_room_number(), owner.name) gr.game_ipaddr = u"127.0.0.1" db_session.add(gr) db_session.flush() pr = PersonalRecord(owner.id, gr.id) db_session.add(pr) db_session.flush() return gr.id, owner, users
def before_request(): if ACCESS_LOG_ON: user_identify = UserIdentify() try: access_log = AccessLog() access_log.ip = str(request.remote_addr) access_log.path = str(request.path) access_log.email = 'anonymous' if user_identify.is_Guest() else user_identify.email db_session.add(access_log) db_session.commit() except Exception as e: db_session.rollback()
def accounts_add(user): schema = { "type": "object", "properties": { "folder_id": {"type": "integer"}, "encrypted_account_data": { "type": "array", "items": { "type": "object", "properties": { "user_id": {"type": "integer"}, "password": {"type": "string"}, "account_metadata": {"type": "string"}, "encrypted_aes_key": {"type": "string"}, }, "required": ["user_id", "password", "encrypted_aes_key", "account_metadata"] } } }, "required": ["folder_id", "encrypted_account_data"] } error = validate_schema(request.json, schema) folder_id = request.json["folder_id"] encrypted_account_data = request.json["encrypted_account_data"] f = Folder.query.get(folder_id) if not f: return error_response("item_not_found", "Folder not found") if not f.user_can_write(user): return error_response("insufficient_permissions", "You do not have " "write permission for this folder") a = Account(folder_id=folder_id) db_session.add(a) db_session.flush() for item in encrypted_account_data: db_session.add(AccountDataItem( user_id=item["user_id"], account_id=a.id, password=item["password"], account_metadata=item["account_metadata"], encrypted_aes_key=item["encrypted_aes_key"], )) db_session.commit() return jsonify(account_id=a.id)
def authorized(access_token): if access_token is None: flash(u'Something went wrong trying to sign into GitHub. :(', 'error') return redirect(url_for('index')) user = User.query.filter_by(github_access_token=access_token).first() if user is None: user = User(access_token) db_session.add(user) user.github_access_token = access_token db_session.commit() session['user_id'] = user.id return redirect(url_for('file_issue'))
def mutate(self, info, holiday_date): query = Publicholiday.get_query(info) date = query.filter( PublicholidayModel.holiday_date == holiday_date).first() if date: raise Exception('The date you selected already exists!') publicHoliday = PublicholidayModel( holiday_date=holiday_date) db_session.add(publicHoliday) db_session.commit() ok = True return AddPublicholiday(publicHoliday=publicHoliday, ok=ok)
def save_timestamp_and_nonce(self, client_key, timestamp, nonce, request_token=None, access_token=None): nonce = Nonce(nonce, timestamp) nonce.client = Client.query.filter_by(client_key=client_key).one() if request_token: nonce.token = RequestToken.query.filter_by(token=request_token).one() if access_token: nonce.token = AccessToken.query.filter_by(token=access_token).one() db_session.add(nonce) db_session.commit()
def post(self): data = json_request(self.request) if data: name = data.get("name", "") img = data.get("image", None) if not name or not img: self.write({"code": 0, "message": "Invalid input data: %s" %data}) dog = Dog(name, resize_image(img)) db_session.add(dog) db_session.commit() self.write({"code": 1, "message": "Dog created. ID: %s" %dog.id}) else: self.write({"code": 0, "message": "Input data must be json"})
def create_task(request, group_id): ''' INPUT Takes in a submission of the create task form, gathering the Title, Description, Deadline, Assignee, and optional Points arguments. Also takes the Group ID and Assigner ID implicitly from the page request. OUTPUT Creates a new Task entry in the database associated with all relevant parties, adding it to the Tasks for each Member assigned. ''' # Grab the information of the creator group & member # Grab the basic stuff associated with the Task. When's it due, what is it, what has to be returned, # any special comments. name = request.form['name'] deadline = request.form['deadline'] if request.form['deadline'] != None else None description = request.form['description'] if request.form['description'] != None else None deliverable = request.form['deliverable'] if request.form['deliverable'] != None else None comments = request.form['comments'] if request.form['comments'] != None else None # Create the task using the information we picked out of the form. new_task = Task(name=name, group_id=group_id, description=description, deadline=deadline, deliverable=deliverable, comments=comments) # Now we need to set all our ForeignKey associations. First, make lists of all the Members and Roles # which are supposed to be true now. new_approving_members = [Member.query.filter_by(group_id=group_id, codename=membername) for membername in request.form['approving_members']] new_delivering_members = [Member.query.filter_by(group_id, codename=membername) for membername in request.form['delivering_members']] new_approving_roles = [Role.query.get(int(role_id)) for role_id in request.form['approving_roles']] new_delivering_roles = [Role.query.get(int(role_id)) for role_id in request.form['delivering_roles']] # Then, set all of these relations to be set as described by the form. new_task.approving_members = new_approving_members new_task.approving_roles = new_approving_roles new_task.delivering_members = new_delivering_members new_task.delivering_roles = new_delivering_roles # Finally, correct the approving_members and delivering_members relations to only contain Members # who have one of the Roles specified in the approving_roles and delivering_roles relations. new_task.update_approvers_by_roles() new_task.update_deliverers_by_roles() # Add and save our work. db_session.add(new_task) db_session.commit() return new_task
def mutate(self, info, id): query = User.get_query(info) user_id = from_global_id(id)[1] user = query.filter(UserModel.id == user_id).first() if user.is_archived is False: raise Exception('This user has an unarchived status!') user.is_archived = False user.archive_reason = None db_session.add(user) db_session.commit() ok = True return UnArchiveUser(User=user, ok=ok)
def authorized(access_token): if access_token is None: flash(u'Something went wrong trying to sign into GitHub. :(', 'error') return redirect(g.referer) user = User.query.filter_by(github_access_token=access_token).first() if user is None: user = User(access_token) db_session.add(user) db_session.commit() session['user_id'] = user.id if session.get('form_data', None) is not None: return redirect(url_for('file_issue')) else: return redirect(g.referer)
def add_user(): print("For better security it is recommended that you add users using a" " client on a different machine from the server, this utility is only" " designed for adding a user to an otherwise empty system.\n") init(config["connection_string"]) u = User() while not u.username: u.username = input("Enter username: "******"Enter full name: ") while not u.email: u.email = input("Enter email: ") password = None while not password: password = getpass("Enter password: "******"y", "n"]: admin_response = input("Is user an admin? [y/n]: ") u.admin = admin_response == "y" print("Generating keys...", end="") sys.stdout.flush() private = RSA.generate(config["key_length"]) public = private.publickey() salt = os.urandom(8) key = PBKDF2(password, salt).read(32) iv = os.urandom(16) cypher = AES.new(key, AES.MODE_CFB, iv) encrypted_private_key = cypher.encrypt(private.exportKey("DER")) u.public_key = base64.b64encode(public.exportKey("DER")).decode("UTF-8") u.encrypted_private_key = base64.b64encode(encrypted_private_key).decode( "UTF-8") u.pbkdf2_salt = base64.b64encode(salt).decode("UTF-8") u.aes_iv = base64.b64encode(iv).decode("UTF-8") auth_key = base64.b64encode(hashlib.pbkdf2_hmac("sha512", password.encode("UTF-8"), u.username.encode("UTF-8"), 100000)) u.auth_hash = bcrypt.hashpw(auth_key, bcrypt.gensalt()).decode("UTF-8") print("Done!") print("Adding user...", end="") sys.stdout.flush() db_session.add(u) db_session.commit() print("Done!")
def log_last_scraped(self): try: try: last_book_id = db_session.query(Book).order_by(Book.book_id.desc()).first() if last_book_id is not None: setting = db_session.query(Setting).filter(Setting.bit == 0).one() setting.book_last_id = last_book_id.book_id setting.book_last_ran = cutil.get_datetime() db_session.add(setting) db_session.commit() except NoResultFound: # If there is no raw data then no books were collected pass except: logger.exception("Problem logging last book scraped")
def add_user(user): if not user.admin: return error_response("not_admin", "You must be an administrator to add" " users") schema = { "type": "object", "properties": { "full_name": {"type": "string"}, "username": {"type": "string"}, "email": {"type": "string"}, "public_key": {"type": "string"}, "admin": {"type": "boolean"}, "encrypted_private_key": {"type": "string"}, "aes_iv": {"type": "string"}, "pbkdf2_salt": {"type": "string"}, "auth_key": {"type": "string"}, }, "required": ["full_name", "username", "email", "public_key", "admin", "encrypted_private_key", "aes_iv", "pbkdf2_salt", "auth_key"] } error = validate_schema(request.json, schema) if error: return error if User.query.filter(User.username==request.json["username"]).count(): return error_response("already_exists", "A user with that username" " already exists!") u = User(); u.full_name = request.json["full_name"] u.username = request.json["username"] u.email = request.json["email"] u.public_key = request.json["public_key"] u.admin = request.json["admin"] u.encrypted_private_key = request.json["encrypted_private_key"] u.aes_iv = request.json["aes_iv"] u.pbkdf2_salt = request.json["pbkdf2_salt"] u.auth_hash = bcrypt.hashpw(request.json["auth_key"].encode("UTF-8"), bcrypt.gensalt()).decode("UTF-8") db_session.add(u) db_session.commit() return jsonify(user_id=u.id)