Exemplo n.º 1
0
 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()
Exemplo n.º 2
0
 def breakup(self, json):
   """解散、強制解散"""
   args = loads(json)
   print args
   user = self._whoami(args["caller"])
   if user is None:
     return dumps((False,))
   pr = self._is_room_owner(args["channel"], args["caller"])
   if (not pr) and (not args["force"]):
     return dumps((False,))
   if (not pr) and args["force"]:
     q = db_session.query(GeneralRecord
       ).filter(GeneralRecord.active==True
       ).filter(GeneralRecord.room_number==args["room_number"]
       ).filter(GeneralRecord.channel==args["channel"])
     try:
       gr = q.one()
     except NoResultFound:
       return dumps((False,))
   else:
     gr = pr.general_record
   members = self._execute_breakup(gr)
   returns = self._construct_room_info(gr, user)
   returns.update({"members": [self._construct_member_info(pr) for pr in members]})
   db_session.commit()
   return dumps((True, returns))
def users_self_update_password(user):
    schema = {
        "type": "object",
        "properties": {
            "encrypted_private_key": {"type": "string"},
            "aes_iv": {"type": "string"},
            "pbkdf2_salt": {"type": "string"},
            "auth_key": {"type": "string"},
        },
        "required": ["encrypted_private_key", "aes_iv", "pbkdf2_salt",
            "auth_key"]
    }

    error = validate_schema(request.json, schema)
    if error:
        return error

    u = User.query.get(user.id)

    user.encrypted_private_key = request.json["encrypted_private_key"]
    user.aes_iv = request.json["aes_iv"]
    user.pbkdf2_salt = request.json["pbkdf2_salt"]
    user.auth_hash = bcrypt.hashpw(request.json["auth_key"].encode("UTF-8"),
        bcrypt.gensalt()).decode("UTF-8")

    db_session.commit()

    return jsonify(success=True)
Exemplo n.º 4
0
def vote():
    topic = g.topic
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = topic.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = topic.update_points(up=up, points=2)
                topic.user.update_points(up=up, points=6)
            else:
                points = topic.points
        else:
            # this is a new vote
            points = topic.update_points(up)
            user_points = 1
            if up:
                user_points = 5
            topic.user.update_points(up=up, points=user_points)
        
        db_session.commit()
        data = {
            "points": points
        }

        cache.update_topic(topic.id, topic)
        cache.update_sorted_topics(topic, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
Exemplo n.º 5
0
 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("该邮箱已经被注册,请更换邮箱申请或尝试找回密码!")
Exemplo n.º 6
0
def edit_profile():
    """Updates a profile"""
    if g.user is None:
        abort(401)
    form = dict(name=g.user.name, email=g.user.email)
    if request.method == 'POST':
        if 'delete' in request.form:
            db_session.delete(g.user)
            db_session.commit()
            session['openid'] = None
            flash(u'Profile deleted')
            return redirect(url_for('index'))
        form['name'] = request.form['name']
        form['email'] = request.form['email']
        if not form['name']:
            flash(u'Error: you have to provide a name')
        elif '@' not in form['email']:
            flash(u'Error: you have to enter a valid email address')
        else:
            flash(u'Profile successfully created')
            g.user.name = form['name']
            g.user.email = form['email']
            db_session.commit()
            return redirect(url_for('edit_profile'))
    return render_template('edit_profile.html', form=form)
Exemplo n.º 7
0
    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))
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
def delete_task(task_id, member_id):
    '''
    INPUT
    Triggered via a close button element, handed the task_id implicitly from the
    page request.  Assumes there will be a member_id and group_id in the request.

    REQUIREMENT
    Can only be used before a task has been delivered.

    OUTPUT
    Removes a Task entry from the database, erasing it from the Tasks of each
    Member.
    '''

    # Grab the Task we need.
    task = Task.query.get(task_id)
    member = Member.query.get(member_id)

    # Sanity check -- does this Member have delete rights -- i.e. are they an approving member?
    if task.is_approving(member):
        # Yup!  Delete it and save our work.
        db_session.delete(task)
        db_session.commit()

    else:
        # No!  Scoundrels, throw up an Exception.
        raise Exception("This Member is trying to delete a Task they aren't approving!")
