コード例 #1
0
def forget_passwd():
    error = Error(0, '人生需要目标,有了目标才有奋斗的方向!')
    forget_info = request.json
    email = forget_info.get('email')
    passwd = forget_info.get('password')
    verify = forget_info.get('verify')
    if not (email and verify):
        error.err_code = 9
        error.err_msg = "参数为空"
        return error.make_json_response()
    user = User.get_user_by_email(email)
    if user is None:
        error.err_code = 9
        error.err_msg = '该邮箱填写错误'
    new_veri_code = redis_client.get(email)
    if new_veri_code is None:
        error.err_code = 9
        error.err_msg = '请获取邮箱验证码'
        return error.make_json_response()
    if str(new_veri_code, encoding='utf-8') != str(verify):
        error.err_code = 9
        error.err_msg = '该验证码错误,请尝试重新获取'
        return error.make_json_response()
    passwd = render_password(passwd)
    acc = {'password': passwd}
    add_status = User.update_user(user.id, acc)
    if add_status:
        return error.make_json_response()
    else:
        error.err_code = 0
        error.err_msg = "修改成功"
        return error.make_json_response()
コード例 #2
0
ファイル: account.py プロジェクト: mateon01/TIL-Python
    def post(self):
        id = request.form.get('id')
        pw = request.form.get('pw')

        if User.objects(id=id):
            return '', 204
        else:
            User(id=id, pw=pw).save()
            return '', 201
コード例 #3
0
    def post(self):
        id = str(current_identity)
        title = request.form.get('title')
        content = request.form.get('content')

        PostCol(title=title,
                content=content,
                author=User(id,
                            User.objects(id=id).first().pw)).save()

        return '', 201
コード例 #4
0
    def test_create_user(self):
        """ Create user in db
        Should: return save user in db """

        user = User(username='******',
                    email="*****@*****.**",
                    password="******",
                    provider="Tutubo")
        user.save()

        fresh_user = User.objects().first()
        assert fresh_user.username == 'oli'
        assert fresh_user.email == '*****@*****.**'
        assert fresh_user.password == '123'
        assert fresh_user.provider == 'Tutubo'
コード例 #5
0
ファイル: api_docs.py プロジェクト: saltedfist/flag_IT
def api_update():
    error = Error(0, 'success')
    access_token = request.headers.get("Access-Token")
    uid = redis_client.get(access_token)
    if not uid:
        error.err_msg = 9
        error.err_code = 'access token 为空'
        return error.make_json_response()
    user = User.get_user_by_id(int(uid))
    if user.id != 1:
        error.err_code = 9
        error.err_msg = '该用户暂无此权限,请联系管理员。'
        return error.make_json_response()
    update_info = request.json if request.json else None
    docs_id = update_info.get('docs_id')
    if docs_id is None:
        error.err_code = 9
        error.err_msg = '缺少参数。'
        return error.make_json_response()
    docs_id = update_info.pop("docs_id")
    parameter = json.dumps(update_info.get('parameter'))
    update_info['parameter'] = parameter
    re_info = json.dumps(update_info.get('re_info'))
    update_info['re_info'] = re_info
    update_status = ApiDocs.update_docs(docs_id, update_info)
    if update_status:
        return error.make_json_response()
    error.err_code = 9
    error.err_msg = '更新失败,请重试。'
    return error.make_json_response()
コード例 #6
0
ファイル: image.py プロジェクト: luigidarco96/PyServer
    def post(self):
        """
        Add a new image for the caller user
        """

        current_user = User.find_by_username(get_jwt_identity()['username'])

        current_dir = "{}{}/".format(image_save_path, current_user.id)

        if not os.path.exists(current_dir):
            os.makedirs(current_dir, exist_ok=True)

        data = request.get_json()
        image = base64.b64decode(data['image'])

        timestamp = calendar.timegm(time.gmtime())
        image_name = str(timestamp) + ".jpg"

        current_path = "{}/{}".format(current_dir, image_name)

        with open(current_path, 'wb') as f:
            f.write(image)

        custom_link = "{}/images/{}/{}".format(server_url, current_user.id,
                                               image_name)
        return custom_response(200, "Image saved", custom_link)
