Ejemplo n.º 1
0
def create():
    name = request.form['name']
    if User.exist(name):
        abort(400, "A user with the same name already exists")
    user = User.create(name, app.config['USER_PWD'])
    db.session.commit()
    return jsonify(user.id)
Ejemplo n.º 2
0
def _get_verify_list(status=None):
    page_index, page_size = get_page_info()

    join = 'as a left join %s as b on a.newWriterId = b.id' % (
        NewWriterPool.__table__, )
    args = [ctx.request.user.uid]
    where = '%s where a.uid = ? and a.status != 1' % (join, )
    count_where = 'where uid = ? and status != 1'

    if status is not None:
        args.append(status)
        where = '%s and a.status = ?' % (where, )
        count_where = '%s and status = ?' % (count_where, )

    total = NewWriterVerifyRecord.count_by(count_where, *args)
    page = Page(total, page_index, page_size)

    where = '%s order by a.updateAt DESC limit ?,?' % (where, )

    args.append(page.offset)
    args.append(page.limit)
    lists = NewWriterVerifyRecord.select_by(where, args, [
        'a.*', 'b.phone', 'b.ippreId', 'b.uid as userId', 'b.verifyType',
        'b.verifyResult'
    ])
    IPPool.join_by(lists, 'ippreId', 'ippreId')
    User.join_by(lists, 'userId', 'id')

    return lists, page.to_dict()
Ejemplo n.º 3
0
def _get_list_by_page(list_type='0',
                      status='-1',
                      final_state='-1',
                      title=None,
                      boutique='-1'):
    page_index, page_size = get_page_info()

    args = [list_type]
    where = 'where type = ?'

    if title:
        global IPPRE
        query = IPPRE.query

        query_res = query.contains('title', title).find()

        id_list = []
        for info in query_res:
            id_list.append(info.id)

        args = []
        where = "where ippreId in ('%s')" % ("','".join(id_list), )

    else:
        if status != '-1':
            args.append(status)
            where = '%s and status = ?' % (where, )
        if final_state != '-1':
            args.append(final_state)
            where = '%s and finalState = ?' % (where, )
        if boutique == '1':
            where = '%s and ((verifyType = 3 or verifyType = 4) and verifyResult = 1)' % (
                where, )
        if boutique == '2':
            where = '%s and ((verifyType = 3 or verifyType = 4) and verifyResult = 2)' % (
                where, )
        if boutique == '3':
            where = '%s and ((verifyType = 1 and verifyResult = 1) or ((verifyType = 3 or verifyType = 4) and verifyResult = 0))' % (
                where, )
        if boutique == '4':
            where = '%s and verifyType = 1 and verifyResult = 2' % (where, )

    total = NewWriterPool.count_by(where, *args)

    page = Page(total, page_index, page_size)
    where = '%s order by id DESC limit ?,?' % (where, )

    args.append(page.offset)
    args.append(page.limit)
    lists = NewWriterPool.find_by(where, *args)
    IPPool.join_by(lists, 'ippreId', 'ippreId')
    User.join_by(lists, 'uid', 'id')

    return lists, page.to_dict()
Ejemplo n.º 4
0
def do_reg_user():
    app.logger.debug(request)
    # 교회에 해당 아이디를 생서 우편번호화 생성 일자 결합
    #church_id = createChurchId(request.values['zip_code']);

    # 입력반응 사용자 정보 저장
    user = User(request)
    user.insert_user_info()
    # 입력 받은 교회 정보 저장
    #regChruchInfo(request, church_id)
    return render_template('user/welcome.html')
Ejemplo n.º 5
0
def create_admin():
    admin_username = app.config["ADMIN_USERNAME"]
    admin = User.query.filter_by(username=admin_username).one_or_none()
    if not admin:
        admin = User.create(admin_username, app.config["ADMIN_PWD"])
    if not admin.is_admin():
        admin.add_role(Role.get_admin())
Ejemplo n.º 6
0
def reset_password():
    """
    重置密码
    :return:
    """
    email = request.json.email
    user = User.objects(account__email=email).first()
    if user:
        user.account.activation_key = str(uuid4())
        user.save()

        url = 'http://m.maybe.cn/account/confirm_reset_password?activation_key=%s&email=%s' % (
            user.account.activation_key, user.account.email)
        html = render_template('admin/user/_reset_password.html',
                               project=current_app.config['PROJECT'],
                               username=user.name,
                               url=url)
        message = Message(subject=gettext('reset your password in ') + 'maybe',
                          html=html,
                          recipients=[user.account.email])
        message.sender = '*****@*****.**'
        mail.send(message)
        return jsonify(
            message='OK',
            desc=gettext(
                'please see your email for instructions on how to access your account'
            ))
    else:
        return jsonify(
            message='Failed',
            desc=gettext('sorry, not found user for that email address'))