Exemplo n.º 10
0
def comment_create():
    data = request.get_json()
    article = g.article
    
    form = CommentForm(**data)
    if form.validate():
        form_data = form.data
        form_data['user'] = g.user
        form_data['ip'] = request.remote_addr

        try:
            comment = article.create_comment(**form_data)
            article.update_comment_count()
            article.update_user_comment_count(user_id=comment.user_id)

            db_session.commit()

            cache.update_article(article.id, article)
            cache.update_sorted_articles(article, 'comment_count')
            return jsonify({"data": comment.json_data()})
        except ModelException, me:
            db_session.rollback()
            return json_error(type=me.type, messages=me.message)
        except Exception, e:
            logging.error(e)
            db_session.rollback()
            return json_error_database()
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)
Exemplo n.º 12
0
 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))
Exemplo n.º 13
0
 def handleRemoveGeopointGroup(self):
     """
     删除指定的整个地理坐标集合
     需要校验地理坐标集合是否属于操作者本人
     :return:
     """
     gid, pwd = self.postParams("gid", "pwd")
     if self.checkParamsAvailable(gid, pwd):
         if self.userIdentification(pwd):
             current_user = UserIdentify()
             geo_group_info = db_session.query(GeoPointGroup).filter(GeoPointGroup.id==gid).first()
             if geo_group_info is not None:
                 if (geo_group_info.u_id == current_user.uid):
                     try:
                         # 删除集合下的所有观察子节点
                         db_session.query(GeoPointUnit).filter(GeoPointUnit.group_id==gid).delete()
                         db_session.delete(geo_group_info)
                         db_session.commit()
                         self.changeResponse2Success()
                     except Exception as e:
                         self.setFailureReason(str(e), redirect_url=url_for(".ViewGeoGroup", gid=gid))
                 else:
                     self.setFailureReason("该地理坐标点位集合不属于您,无法执行删除操作!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
             else:
                 self.setFailureReason("指定的地理坐标点位集合不存在!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
         else:
             self.setFailureReason("对不起,您不具备执行当前操作的权限!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
Exemplo n.º 14
0
 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('缺少关键参数!')
Exemplo n.º 15
0
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()
Exemplo n.º 16
0
 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))
Exemplo n.º 17
0
 def update_current_order(id,new_status_id, new_delivery_id=None, new_delivery_address=None, new_comment=None):
     entry = Order.get_order(id)
     entry.status_id = new_status_id
     entry.delivery_id = new_delivery_id
     entry.delivery_address = new_delivery_address
     entry.comment = new_comment
     db_session.commit()
Exemplo n.º 18
0
    def update_view_count(self, ip, user=None, commit=False):
        """Updates the view count of the entry. The view count is only updated once very 2 hours to avoid duplication
        Args:
            ip (str): an ip address of the current user_id
            user (User): the current user (None if it is a guest)
            commit (bool): whether to commit changes
        Returns
            True if view_count is updated
            False otherwise
        """
        updated = False
        last_view = self._last_ip_view(hash(ip))
        threshold = 2*3600*1000 # update view_count once very 2 hours
        diff = now_ms() - last_view
        if diff == 0 or diff > threshold:
            cls = self.__class__
            self.query.filter_by(id=self.id).update({cls.view_count: cls.view_count + 1})
            updated = True
            if commit:
                db_session.commit()

        # add the entry to user log
        if user is not None:
            self._update_user_view_log(user.id)

        return updated
Exemplo n.º 19
0
    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
Exemplo n.º 20
0
def event_rsvp(request, event_id, member_id):
    '''
    INPUT
    Member object in the request to make sure they were invited to begin with. Other
    than that, the event_id is enough to work things out.

    RESULT
    The Member is added to the Event's .rsvp_yes attribute.  The function returns
    True to confirm successful operation, Exception if it fails.
    '''
    # Grab the standard Group and Member so we know who and where the request is coming from.

    # Grab the event and validate where the guest was even invited.
    # ...
    # Because *God*, does she even go here?
    this_event = Event.query.get(event_id)
    rsvp_member = Member.query.get(member_id)
    if rsvp_member in this_event.invited:
        attending = request.form['attending']
        if attending: # Note, this works specifically because the form's value for Yes is True.
            this_event.rsvp_yes.append(rsvp_member)
        else:
            this_event.rsvp_no.append(rsvp_member)
        db_session.commit()
    else:
        return Exception("That member wasn't even invited to this event!")
Exemplo n.º 21
0
def vote():
    article = g.article
    data = request.get_json()
    up = data.get('up', True)

    try:
        vote = article.vote(user=g.user, ip=request.remote_addr, up=up)
        if vote.id:
            # this is an updated vote
            if vote.changed:
                points = article.update_points(up=up, points=2)
                article.user.update_points(up=up, points=11)
            else:
                points = article.points
        else:
            # this is a new vote
            points = article.update_points(up)
            user_points = 1
            if up:
                user_points = 10
            article.user.update_points(up=up, points=user_points)
        
        db_session.commit()
        data = {
            "points": points
        }

        cache.update_article(article.id, article)
        cache.update_sorted_articles(article, 'points')
        return jsonify({"data": data})
    except Exception, e:
        logging.error(e)
        db_session.rollback()
        return json_error_database()
Exemplo n.º 22
0
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!")
Exemplo n.º 23
0
 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)