コード例 #7
0
    def get(self, id):
        """
        Return all the calories for the specified user
        """
        current_user = User.find_by_username(get_jwt_identity()['username'])

        if current_user.is_admin() or current_user.has_child(id):
            user = User.query.filter_by(id=id).first()
            if user is None:
                return custom_response(
                    404,
                    "User {} not found".format(id)
                )
            calories = Calorie.query.with_parent(user).all()
            calories = list_to_array(calories)
            return custom_response(
                200,
                "{} calories".format(user.username),
                calories
            )
        else:
            return custom_response(
                401,
                "Permission denied. User {} not a child".format(id)
            )
コード例 #8
0
ファイル: audience.py プロジェクト: saltedfist/flag_IT
def audience_add():
    error = Error(0, '关注成功')
    token = request.headers.get("Access-Token")
    if not token:
        error.err_code = 9
        error.err_msg = "token is None"
        return error.make_json_response()
    uid = verify_token(token)
    if uid is None:
        error.err_code = 9
        error.err_msg = "token error"
        return error.make_json_response()
    user = User.get_user_by_id(uid)
    if user is None:
        error.err_code = 9
        error.err_msg = "登陆时间已过期,请重启登陆"
        return error.make_json_response()
    json_data = request.json
    by_uid = json_data.get('by_uid')
    status = json_data.get('status') if json_data.get('status') else 1
    if not all([by_uid]):
        error.err_code = 9
        error.err_msg = "提交数据缺失,请确认后重新提交."
        return error.make_json_response()
    audience_data = {'by_uid': by_uid, 'status': status, 'uid': uid}
    add_status = Audience.add(audience_data)
    if add_status is True:
        return error.make_json_response()
    error.err_code = 9
    error.err_msg = '关注失败,请重新关注.'
    return error.make_json_response()
コード例 #9
0
ファイル: user.py プロジェクト: luigidarco96/PyServer
 def get(self):
     """
     Return the information for the caller user
     """
     user = User.find_by_username(get_jwt_identity()['username'])
     return custom_response(200, "User {}".format(user.username),
                            user.to_dict())
コード例 #10
0
 def get(self):
     """
     Return all the steps for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     steps = Step.query.with_parent(current_user).all()
     steps = list_to_array(steps)
     return custom_response(200, "Your steps", steps)
コード例 #11
0
ファイル: activity.py プロジェクト: luigidarco96/PyServer
 def get(self):
     """
     Return all activities for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     activities = Activity.query.with_parent(current_user).all()
     activities = list_to_array(activities)
     return custom_response(200, "Your activities", activities)
コード例 #12
0
ファイル: meter.py プロジェクト: luigidarco96/PyServer
 def get(self):
     """
     Return all the meters for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     meters = Meter.query.with_parent(current_user).all()
     meters = list_to_array(meters)
     return custom_response(200, "Your meters", meters)
コード例 #13
0
ファイル: heart_rate.py プロジェクト: luigidarco96/PyServer
 def get(self):
     """
     Return all the heart rates for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     heart_rates = HeartRate.query.with_parent(current_user).all()
     heart_rates = list_to_array(heart_rates)
     return custom_response(200, "Your heart rates", heart_rates)
