示例#1
0
def get_user_by_username(username: str) -> UserModel:
    user = None
    # 邮箱登录
    if '@' in username:
        if not validate_email(username):
            raise InvalidParam
        user = UserModel.objects(email=username).first()
    # 手机号登录
    else:
        if not validate_phone(username):
            raise InvalidParam
        user = UserModel.objects(phone=username).first()
    return user
示例#2
0
    def on_get(self, req, resp):
        email = req.media['email']
        password = req.media['password']
        # Cannot use UserModel.objects(email = email).get here because get will raise an error if the user doesn't exist
        user = UserModel.objects(email=email)
        if not user:
            resp.status = falcon.HTTP_400
            resp.body = "Email or password is incorrent!"
            return

        user = user.get()
        if bcrypt.checkpw(password.encode('utf8'),
                          user.password.encode('utf8')):
            jwtToken = jwt.encode({
                'id': str(user.id)
            },
                                  JWT_SECRET,
                                  algorithm='HS256').decode('utf-8')

            resp.status = falcon.HTTP_200
            resp.body = json.dumps({
                'jwtToken': jwtToken,
                'message': "Logged in successfully!"
            })
        else:
            resp.status = falcon.HTTP_400
            resp.body = "Email or password is incorrent!"
示例#3
0
    def post(self, gameKey: int) -> Response:
        payload: dict = request.json
        game: GameModel = GameModel.objects(game_key=gameKey).first()
        if not game:
            return Response('', 204)

        user: UserModel = UserModel.objects(user_id=payload['id'],
                                            game=game).first()
        if user:
            if check_password_hash(user.password, payload['password']):
                return jsonify({
                    'accessToken':
                    create_access_token(payload['id'],
                                        expires_delta=timedelta(days=10))
                })

            else:
                return Response('', 205)

        default_team: TeamModel = TeamModel.objects(game=game,
                                                    team_id=0).first()
        UserModel(game, payload['id'], payload['email'],
                  generate_password_hash(payload['password']),
                  default_team).save()
        return jsonify({
            'accessToken':
            create_access_token(payload['id'],
                                expires_delta=timedelta(days=10))
        })
示例#4
0
    def delete(self, postId):
        user = UserModel.objects(id=get_jwt_identity()).first()
        post = PostModel.objects(postId=postId).first()

        if not post:
            return Response('', 204)
        if user != post.author: abort(403)
        post.delete()

        return Response('', 201)
示例#5
0
    def post(self):
        payload = request.json

        for key in ['id', 'password']:
            if key not in payload:
                abort(400)

        if UserModel.objects(id=payload['id'], pw=payload['password']).first():
            return jsonify({"accessTocken": create_access_token(identity=payload['id'], expires_delta=timedelta(days=1))})

        abort(401)
示例#6
0
    def get(self) -> Response:
        team_objects: List[TeamModel] = TeamModel.objects(game=g.game)
        result = {'teamCount': len(team_objects)}

        for team in team_objects:
            result[str(team.team_id)] = {
                'member': [user.user_id for user in UserModel.objects(team=team)],
                'teamColor': team.team_color
            }

        return jsonify(result)
示例#7
0
    def wrapper(*arg, **kwargs):
        jwt = get_jwt_claims()

        g.game: GameModel = GameModel.objects(game_key=jwt['game_key']).first()
        if not g.game:
            abort(403)

        g.user: UserModel = UserModel.objects(user_id=jwt['user_id'],
                                              game=g.game).first()
        if not g.user:
            abort(403)
        return fn(*arg, **kwargs)
示例#8
0
    def post(self):

        payload = request.json
        for key in ['id', 'password']:
            if key not in payload:
                abort(400)

        if UserModel.objects(id=payload['id']).first():
            return Response('', 204)

        UserModel(id=payload['id'], pw=payload['password']).save()
        return Response('', 201)
    def delete(self, id):
        user = UserModel.objects(id=get_jwt_identity()).first()
        comment = CommentModel.objects(commentId=id).first()

        if not comment:
            return Response('', 204)
        if user != comment.author:
            abort(403)

        comment.delete()

        return Response('', 201)
示例#10
0
    def post(self, postId):
        user = UserModel.objects(id=get_jwt_identity()).first()

        payload = request.json

        for key in ['title', 'content']:
            if key not in payload:
                abort(400)

        PostModel(str(ObjectId()), user, payload['title'],
                  payload['content']).save()

        return Response('', 201)
示例#11
0
    def post(self, id):
        user = UserModel.objects(id=get_jwt_identity()).first()
        post = PostModel.objects(postId=id).first()
        payload = request.json

        for key in ['content']:
            if key not in payload:
                abort(400)

        if not post:
            return Response('', 204)
        comment_id = str(ObjectId())
        CommentModel(comment_id, post, user, payload['content']).save()

        return Response('', 201)
示例#12
0
    def post(self) -> Response:
        if not g.user:
            abort(403)

        if g.user.team.team_id != 0:
            return Response('', 204)

        team: TeamModel = TeamModel.objects(team_id=int(request.args.get('team'))).first()
        if (not team) or len(UserModel.objects(team=team)) > 5:
            return Response('', 205)

        g.user.team = team
        g.user.save()

        return Response('', 201)
示例#13
0
    def _create_user_and_access_token(self,
                                      game_key=100000,
                                      id_='test',
                                      password='******',
                                      email='*****@*****.**'):
        rv = self.client.post('/auth/' + str(game_key),
                              data=dumps(
                                  dict(id=id_, password=password,
                                       email=email)),
                              content_type='application/json')
        token = loads(rv.data, encoding='utf-8')['accessToken']

        test_user = UserModel.objects(game=self.test_game, user_id=id_).first()

        return test_user, f'Bearer {token}'
示例#14
0
    def patch(self, id):
        user = UserModel.objects(id=get_jwt_identity()).first()
        comment = CommentModel.objects(commentId=id).first()
        payload = request.json

        for key in ['content']:
            if key not in payload:
                abort(400)

        if not comment:
            return Response('', 204)
        if user != comment.author: abort(403)

        comment.content = payload['content']
        comment.save()

        return Response('', 201)
示例#15
0
    def on_post(self, req, resp):
        email = req.media['email']
        password = req.media['password']

        if not password:
            resp.status = falcon.HTTP_400
            resp.body = "Password cannot be emptied!"

        if not UserModel.objects(email=email):
            hashPassword = bcrypt.hashpw(bytes(password, encoding='utf-8'),
                                         bcrypt.gensalt())
            newUser = UserModel(email=email, password=hashPassword)
            newUser.save()
            resp.status = falcon.HTTP_201
            resp.body = "Your account has been created!"
        else:
            resp.status = falcon.HTTP_400
            resp.body = "The email has been used!"
示例#16
0
    def patch(self, postId):
        user = UserModel.objects(id=get_jwt_identity()).first()
        post = PostModel.objects(postId=postId).first()

        if not post:
            return Response('', 204)
        if user != post.author:
            abort(403)

        payload = request.json

        for key in ['title', 'content']:
            if key not in payload:
                abort(400)

        post.title = payload['title']
        post.content = payload['content']
        post.save()

        return Response('', 201)
 def check_user_team(self, user_id='test', team_number=0):
     user = UserModel.objects(user_id=user_id).first()
     self.assertEqual(user.team.team_id, team_number)
示例#18
0
def add_claims(user_id):
    return {
        'user_id': user_id,
        'game_key': UserModel.objects(user_id=user_id).first().game.game_key
    }