Exemplo n.º 24
0
def deliver_task(request, task_id, member_id):
    '''
    INPUT
    Triggered via a delivery mechanism.  Only requires the task_id and a reference
    to the deliverable which completed it.  If an already delivered task is delivered
    again, the new deliverable overwrites the old one.  Assumes that request.POST['deliverable']
    has something in it -- text, image, file, whatever.  For now, it's stored as binary data.

    OUTPUT
    Changes the delivered Boolean of the specified Task to True, puts whatever was stored at
    that part of the request into the Task.deliverable attribute.
    '''
    current_member = Member.query.get(member_id)
    task = Task.query.get(task_id)
    signature = request.form['signature']
    if task.is_delivering(current_member):
        if current_member.get_realname() == signature:
            task.delivered = True

            # Set the late property to True if they turned it in after the deadline.
            if datetime.now() > task.deadline:
                task.late = True

            db_session.commit()
        else:
            raise Exception("The signature doesn't line up the Member's stored real name!")
    else:
        raise Exception("The person turning this in isn't the one who was supposed to!")
Exemplo n.º 25
0
 def leave_room(self, json):
   """退室。ホストが抜けたら解散"""
   args = loads(json)
   print args
   pr = self._is_room_owner(args["channel"], args["caller"])
   if pr:
     members = self._execute_breakup(pr.general_record)
   else:
     user = self._whoami(args["caller"])
     if user is None:
       return dumps((False,))
     pr = self._get_active_pr(user)
     if pr is None:
       return dumps((False,))
     if pr.general_record.channel != args["channel"]:
       return dumps((False,))
     pr.active = False
     pr.leaved = True
   pr.general_record.umari_at = None
   pr.general_record.rating_match = None
   db_session.commit()
   returns = self._construct_room_info(pr.general_record, pr.user)
   if pr.general_record.brokeup:
     returns.update({"members": [self._construct_member_info(pr) for pr in members]})
   return dumps((True, returns))
Exemplo n.º 26
0
 def update_order_product(order_id, product_id, dimension_id, new_quantity, new_price):
     number_of_items = Dimension.get_dimension(dimension_id).number
     product_price_per_line = number_of_items*new_quantity*new_price
     order_product_up = OrderProduct.get_order_product(order_id, product_id, dimension_id)
     order_product_up.quantity = new_quantity
     order_product_up.price = new_price
     order_product_up.product_price_per_line = product_price_per_line
     db_session.commit()
Exemplo n.º 27
0
    def update_comment_count(self, offset=1, commit=False):
        cls = self.__class__
        self.query.filter_by(id=self.id).update({cls.comment_count: cls.comment_count + offset})

        if commit:
            db_session.commit()

        return self.comment_count 
Exemplo n.º 28
0
 def update_order_number(id,order_number):
     order = Order.get_order(id)
     if Order.query.filter(Order.order_number == order_number).count() == 0:
         order.order_number = order_number
         db_session.commit()
         return True
     else:
         return False
Exemplo n.º 29
0
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'))
Exemplo n.º 30
0
 def update_order_details(id, gift, status, delivery_date):
     order = Order.get_order(id)
     order_status = OrderStatus.query.filter(OrderStatus.name == status).first()
     order.gift = gift
     order.status = order_status
     order.status_id = order_status.id
     order.delivery_date = delivery_date
     db_session.commit()