Ejemplo n.º 7
0
 def delete(self, userid):
     '''Delete user data by user ID'''
     try:
         resp = User().delete_data_by_userid(userid)
         return masked_json_template(resp, 200)
     except:
         abort(400, "Input unrecognizable.")
Ejemplo n.º 8
0
 def get(self, username):
     '''Get user data by username'''
     try:
         resp = User().get_data_by_username(username)
         return masked_json_template(resp, 200)
     except:
         abort(400, "Input unrecognizable.")
Ejemplo n.º 9
0
def __make_default():
    admin_role = Role.create_role(db_manager, "admin", "Forum administrator")
    admin_role.add_permission("create")
    admin_role.add_permission("read")
    admin_role.add_permission("update")
    admin_role.add_permission("delete")

    super_moderator = Role.create_role(db_manager, "moderator",
                                       "Forum super moderator")
    super_moderator.add_permission("create")
    super_moderator.add_permission("read")
    super_moderator.add_permission("update")
    super_moderator.add_permission("delete")

    Role.create_role(db_manager, "user", "Forum user")
    User.create_user(db_manager, "Admin", "*****@*****.**", "123456")
Ejemplo n.º 10
0
    def pay(self, order, amount, coin_type=COIN_TYPE.COIN):
        if coin_type == COIN_TYPE.COIN and amount > self.balance:
            current_app.logger.error(
                'order coin exceed wallet balance. order: {}, amount: {}, balance: {}'
                .format(order.id, amount, self.balance))
            amount = self.balance
        if coin_type == COIN_TYPE.CASH and amount > self.cash:
            current_app.logger.error(
                'order cash exceed balance. order: {}, amount: {}, balance: {}'
                .format(order.id, amount, self.cash))
            amount = self.cash

        time = datetime.utcnow()
        reason = COIN_TRADE_REASON.PAY
        kind = COIN_TRADE_TYPE.OUTCOME
        user = User.objects(id=order.customer_id).first()
        trade = CoinTrade.create(user=user,
                                 amount=amount,
                                 time=time,
                                 kind=kind,
                                 reason=reason,
                                 wallet=self,
                                 reason_id=str(order.id),
                                 coin_type=coin_type)
        return trade
Ejemplo n.º 11
0
    def logs(self, ltype, lid):
        """

        :param ltype:
        :param lid:
        :return:
        """
        if ltype == 'express':
            logistics = Logistic.objects(id=lid).first().express_tracking
            return self.render('admin/logistic/express.html',
                               logistics=logistics)
        elif ltype == 'logistic':
            logistics = LogisticLog.objects(logistic_id=lid,
                                            log_type__ne='API')
            user = lambda i: getattr(User.objects(id=i).first(), 'name', ''
                                     ) if i and i != 'system' else i
            return self.render('admin/logistic/logs.html',
                               logistics=logistics,
                               user=user)
        elif ltype == 'print':
            logistic = Logistic.objects(id=lid).first()
            if logistic.is_closed:
                return Response('this logistics id has been closed.')
            return self.render('admin/logistic/print_page.html',
                               logistic=logistic)
Ejemplo n.º 12
0
def reset_password():
    """
    重置密码
    :return:
    """
    form = RecoverPasswordForm()
    if form.validate_on_submit():
        user = User.objects(account__email=form.email.data).first()
        if user:
            flash(
                gettext(
                    'please see your email for instructions on how to access your account'
                ), 'success')
            user.account.activation_key = str(uuid.uuid4())
            user.save()

            # send recover password html
            # TODO: change project name
            url = 'http://bigbang.maybe.cn/admin/confirm_reset_password?activation_key=%s&email=%s' % (
                user.account.activation_key, user.account.email)
            html = render_template('admin/user/_reset_password.html',
                                   project=current_app.config['PROJECT'],
                                   username=user.name,
                                   url=url)
            jobs.notification.send_mail.delay(
                [user.account.email],
                gettext('reset your password in ') + 'Maybe', html)
            return render_template('admin/user/reset_password.html', form=form)
        else:
            flash(gettext('sorry, no user found for that email address'),
                  'error')

    return render_template('admin/user/reset_password.html', form=form)
Ejemplo n.º 13
0
    def load_user(id):
        """

        :param id:
        :return:
        """
        return User.objects(id=id, is_deleted=False).first()
