Ejemplo n.º 1
0
    def post(self):

        args = parser.parse(signup_args, request)
        if User.objects(username=args['email']):
            return api_abort(422, "Eamil已注册")
        elif User.objects(username=args['username']):
            return api_abort(422, "用户名已存在")
        try:
            u = User(
                email=args["email"].lower(),
                username=args["username"],
                # TODO: nginx
                avatar='http://192.168.1.106:8000/avatar/r{0}.png'.format(
                    random.randint(1, 10)))
            u.set_password(args["password"])
            u.save()
            if os.getenv('FLASK_ENV') == 'development':
                # 发送 email
                uid = User.objects(email=args['email']).first().id
                send_confirm_email(args['email'], args['username'],
                                   generate_token(uid))
            return '', 201
        except Exception as e:
            current_app.logger.error(e)
            return api_abort(500)
Ejemplo n.º 2
0
 def delete(self, post_id):
     '''删除文章'''
     try:
         p = Post.objects(id=post_id)
         if p is None: return api_abort(404)
         p.delete()
     except Exception as e:
         current_app.logger.errors(e)
         return api_abort(404)
     return '', 204
Ejemplo n.º 3
0
    def get(self):
        '''
            variable r   
            Success:
              {'access_token': '374171064616b9c53adb9149c356954ec3bf4199', 'token_type': 'bearer', 'scope': ''}
            Exception:
              {'error': 'bad_verification_code', 'error_description': 'The code passed is incorrect or expired.', 'error_uri': 'https://developer.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#bad-verification-code'}
        '''
        code = request.args.get('code', '')
        if code == '':
            return api_abort(403, 'Access denied, please try again.')
        try:
            request_assess_token_url = f'https://github.com/login/oauth/access_token?client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&code={code}'
            request_assess_token_headers = {'accept': 'application/json'}
            print(request_assess_token_url)
            r = requests.post(request_assess_token_url,
                              headers=request_assess_token_headers).json()
            print(r)
        except Exception as e:
            current_app.logger.error(e)
            return api_abort(500, 'Requests Github Access Token Error')
        current_app.logger.info(f'request github access_token: {r}')
        if not r.get('access_token', None):
            return api_abort(401, 'The code passed is incorrect or expired.')

        request_user_info_url = 'https://api.github.com/user'
        request_user_info_headers = {
            'accept': 'application/json',
            'Authorization': 'token ' + r['access_token']
        }
        try:
            user_info = requests.get(request_user_info_url,
                                     headers=request_user_info_headers).json()
            current_app.logger.info(f'requests github user_info: {user_info}')
            # return user_info
        except Exception as e:
            current_app.logger.error(e)
            return api_abort(400)

        username = user_info.get('login')
        # current_app.logger.info(u)
        u = User.objects(username=username).first()
        if u:
            return generate_token(u.id)
        else:
            user = User(username=username,
                        email=user_info.get('email', ''),
                        avatar=user_info.get('avatar_url', ''))
            user.save()
            uid = User.objects(username=username).first()
            current_app.logger.info(uid)

            return generate_token(uid)
Ejemplo n.º 4
0
 def get(self, post_id):
     '''根据id返回文章内容'''
     try:
         post = Post.query_post_by_id(id=post_id)
         return post
     except Exception as e:
         current_app.logger.error(e)
         return api_abort(404)
Ejemplo n.º 5
0
    def post(self):

        args = parser.parse(login_args, request)

        email = args['email'].lower()
        password = args['password']
        try:
            u = User.objects(email=email).first()
            if not u:
                return api_abort(401, 'Email not exist')
            current_app.logger.info(
                f'args: {args}\nuid: {str(u.id)}\nusername: {u.username}')
            if not u.validate_password(password):
                return api_abort(401, 'Password Unauthorized')
            return generate_token(str(u.id))
        except Exception as e:
            current_app.logger.error(e)
            return api_abort(500)
Ejemplo n.º 6
0
    def get(self, token):
        if not validate_token(token):
            return api_abort(401)
        u = User.objects(id=g.uid).first()
        u.add_permission(
            [Permission.COMMENT, Permission.ASK, Permission.DELETE])
        u.save()

        return {'confirm_email': True}