Exemplo n.º 31
0
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)

    # 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)
Exemplo n.º 32
0
    async def channel_karma(self,
                            ctx: Context,
                            channel: TextChannel,
                            mode: MiniKarmaMode.get = None):
        # TODO: avoid writing duplicate code with above if possible?
        karma_channel = (db_session.query(MiniKarmaChannel).filter(
            MiniKarmaChannel.channel == channel.id).first())

        if mode == MiniKarmaMode.Mini:
            if karma_channel is None:
                user = (db_session.query(User).filter(
                    User.user_uid == ctx.author.id).first())
                new_karma_channel = MiniKarmaChannel(
                    channel=channel.id,
                    user_id=user.id,
                )
                db_session.add(new_karma_channel)
                try:
                    db_session.commit()
                    await ctx.send(
                        f"Added {channel.mention} to the mini-karma channels")
                except SQLAlchemyError as e:
                    db_session.rollback()
                    logging.error(e)
                    await ctx.send(
                        "Something went wrong. No change has occurred.")
            else:
                await ctx.send(
                    f"{channel.mention} is already on mini-karma mode!")
        elif mode == MiniKarmaMode.Normal:
            if karma_channel is not None:
                db_session.query(MiniKarmaChannel).filter(
                    MiniKarmaChannel.channel == channel.id).delete()
                try:
                    db_session.commit()
                    await ctx.send(
                        f"{channel.mention} is now on normal karma mode")
                except SQLAlchemyError as e:
                    db_session.rollback()
                    logging.error(e)
                    await ctx.send(
                        "Something went wrong. No change has occurred")
            else:
                await ctx.send(
                    f"{channel.mention} is already on normal karma mode!")
        else:
            if karma_channel is None:
                await ctx.send(f"{channel.mention} is on normal karma mode.")
            else:
                await ctx.send(f"{channel.mention} is on mini-karma mode.")
Exemplo n.º 33
0
 def mutate(self, info, name):
     matching = ArtistModel.query.filter(
         or_(ArtistModel.name == name,
             ArtistModel.alt_names.any(
                 ArtistNameModel.name == name))).all()
     if len(matching) == 0:
         # create
         new_artist = ArtistModel(name=name)
         db_session.add(new_artist)
         db_session.commit()
         return QueryOrCreateArtistMutation(artists=[new_artist])
     else:
         # TODO: what to do when more than one match???
         return QueryOrCreateArtistMutation(artists=matching)
 def mutate(root, info, store_id, tenant, working_hours, is_enabled,
            address):
     try:
         new_store = StoreModel(store_id=store_id,
                                tenant=tenant,
                                working_hours=working_hours,
                                is_enabled=is_enabled,
                                address=address)
         db_session.add(new_store)
         db_session.commit()
         ok = True
         return CreateStore(ok=ok, store=new_store)
     except Exception:
         return CreateStore(ok=False)
Exemplo n.º 35
0
def add_user():
    if not request.json or ('username' not in request.json
                            or 'password' not in request.json
                            or 'level' not in request.json):
        abort(406)
    if not request.json['username'] or \
            not request.json['password'] or \
            not request.json['level']:
        abort(406)
    user = User(request.json['username'], request.json['password'],
                request.json['level'])
    db_session.add(user)
    db_session.commit()
    return jsonify({'mobilerp': [user.serialize]})
 def create_session(self, user_id=None):
     """ overloaded create_session method """
     sess_id = super().create_session(user_id)
     if sess_id is None:
         return None
     try:
         sess = UserSession()
         sess.user_id = user_id
         sess.session_id = sess_id
         db_session.add(sess)
         db_session.commit()
         return sess.session_id
     except:
         return None