Ejemplo n.º 14
0
def login():
    """
    登录
    :return:
    """
    if request.user_agent.platform in ['ipad', 'iphone', 'android']:
        return jsonify(error='请先登录')
    # 用户验证通过直接跳转到首页
    if current_user.is_authenticated:
        return redirect_next()
    if request.method == 'POST':
        email = request.form.get('email', None)
        password = request.form.get('password', None)
        if email and password:
            user, authenticated = User.authenticate(email=email,
                                                    password=password)
        else:
            flash(gettext('please enter the correct email and password.'))
            return redirect_next()

        if user and authenticated:
            # remember = request.form.get('remember') == 'y'
            remember = True
            login_user(user, remember)
        else:
            flash('帐号或密码不正确')

        return redirect_next()

    return render_template('admin/user/login.html')
Ejemplo n.º 15
0
def forget_password():
    """

    :return:
    """
    email = request.json.get('email', '')
    if not email:
        return jsonify(message='Failed',
                       error=gettext('please correct the email format'))

    user = User.objects(account__email=email).first()
    if not user:
        return jsonify(
            message='Failed',
            error=gettext('sorry, no user found for that email address'))

    user.account.activation_key = str(uuid4())
    user.save()
    url = 'http://account.maybe.cn/account/confirm_reset_password?activation_key=%s&email=%s' % (
        user.account.activation_key, user.account.email)
    html = render_template('admin/user/_reset_password.html',
                           username=user.name,
                           url=url)
    jobs.notification.send_mail.delay([user.account.email],
                                      gettext('reset your password in ') +
                                      'maybe',
                                      html=html)
    return jsonify(message='OK')
Ejemplo n.º 16
0
 def get(self, hobby, register_after):
     '''Get user's hobby'''
     try:
         resp = User().get_data_by_hobby(hobby, register_after)
         return masked_json_template(resp, 200)
     except:
         abort(400, "Input unrecognizable.")
Ejemplo n.º 17
0
def start_main_window():
    app = QtWidgets.QApplication(sys.argv)

    #     signin_dialog = signin_window.SignInDialog()
    # #
    #     if signin_dialog.exec_() != 1:
    #         return
    #-----------------------------------------
    from app._lib.server import api
    from app.models.user.user import User
    server = api.Api(TITOD_HOST, TITOD_PORT)
    server.get_credentials('AndrIi', '123')
    user = User.init_user(server)
    user.set_current_project()
    #
    # #     user.update_user_data()
    #     create_users(server)

    w = MainAppWindow(user)
    #-----------------------------------------

    #     w = MainAppWindow(signin_dialog.user)
    w.show()

    sys.exit(app.exec_())
Ejemplo n.º 18
0
 def get(self, hobby, start_date, end_date):
     '''Get user's hobby'''
     try:
         resp = User().get_data_by_hobby_between(hobby, start_date, end_date)
         return masked_json_template(resp, 200)
     except:
         abort(400, "Input unrecognizable.")
Ejemplo n.º 19
0
    def connect_to_server(self):
        server = self._get_server()
        if not server:
            self.msgfield_lb.setText("Error connecting to server.")
            self.user = None
            return
#         try:
#             server = api.Api(HOST, PORT, timeout=None)
#         except Exception:
#             exc = traceback.format_exc()
#             print("!=> Error connecting to server. {}", exc)
#             self.msgfield_lb.setText("Error connecting to server.")
#             self.user = None
# #             self.server = None
#             return

        login = self.login_le.text()
        passwd = self.passwd_le.text()
        response = server.get_credentials(login, passwd)

        if response[0] is True:
            self.user = User.init_user(server)
            self.user.set_current_project()
            self.accept()
        else:
            self.msgfield_lb.setText(response[1])
Ejemplo n.º 20
0
 def post(self):
     '''Add new user'''
     try:
         json_data = api.payload
         resp = User().register(json_data)
         return masked_json_template(resp, 200)
     except:
         abort(400, "Input unrecognizable.")
Ejemplo n.º 21
0
def user_info(user_id):
    """
    获取用户信息
    :param user_id:
    :return:
    """
    user = User.objects(id=user_id).first_or_404()
    return jsonify(message='OK', user=json_templ.user_json(user))
Ejemplo n.º 22
0
 def put(self, userid):
     '''Update user data by user ID'''
     try:
         json_data = api.payload
         resp = User().update_data_by_userid(userid, json_data)
         return masked_json_template(resp, 200)
     except:
         abort(400, "Input unrecognizable.")