コード例 #14
0
def account_register():
    if request.method == 'POST':
        error = Error(0, '人生需要目标,有了目标才有奋斗的方向!')
        info = request.json
        if info is None:
            error.err_code = 9
            error.err_msg = "参数为空1"
            return error.make_json_response()
        name = info.get('name')
        pass_word = info.get('password')
        # phone = info.get('phone')
        email = info.get('email')
        # verification = request.form.get('verify')
        verification = info.get('verify')  # 验证码
        if not (name and pass_word and email and verification):
            error.err_code = 9
            error.err_msg = "参数为空2"
            return error.make_json_response()
        check_name = User.get_user_by_name(name)
        if check_name:
            error.err_code = 8
            error.err_msg = "该用户名已存在"
            return error.make_json_response()
        acc = {
            'name': name,
            'password': pass_word,
            'email': email,
            'status': 1
        }
        new_verification = redis_client.get(email)
        if new_verification is None:
            error.err_code = 3
            error.err_msg = '请获取邮箱验证码'
            return error.make_json_response()
        if str(verification) != str(new_verification, encoding='utf-8'):
            error.err_code = 4
            error.err_msg = '该验证码错误,请尝试重新获取'
            return error.make_json_response()
        add_status = User.add_user(acc)
        if add_status:
            return error.make_json_response()
        else:
            error.err_code = 5
            error.err_msg = "创建失败"
            return error.make_json_response()
コード例 #15
0
 def get(self):
     """
     Return all the personal info for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     personal_info = PersonalInfo.query.with_parent(current_user).order_by(
         PersonalInfo.timestamp.desc()).all()
     personal_info = list_to_array(personal_info)
     return custom_response(200, "Your personal info", personal_info)
コード例 #16
0
ファイル: user.py プロジェクト: luigidarco96/PyServer
 def get(self):
     """
     Return all the children for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     children = current_user.family_members.all()
     children = list_to_array(children)
     return custom_response(200,
                            "{}'s children".format(current_user.username),
                            children)
コード例 #17
0
        def decorated_function(*args, **kwargs):
            user = get_jwt_identity()
            current_user = User.find_by_username(user["username"])
            if not current_user:
                return {'message': "Permission denied. User not found"}, 401

            if current_user.role > access_level:
                return {'message': "Permission denied."}, 401

            return f(*args, **kwargs)
コード例 #18
0
    async def get_all_user_by_lang(self, lang_id: int) -> List[User]:
        sql = f"""
        {User.__select__} where "lang_id" = $1
        """

        return [
            User(**acc) for acc in await self.connection.fetch(
                sql,
                lang_id,
            )
        ]
コード例 #19
0
ファイル: users.py プロジェクト: NachoRaik/tu2bo-authserver
    def user_oauth_login():
        body = request.get_json()
        if (not body or not OAUTH_FIELD in body.keys()):
            return error_response(400, 'Cant verify login credentials')

        try:
            idinfo = id_token.verify_oauth2_token(
                body['idToken'],
                requests.Request()) if not app.config['TESTING'] else {
                    'email': body['idToken']
                }
            email = idinfo['email']
            user = User.objects(email=email)
            if not user:
                username = email.split('@')[0]
                username = "******" + username
                photo = body['photoURL'] if 'photoURL' in body else None
                user = User(email=email,
                            profile_pic=photo,
                            username=username,
                            provider="Google").save()
            else:
                user = user[0]
                if user.is_blocked:
                    return error_response(401, "User is blocked")

            token = jwt.encode(
                {
                    'email': user.email,
                    'exp':
                    datetime.datetime.utcnow() + datetime.timedelta(days=7)
                },
                app.config['SECRET_KEY'],
                algorithm=ENCODING_ALGORITHM)
            return jsonify({
                'token': token.decode('UTF-8'),
                "user": user.serialize()
            })
        except ValueError as err:
            return error_response(401,
                                  'Cant verify Google credentials ' + str(err))
コード例 #20
0
ファイル: user.py プロジェクト: luigidarco96/PyServer
 def put(self):
     """
     Update the information of the caller user
     """
     user = User.find_by_username(get_jwt_identity()['username'])
     new_user = request.get_json()
     user.full_name = new_user['full_name']
     user.date_of_birth = new_user['date_of_birth']
     user.gender = new_user['gender']
     user.update()
     return custom_response(200, "Your information was updated",
                            user.to_dict())