Exemplo n.º 37
0
    async def on_message_delete(self, message: Message):
        # Get the message from the database
        db_message = (db_session.query(LoggedMessage).filter(
            LoggedMessage.message_uid == message.id).one_or_none())

        # Can't really do anything if the message isn't in the logs so only handle when it is
        if db_message:
            # Update the message deleted_at and commit the changes made
            db_message.deleted_at = datetime.utcnow()
            try:
                db_session.commit()
            except (ScalarListException, SQLAlchemyError) as e:
                db_session.rollback()
                logging.error(e)
    def destroy_session(self, request=None):
        """ removes a session """
        try:
            sess_id = self.session_cookie(request)
            if sess_id is None:
                return False

            sess = db_session.query(UserSession).filter(
                UserSession.session_id == sess_id).one()
            db_session.delete(sess)
            db_session.commit()
            return True
        except:
            return False
Exemplo n.º 39
0
def put_data_resume_in_base(data_resumes_list, db_session):
    all_urls = []
    for item in Resume.query.all():
        all_urls.append(item.url)

    for item in data_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)
    db_session.commit()
Exemplo n.º 40
0
    async def del_filament(self, ctx: Context, filament_name: clean_content):
        filament = (db_session.query(FilamentType).filter(
            FilamentType.name.like(filament_name)).first())

        if not filament:
            await ctx.send(
                f'Couldn\'t find a filament that matches the name "{filament_name}"'
            )
            return

        db_session.delete(filament)
        db_session.commit()

        await ctx.send(f'Removed "{filament_name}" from the filament list!')
Exemplo n.º 41
0
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)
    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(url_for('index'))
Exemplo n.º 42
0
    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)
Exemplo n.º 43
0
    async def add(self, ctx: Context, *args: clean_content):
        if not args:
            await ctx.send("You're missing a time and a message!")
        else:
            trigger_time = parse_time(args[0])
            now = datetime.now()
            if not trigger_time:
                await ctx.send("Incorrect time format, please see help text.")
            elif trigger_time < now:
                await ctx.send("That time is in the past.")
            else:
                # HURRAY the time is valid and not in the past, add the reminder
                display_name = get_name_string(ctx.message)

                # set the id to a random value if the author was the bridge bot, since we wont be using it anyways
                # if ctx.message.clean_content.startswith("**<"): <---- FOR TESTING
                if user_is_irc_bot(ctx):
                    author_id = 1
                    irc_n = display_name
                else:
                    author_id = (db_session.query(User).filter(
                        User.user_uid == ctx.message.author.id).first().id)
                    irc_n = None

                if len(args) > 1:
                    rem_content = " ".join(args[1:])
                    trig_at = trigger_time
                    trig = False
                    playback_ch_id = ctx.message.channel.id
                    new_reminder = Reminder(
                        user_id=author_id,
                        reminder_content=rem_content,
                        trigger_at=trig_at,
                        triggered=trig,
                        playback_channel_id=playback_ch_id,
                        irc_name=irc_n,
                    )
                    db_session.add(new_reminder)
                    try:
                        db_session.commit()
                        await ctx.send(
                            f"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {CONFIG.REMINDER_SEARCH_INTERVAL} seconds)."
                        )
                    except (ScalarListException, SQLAlchemyError) as e:
                        db_session.rollback()
                        logging.error(e)
                        await ctx.send(f"Something went wrong")
                else:
                    await ctx.send("Please include some reminder text!")
Exemplo n.º 44
0
    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 its cost per kilogram."
            )
            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"
            )

        print_root_dir = Path(CONFIG["PRINTER_FILE_ROOT"])
        print_images_dir = Path(print_root_dir, "images")

        # Do a quick check the folder(s) exist and make them if not
        print_images_dir.mkdir(parents=True, exist_ok=True)

        filament_name, filament_cost = args[:2]
        filament_cost = float(filament_cost)
        image_file = Path(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=filament_name,
                                cost=filament_cost,
                                image_path=str(image_file))
        db_session.add(filament)
        db_session.commit()
        await ctx.send(
            f'"{filament_name}" added to the available filament list!')