Ejemplo n.º 7
0
 def get(self):
     nickname = request.args.get('nickname')
     if nickname is None:
         return api_abort(400, "param nickname missing")
     user = User.query.filter_by(nickname=nickname).first()
     if user is None:
         exit_status = 0
     else:
         exit_status = 1
     return {"status": int(exit_status)}
Ejemplo n.º 8
0
 def get(self):
     tel = request.args.get('tel')
     if tel is None:
         return api_abort(400, "param tel missing")
     user = User.query.filter_by(telephone=tel).first()
     if user is None:
         exit_status = 0
     else:
         exit_status = 1
     return {"status": int(exit_status)}
Ejemplo n.º 9
0
        def wrapper(*args, **kwargs):

            token_type, token = get_token()

            if request.method != "OPTIONS":
                if token is None:
                    return api_abort(400, 'token missing')
                if token_type is None or token_type.lower() != "bearer":
                    return api_abort(400, "The token type must be bearer.")

                result = validate_token(token)

                if not result:
                    return api_abort(401, "admin 错误")
                # g.uid = result.get('msg')
                u = User.objects(id=g.uid).first().has_permission(perm)
                if not u:
                    return api_abort(401, '莫得权限')

            return f(*args, **kwargs)
Ejemplo n.º 10
0
    def decorator(*args, **kws):
        r = redis.Redis(connection_pool=pool)
        token = request.headers.get('Authorization', None)
        if token is None:
            return api_abort(403, 'token missing')
        try:
            access_token = token.split(';')[0]
            refresh_token = token.split(';')[1]
        except IndexError:
            access_token = token.split(';')[0]
            refresh_token = ""

        if r.sismember(key_access_token, access_token):
            user = load_user(access_token)
            if user is None:
                return api_abort(403, 'bad token')
            g.current_user = user
            return f(*args, **kws)

        if r.sismember(key_refresh_token, refresh_token):
            user = load_user(refresh_token)
            if user is None:
                return api_abort(403, 'bad token')

            r.srem(key_refresh_token, refresh_token)
            access_token = generate_token(user, 'access', access_token_expires)
            refresh_token = generate_token(user, 'refresh',
                                           refresh_token_expires)
            token_info = {
                "access_token": access_token,
                "refresh_token": refresh_token,
                "expires_access": access_token_expires,
                "expires_refresh": refresh_token_expires
            }

            g.current_user = user
            resp = f(*args, **kws)
            resp['token'] = token_info
            return resp

        return api_abort(403, 'bad token')
Ejemplo n.º 11
0
    def post(self):
        '''提交评论
        Args:
            content: 
            post_id: 5db17a4f14fc6a9a236c8d63
            reply_id: 5db17a4f14fc6a9a236c8d63 or None
        '''
        args = parser.parse(comment_args, request)
        author = User.objects(id=g.uid).first()
        post = Post.objects(id=args['post_id']).first()

        if not post: return api_abort(404)
        try:
            c = Comment(author=author,
                        content=args['content'],
                        reply=args.get('reply_id', '') or args['post_id'])
            post.comments.append(c)
            post.save()
            return '', 201
        except Exception as e:
            current_app.logger.error(e)
            return api_abort(500)
Ejemplo n.º 12
0
 def put(self, post_id):
     '''更新文章 TODO:'''
     data = request.get_json()
     print(data)
     try:
         # data = parser.parse(post_args, request)
         p = Post(id=post_id)
         Post.objects(id=post_id).update_one(set__title=data['title'])
         p.reload()
         return ''
     except Exception as e:
         current_app.logger.error(e)
         return api_abort(500)
Ejemplo n.º 13
0
def generate_token(user_id, t="login"):
    user_id = str(user_id)
    expires_in = 3600 * 24 * 30
    if t == 'confirm': expires_in = 3600 * 3
    elif t == 'reset': expires_in = 3600
    try:
        data = {"user_id": user_id}
        s = Serializer(SECRET_KEY, expires_in=expires_in)
        token = s.dumps(data).decode('ascii')
        current_app.logger.info(f'user_id: {user_id}\n token:{token}')
        return token
    except Exception as e:
        current_app.logger.error(e)
        return api_abort(500)
Ejemplo n.º 14
0
 def post(self):
     '''新建文章'''
     data = parser.parse(post_args, request)
     try:
         p = Post(
             title=data['title'],
             content=data['content'],
             category=data['category'],
             tags=data['tags'],
         )
         p.save()
     except Exception as e:
         current_app.logger.error(e)
         return api_abort(500)
     return '', 201