コード例 #21
0
ファイル: target.py プロジェクト: saltedfist/flag_IT
    def change_target(cls, target_id: int, uid: int):

        target = DB.session.query(cls).filter(cls.target_id == target_id, cls.status == 0).one_or_none()
        if target.id != uid:
            return False
        challenge_gold = target.challenge_gold
        gold_type = target.gold_type
        target_id = target.id
        if target.insist_day + 1 >= target.number_of_days:
            target.status = 1
            target.end_time = timemac.today()
            DB.session.commit()
            # 挑战成功: 缺少给用户加金币,或者退还钱逻辑. 还需要在user表中 对积分或者rmb 进行修改.
            user = User.get_user_by_id(uid)
            user.update_time = timemac.today()
            if gold_type == 1: #1:金额   2:积分 待rmb与积分表建完,再完善逻辑.
                user.money = user.money + challenge_gold
                DB.session.commit()
                temp = {
                    'uid': user.id,
                    'money': user.money,
                    'type': 1,
                    'status': 1,
                    'target_id': target_id,
                    'create_time': timemac.today(),
                    'source_info': 1
                }
                add_status = Money_Detail.add_money_detail(temp)
                if add_status is False:
                    return False
                return True
            elif gold_type == 2:
                user.money = user.integral + target.challenge_gold
                DB.session.commit()
                temp = {
                    'uid': user.id,
                    'money': user.money,
                    'type': 1,
                    'status': 1,
                    'target_id': target_id,
                    'create_time': timemac.today(),
                    'source_info': 1
                }
                add_status = Integral_Detail.add_integral_detail(temp)
                if add_status is False:
                    return False
                return True
            else:
                return False
        else:
            target.insist_day = target.insist_day + 1
        DB.session.commint()
        return True
コード例 #22
0
ファイル: activity.py プロジェクト: luigidarco96/PyServer
 def post(self):
     """
     Add a new activity for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     activity = request.get_json()
     new_activity = Activity(name=activity['name'],
                             datetime=activity['datetime'],
                             duration=activity['duration'],
                             user=current_user)
     new_activity.save()
     return custom_response(200, "Activity added", new_activity.id)
コード例 #23
0
 def get(self):
     """
     Return all the calories for the caller user
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     calories = Calorie.query.with_parent(current_user).all()
     calories = list_to_array(calories)
     return custom_response(
         200,
         "Your calories",
         calories
     )
コード例 #24
0
ファイル: image.py プロジェクト: luigidarco96/PyServer
    def get(self, user, image):
        """
        Return the image requested
        """
        current_user = User.find_by_username(get_jwt_identity()['username'])

        if current_user.id != user:
            return custom_response(401, "Permission denied")

        current_dir = "{}{}".format(image_save_path, user)

        return send_from_directory(current_dir, image)
コード例 #25
0
def createUser():
    try:
        data = request.form
        for key in getModelKeys(User):
            if not key in data:
                raise AssertionError(f'Property {key} is missing')

        user = User(email=data['email'])
        user.setPassword(data['password'])
        session.add(user)

        session.commit()
        session.refresh(user)

        return jsonify(user=JSONEncoder(user)), 201

    except AssertionError as err:
        return jsonify({"message": str(err)}), 400

    except Exception as err:
        print(err)
        return jsonify({"message": str(err)}), 500
コード例 #26
0
ファイル: activity.py プロジェクト: luigidarco96/PyServer
    def delete(self, id):
        """
        Delete an activity by its id
        """
        current_user = User.find_by_username(get_jwt_identity()['username'])
        activity = Activity.query.with_parent(current_user).filter_by(
            id=id).first()

        if activity is None:
            return custom_response(404,
                                   "Activity with id {} not found".format(id))

        activity.delete()
        return custom_response(200, "Activity {} deleted".format(id))