Exemplo n.º 45
0
def accounts_edit(user, account_id):
    schema = {
        "type": "object",
        "properties": {
            "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": ["encrypted_account_data"]
    }

    error = validate_schema(request.json, schema)

    encrypted_account_data = request.json["encrypted_account_data"]

    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")

    AccountDataItem.query.filter(AccountDataItem.account_id==a.id).delete()

    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(success=True)
Exemplo n.º 46
0
async def on_message_edit(before: Message, after: Message):
    # Only care about messages that are in public channels
    if isinstance(before.channel, GuildChannel):
        # Message wasn't pinned
        if before.pinned == after.pinned:
            # Log any edits to messages
            original_message = db_session.query(LoggedMessage).filter(
                LoggedMessage.message_uid == before.id).first()
            if original_message:
                message_diff = MessageDiff(
                    original_message=original_message.id,
                    new_content=after.clean_content,
                    created_at=(after.edited_at or datetime.utcnow()))
                db_session.add(message_diff)
                db_session.commit()
def update_user(user_id):
    """ updates a user by their id """
    req = request.get_json()
    if req is None:
        return jsonify({'error': 'Wrong format'}), 400
    try:
        user = db_session.query(User).filter(User.id == user_id).one()
        if req.get('first_name') is not None:
            user.first_name = req.get('first_name')
        if req.get('last_name') is not None:
            user.last_name = req.get('last_name')
        db_session.commit()
        return jsonify(user.to_dict())
    except:
        abort(404)
Exemplo n.º 48
0
def write_article():
    title = u'发布成功'
    post_title = request.form.get('title')
    post_content = request.form.get('content')
    post_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    post_uid = db_session.query(
        User.id).filter(User.username == session.get('username')).first()[0]
    tmp = Article(title=post_title,
                  content=post_content,
                  data_publish=post_datetime,
                  user_id=post_uid)
    db_session.add(tmp)
    db_session.commit()
    db_session.close()
    return render_template('write.html', title=title)
Exemplo n.º 49
0
    def record(self, user, ip, data, reason=None, commit=False):
        ref_name = get_remote_side(self, 'edits')

        cls = get_remote_side_class(self, 'edits')
        edit = cls()
        setattr(edit, ref_name, self.id)
        edit.user_id = user.id
        edit.ip = hash(ip)
        edit.data = data
        edit.reason = reason

        db_session.add(edit)

        if commit:
            db_session.commit()
Exemplo n.º 50
0
    def mutate(self, info, name, hiredOn, departmentid):
        print('----------------------------------------')
        print(info.context.headers['Authorization'])
        print('----------------------------------------')
        hiredDate = datetime.strptime(hiredOn, '%d/%m/%Y')
        newEmployee = EmployeeModel(name=name,
                                    hired_on=hiredDate,
                                    department_id=departmentid)
        db_session.add(newEmployee)
        db_session.commit()

        return CreateEmployee(id=newEmployee.id,
                              name=newEmployee.name,
                              hiredOn=newEmployee.hired_on,
                              departmentid=newEmployee.department_id)
Exemplo n.º 51
0
def create_event_comment(request, sse, event_id):
    event = db_session.query(Events).filter_by(id=event_id).first()
    if not event:
        return jsonify(error=True, message='event not found')

    data = json.loads(request.data)
    if not data:
        return jsonify(error=True,
                       message='request body is empty, check headers/data')
    if 'text' not in data:
        return jsonify(error=True,
                       message='no text key/value pair in request body')

    text = str(data['text']).encode()

    new_comment = EventComments(event_id=event_id,
                                owner_id=user_session['account_id'],
                                text=text)
    db_session.add(new_comment)

    if event.host_id != user_session['account_id']:
        you = db_session.query(Accounts).filter_by(
            id=user_session['account_id']).one()

        message = you.username + ' commented on your event(' + event.title[:
                                                                           10] + '...' + '): ' + text[:
                                                                                                      10] + '...'

        new_notification = Notifications(action=ACTION_TYPES['NEW_COMMENT'],
                                         target_type=TARGET_TYPES['EVENT'],
                                         target_id=event.id,
                                         from_id=user_session['account_id'],
                                         account_id=event.host_id,
                                         message=message,
                                         link='/event/' + str(event.id))

        db_session.add(new_notification)

        sse.publish({
            "message": message,
            "for_id": event.host_id
        },
                    type='action')

    db_session.commit()

    return jsonify(message='event comment created',
                   comment=new_comment.serialize)
Exemplo n.º 52
0
    def mutate(self, info, merge_to_id, duplicate_id):
        if merge_to_id == duplicate_id:
            return MergeSongMutation(ok=False)
        merge_to_artist = ArtistModel.query.get(merge_to_id)
        duplicate_artist = ArtistModel.query.get(duplicate_id)

        merge_to_artist.alt_names.append(
            ArtistNameModel(name=duplicate_artist.name))
        for alt_name in duplicate_artist.alt_names:
            alt_name.artist = merge_to_artist
        for song in duplicate_artist.songs:
            song.artists.append(merge_to_artist)

        db_session.delete(duplicate_artist)
        db_session.commit()
        return MergeArtistMutation(ok=True)
Exemplo n.º 53
0
def blog_post(blog_post_title):
	whole_blog_post = db_session.query(Blog_Post).filter(Blog_Post.title == blog_post_title).first()
	blog_post_comments = db_session.query(Blog_Post).options(lazyload('comments')).all()
	if request.method == 'POST':
		user_name = request.form['user_name']
		content = request.form['content']
		new_comment = Comments(user_name, content, whole_blog_post)
		db_session.add(new_comment)
		try:
			print("sucsess")
			db_session.commit()
		except exc.SQLAlchemyError:
			print "error"
			pass
		return redirect(url_for('routes.blog_post',blog_post_title=whole_blog_post.title))
	return render_template('blogpost.html', blog_post = whole_blog_post, comments = blog_post_comments)
Exemplo n.º 54
0
 def mutate(self,info,id):
     local_id = from_global_id(id)[1]
     cart=db_session.query(CartModel).filter_by(id=local_id).scalar()
     in_cart = Counter([item.product for item in cart.items])
     insufficient_stock = []
     for prod in in_cart:
         new_inventory= prod.inventory_count - in_cart[prod]
         if new_inventory < 0:
             insufficient_stock.append(to_global_id("Product",prod.id))
         else:   
             db_session.query(ProductModel).filter_by(id=prod.id).update(dict(inventory_count=new_inventory))
     if insufficient_stock:
         db_session.rollback()
         return CartComplete(success=False,insufficient_stock=insufficient_stock)
     db_session.commit()
     return CartComplete(success=True)
    def destroy_session(self, request=None):
        """Overloading

        :param request: Default value = None)

        """
        if request:
            session_id = self.session_cookie(request)
            if session_id:
                if super(SessionDBAuth, self).destroy_session(request):
                    for user_session in db_session.query(UserSession).filter(
                            UserSession.session_id == session_id):
                        db_session.delete(user_session)
                        db_session.commit()
                        return True
        return False
    def log_last_scraped(self):
        try:
            try:
                last_comic_id = min(self.comic_ids) - 1
            except ValueError:
                last_comic_id = self.max_id

            setting = db_session.query(Setting).filter(Setting.bit == 0).one()
            setting.comic_last_id = last_comic_id
            setting.comic_last_ran = cutil.get_datetime()

            db_session.add(setting)
            db_session.commit()

        except:
            logger.exception("Problem logging last comic scraped")
Exemplo n.º 57
0
 def mutate(self, info, input):
     print("input")
     print(input)
     data = input
     data["id"] = data.iduser
     del data['iduser']
     print(data)
     # data = utils.input_to_dictionary(input)
     # data['created'] = datetime.utcnow()
     # data['edited'] = datetime.utcnow()
     print("data")
     print(data)
     user = UserModel(**data)
     db_session.add(user)
     db_session.commit()
     return CreateUser(user=user)
Exemplo n.º 58
0
async def run(article, limit_rd):
    global URL
    async with ClientSession() as session:
        page = Page(url=URL.format(article))
        db_session.add(page)
        db_session.commit()
        db_session.refresh(page)
        main_task = [
            asyncio.ensure_future(
                parse(article,
                      session,
                      0,
                      from_page_id=page.id,
                      limit_rd=limit_rd))
        ]
        await asyncio.gather(*main_task)
Exemplo n.º 59
0
    async def remove(self, ctx: Context, item: str):
        if (
            not db_session.query(BlockedKarma)
            .filter(BlockedKarma.topic == item.casefold())
            .all()
        ):
            await ctx.send(f"{item} is not in the karma blacklist. :page_with_curl:")
        else:
            db_session.query(BlockedKarma).filter(
                BlockedKarma.topic == item.casefold()
            ).delete()
            db_session.commit()

            await ctx.send(
                f"{item} has been removed from the karma blacklist. :wastebasket:"
            )
Exemplo n.º 60
0
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)