Ejemplo n.º 23
0
def sign_up():
    signup_form = SignupForm()
    if signup_form.validate_on_submit():
        user_name = signup_form.user_name_field.data
        user_email = signup_form.user_email_field.data
        user_password = signup_form.user_password_field.data
        if user_name and user_email and user_password:
            User.create(db_manager, user_name, user_email, user_password)
        return redirect("/signin_page")

    page_template = "auth/signup_page.html"
    page_data = {"page_name": "signup_page", "page_title": "Sign Up page"}
    return render_template(
        page_template,
        page_data=page_data,
        signup_form=signup_form,
    )
Ejemplo n.º 24
0
def unfollow(follow_id):
    """

    :param follow_id:
    :return:
    """
    follow_user = User.objects(id=follow_id).first_or_404()
    current_user.unfollow(follow_user)
    return jsonify(message='OK')
Ejemplo n.º 25
0
def confirm_reset_password():
    """
    确认密码
    :return:
    """
    if request.method == 'GET':
        if current_user.is_authenticated:
            if not login_fresh():
                return login_manager.needs_refresh()
            user = current_user
        elif 'activation_key' in request.args and 'email' in request.args:
            activation_key = request.args.get('activation_key')
            email = request.args.get('email')
            user = User.objects(
                Q(account__activation_key=activation_key)
                & Q(account__email=email)).first()
        else:
            return Response('邮件已失效')

        form = ConfirmResetPasswordForm(
            activation_key=user.account.activation_key,
            email=user.account.email)
        return render_template('admin/user/confirm_reset_password.html',
                               form=form)
    if request.method == 'POST':
        form = ConfirmResetPasswordForm()
        activation_key = form.activation_key.data
        email = form.email.data
        user = User.objects(
            Q(account__activation_key=activation_key)
            & Q(account__email=email)).first()
        # 修改密码成功
        if form.validate_on_submit():
            user.account.password = form.password.data
            user.account.activation_key = None
            user.save()
            flash(
                gettext('your password has been changed, please login again'),
                'success')
            return render_template('admin/user/success_reset_password.html')
        # 修改密码失败
        flash(gettext('fail, please confirm your password'), 'success')
        return render_template('admin/user/confirm_reset_password.html',
                               form=form)
Ejemplo n.º 26
0
def ajax_check_user():
    app.logger.debug(request)
    item = User.get_user(request)
    result = ""
    if item:
        result = 'NOTOK'
    else:
        result = 'OK'
    #return json.dumps({'status':'OK'})
    return jsonify({'status': result})
Ejemplo n.º 27
0
def bind_email():
    """

    :return:
    """
    email = request.json.get('email')
    user_id = request.json.get('user_id')
    if not email:
        return jsonify(message='Failed', error=gettext('no email'))
    if User.objects(account__email=email):
        return jsonify(message='Failed',
                       error=gettext('the email alreadly exists'))
    user = User.objects(id=user_id).first()
    user.account.email = email
    user.account.is_email_verified = True
    user.save()
    login_user(user, remember=True)
    return jsonify(message='OK',
                   user=json_templ.get_user_info(user),
                   remember_token=user.generate_auth_token())
Ejemplo n.º 28
0
def follow(follow_id):
    """

    :param follow_id:
    :return:
    """
    follow_user = User.objects(id=follow_id).first_or_404()
    if follow_user.id == current_user.id:
        return jsonify(message='Failed', error='Can not follow yourself')
    current_user.follow(follow_user)
    return jsonify(message='OK')
Ejemplo n.º 29
0
 def get(self):
     '''Logout and autoamatically revoke current access_token (PS: refresh_token still can be used)'''
     is_valid, code, msg = is_token_valid(
         request.headers.get('Authorization'))
     if is_valid:
         encoded_token = request.headers.get('Authorization').replace(
             'Bearer ', '')
         resp = User().do_logout(encoded_token=encoded_token)
         return masked_json_template(resp, 200)
     else:
         abort(code, msg)
Ejemplo n.º 30
0
 def post(self):
     '''Login using Binary Token to get Server Token'''
     try:
         json_data = api.payload
         resp = User().validate_user(json_data=json_data)
         return masked_json_template(resp, 200)
     except:
         resp = get_json_template(response=False,
                                  message="No Json Input Found.",
                                  results=-1,
                                  total=-1)
         return resp, 404
Ejemplo n.º 31
0
 def get_current_user(key_only=False):
     user = users.get_current_user()
     return User.get(user.email(), key_only=key_only)