コード例 #27
0
def account_login():
    if request.method == 'POST':
        json_info = request.json
        email = json_info.get('email')
        password = json_info.get("password")
        if not email or not password:
            return jsonify({"error": 1, "msg": "用户名或密码为空"})

        if type(User.check(email, password)) is str:
            return jsonify({"error": 1, "msg": "用户名或密码错误"})
        else:
            user = User.get_user_by_email(email)
            if user.status == 0 or user.status == '0':
                return jsonify({"error": 2, "msg": "该用户未激活,请联系管理员"})
            from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
            s = Serializer(b'flag_nb_no_1')
            token = s.dumps({'id': str(user.id)})
            redis_client.set(token, user.id, ex=24 * 3600)
            return jsonify({
                "error": 0,
                "msg": "登陆成功",
                "token": str(token, 'utf-8')
            })
コード例 #28
0
ファイル: auth.py プロジェクト: luigidarco96/PyServer
 def post(self):
     """
     Refresh token
     """
     current_user = User.find_by_username(get_jwt_identity()['username'])
     tmp_user = current_user.to_dict()
     tmp_user.update({
         'access_token':
         create_access_token(create_identity(current_user),
                             expires_delta=False),
         'refresh_token':
         create_refresh_token(create_identity(current_user))
     })
     return custom_response(200, 'Access token refreshed', tmp_user)
コード例 #29
0
ファイル: sign.py プロジェクト: saltedfist/flag_IT
def sign_add():
    error = Error(0, '签到成功')
    token = request.headers.get("Access-Token")
    if not token:
        error.err_code = 9
        error.err_msg = "token is None"
        return error.make_json_response()
    uid = verify_token(token)
    if uid is None:
        error.err_code = 9
        error.err_msg = "token error"
        return error.make_json_response()
    user = User.get_user_by_id(uid)
    if user is None:
        error.err_code = 9
        error.err_msg = "登陆时间已过期,请重启登陆"
        return error.make_json_response()
    json_data = request.json
    target_name = json_data.get('target_name') if json_data.get('target_name') else None
    target_id = json_data.get('target_id')
    content = json_data.get('content') if json_data.get('content') else None
    img = request.files.get('img')
    insist_day = json_data.get('insist_day') if json_data.get('insist_day') else 0
    status = json_data.get('status') if json_data.get('status') else 1
    if not all([target_id, img]):
        error.err_code = 9
        error.err_msg = "提交数据缺失,请确认后重新提交."
        return error.make_json_response()
    target = Target_Info.change_target(target_id, uid)
    if target is False:
        error.err_code = 9
        error.err_msg = '提交参数错误!,请确认后重新提交!'
        return error.make_json_response()

    sign_data = {
        'target_name': target_name,
        'target_id': target_id,
        'content': content,
        'img': img,
        'insist_day': insist_day,
        'status': status,
        'uid': uid
    }
    add_status = Sign.add(sign_data)

    if add_status is True:
        return error.make_json_response()
    error.err_code = 9
    error.err_msg = '签到失败,请重新提交!'
    return error.make_json_response()
コード例 #30
0
ファイル: auth.py プロジェクト: luigidarco96/PyServer
    def post(self):
        """
        Create new user session
        """
        body = request.get_json()
        user = User.find_by_username(body['username'])
        if not user:
            return custom_response(
                401, 'User {} doesn\'t exist'.format(body['username']))

        if User.verify_hash(body['password'], user.password):
            tmp_user = user.to_dict()
            tmp_user.update({
                'access_token':
                create_access_token(create_identity(user),
                                    expires_delta=False),
                'refresh_token':
                create_refresh_token(create_identity(user))
            })
            return custom_response(200,
                                   'Logged in as {}'.format(user.username),
                                   tmp_user)
        else:
            return custom_response(401, 'Username or password wrong')