Ejemplo n.º 15
0
    def get(self):
        token = request.headers.get('Authorization', None)
        if token is None:
            return api_abort(403, 'token missing')
        try:
            access_token = token.split(';')[0]
            refresh_token = token.split(';')[1]
        except IndexError:
            access_token = token.split(';')[0]
            refresh_token = ""

        if r.sismember("token:access", access_token):
            return make_resp("", message="OK")
        else:
            return make_resp("", message="Bad Token")
Ejemplo n.º 16
0
 def decorator(*args, **kws):
     resource_name_module_map = {
         "user": User,
         "course": Course,
         "task": Task,
         "discussion": Discussion,
         "chapter": Chapter,
         "problem": Problem,
         "task_answer": TaskAnswer,
         "comment": Comment,
         "notice": Notice,
         "media": Media
     }
     module = resource_name_module_map[resource_name]
     resource_id = find_resource_id(module.id_name)
     if resource_id is None:
         return api_abort(400,
                          "{} id is required".format(resource_name))
     resource = module.query.get(resource_id)
     if resource is None:
         return api_abort(404,
                          "resource {} not found".format(resource_name))
     setattr(g, "current_" + resource_name, resource)
     return f(*args, **kws)
Ejemplo n.º 17
0
    def delete(self, comment_id):
        '''删除评论'''

        # step1. 根据 cid 查询评论作者的 id
        # step2. 判断 g.uid 是否等于作者 id
        # step2.1. 等于则执行删除操作
        # step2.2. 否则返回 422
        # author = User.objects(id=g.uid).first()

        args = parser.parse(delete_comment_args, request)
        post_id = args['post_id']

        try:
            comment_author_id = Post.objects.get(id=post_id).comments.filter(
                cid=comment_id).first().author.id
        except Exception as e:
            current_app.logger.error(e)
            return api_abort(404)
        current_app.logger.info(f'{comment_author_id}, {g.uid}')
        if str(comment_author_id) == g.uid:
            Post.objects(id=post_id).update_one(pull__comments__cid=comment_id)
            return '', 204
        else:
            return api_abort(403)
Ejemplo n.º 18
0
 def get(self):
     '''返回文章集合'''
     # print(post.find_all())
     try:
         data = json.loads(Post.objects.all().only('id', 'title',
                                                   'category',
                                                   'tags').to_json())
         if not data: raise Exception('post not found')
         for i in data:
             i['id'] = i['_id']['$oid']
             del i['_id']
         current_app.logger.info(data)
         return {"posts": data}
     except Exception as e:
         current_app.logger.error(e)
         return api_abort(404)
Ejemplo n.º 19
0
    def get(self, user_id):

        token_type, token = get_token()
        u = User.objects(id=user_id).first()
        if not u: return api_abort(404)
        user_info = {
            'id': str(u.id),
            'username': u.username,
            'avatar': u.avatar,
            'followed': u.followed,
            'follower': u.follower,
            'question': u.question,
        }
        if token != None and validate_token(token) and g.uid == user_id:
            user_info['emali'] = u.email
            return user_info
        else:
            return user_info
Ejemplo n.º 20
0
    def post(self):
        reqparser = [pwd_login_reqparser, tel_login_reqparser]
        auth_user_funcs = [auth_user_by_pwd, auth_user_by_phone]

        data = login_reqparser.parse_args()
        method = data['method']

        data = reqparser[int(method)].parse_args()
        user, message = auth_user_funcs[int(method)](data)
        g.current_user = user

        if message is not 'succeed' or user is None:
            return api_abort(401, message)

        access_token = generate_token(user, 'access', 3600 * 24 * 7)
        refresh_token = generate_token(user, 'refresh', 3600 * 24 * 30)

        return make_resp({
            'user_info': user.to_json(detail=True),
            'access_token': access_token,
            'refresh_token': refresh_token,
            'access_expires': 3600 * 24 * 7,
            'refresh_expires': 3600 * 24 * 30
        })
Ejemplo n.º 21
0
 def decorator(*args, **kws):
     user = g.current_user
     course = g.current_course
     if user not in course.students and not user.is_teacher(course):
         return api_abort(403, "not the student ot teacher")
     return f(*args, **kws)