示例#1
0
    def user_profile(user_info, user_id):
        if request.method == 'GET':
            requester_id = int(user_info["id"])
            app.logger.debug(
                "/users/%s || Requesting AuthServer for user profile", user_id)
            response = users_service.getUserProfile(user_id)
            if response.status_code != 200 or requester_id == user_id:
                return response

            profile_data = json.loads(response.get_data())
            profile_data[
                'friendship_status'] = users_service.getFriendshipStatus(
                    requester_id, user_id)
            return success_response(200, profile_data)
        if request.method == 'PUT':
            requester_id = int(user_info["id"])
            if requester_id != user_id:
                return error_response(403, 'Forbidden')
            return users_service.editUserProfile(user_id, request.get_json())
        if request.method == 'DELETE':
            if user_info != {} and not app.config[
                    'TESTING']:  #It is only allowed to the webadmin to use
                return error_response(403, 'Forbidden')

            # Delete videos
            video_service.removeLikesFromUser(user_id)
            video_service.deleteCommentsFromUser(user_id)
            response = video_service.deleteVideos(user_id)
            return response if response.status_code != 204 else users_service.deleteUserProfile(
                user_id)
示例#2
0
    def change_password(self, request, code, email):
        if not 'password' in request:
            return error_response(400, 'Missing fields')

        if not email in self.db or self.db[email]['code'] != code:
            return error_response(401, 'Invalid code or email')

        save_password(get_hash(request['password']), email, self.db)
        return flask.Response('Password changed', status=204)
示例#3
0
    def login(self, data):
        email = data['email']
        password = data['password']
        if email not in self.db:
            return error_response(401, 'Wrong credentials')
        if not check_password_hash(password, self.db[email]['password']):
            return error_response(401, 'Wrong credentials')

        user = self.db[email]
        response_data = {'token': get_token(email), 'user': get_fields(user)}
        return success_response(200, response_data)
示例#4
0
 def get_video(user_info, video_id):
     requester_id = int(user_info["id"])
     video, err = video_service.getVideo(requester_id, video_id)
     if err:
         return err
     if request.method == 'GET':
         return success_response(200, video)
     elif request.method == 'PATCH':
         if requester_id != video['user_id']:
             return error_response(403, 'Forbidden')
         return video_service.editVideo(video_id, request.get_json())
     elif request.method == 'DELETE':
         if requester_id != video['user_id']:
             return error_response(403, 'Forbidden')
         return video_service.deleteVideo(video_id)
示例#5
0
 def send_mail(self, request):
     if not 'email' in request:
         return error_response(400, 'Missing fields')
     email = request['email']
     if email in self.db:
         generate_code(email, self.db)
     return flask.Response('Email sent', status=200)
 def decorated(*args, **kwargs):
     if request.method in involved_methods:
         body = request.get_json()
         if not body or any(field not in body for field in required_fields):
             app.logger.debug("[%s] Failed because %s ==> %s", f.__name__, msg, body)
             return error_response(400, msg)
     return f(*args, **kwargs)
示例#7
0
    def user_friend_request(user_info, user_id):
        app.logger.debug(
            "/users/%s/friend_request || Requesting AuthServer for user profile",
            user_id)
        response = users_service.getUserProfile(user_id)
        if response.status_code != 200:
            return error_response(
                404, "Can't send friend request to inexistent user")

        err = users_service.sendFriendRequest(int(user_info['id']), user_id)
        if err:
            return error_response(400, err)

        notification_service.newFriendRequest(user_info, response.get_json())
        return success_response(
            200, {"message": "Friendship request sent successfully"})
示例#8
0
 def authorize_user(self, token):
     email = get_email(token)
     if email not in self.db:
         return error_response(401, 'Invalid Token')
     user = self.db[email]
     response_data = {'user': get_fields(user)}
     return success_response(200, response_data)
示例#9
0
    def edit_video(self, video_id, data):
        if any(elemen in data for elemen in ['id', 'author', 'user_id', 'url', 'date']):
            return error_response(400, 'Invalid values')

        if not validate_visibility(data['visibility']):
            return error_response(400, 'Invalid visibility')

        if not video_id in self.db:
            return error_response(404, 'Video not found')
        
        video = self.db[video_id]
        for k,v in data.items():
            if k in video:
                video[k] = v
        
        return success_response(200, get_fields(video_id, video))
示例#10
0
    def addLikeToVideo(self, user_id, video_id, has_liked):
        likes = self.db_handler.change_user_like_on_video(
            video_id, user_id, has_liked)
        if likes is None:
            return error_response(404, 'Video not found')

        return None
示例#11
0
    def delete_user_profile(self, user_id):
        if not any(int(user['id']) == user_id for user in self.db.values()):
            return error_response(404, 'User not found')

        self.db = {
            email: user
            for email, user in self.db.items() if int(user['id']) != user_id
        }
        return flask.Response('', status=204)
示例#12
0
    def addCommentToVideo(self, user_id, video_id, fields):
        comment = self.db_handler.add_video_comment(video_id, user_id, fields)
        if comment is None:
            return None, error_response(404, 'Video not found')

        result = comment.to_mongo().to_dict()
        result['comment_id'] = result['_id']
        del result['_id']
        return result, None
示例#13
0
 def user_videos(user_info, user_id):
     requester_id = int(user_info["id"])
     if request.method == 'POST':
         if requester_id != user_id:
             return error_response(403, 'Forbidden')
         return video_service.addNewVideo(user_id, request.get_json())
     else:
         are_friends = (requester_id == user_id) or (users_service.getFriendshipStatus(requester_id, user_id) == 'friends')
         return video_service.listVideosFromUser(user_id, are_friends)
示例#14
0
 def register(self, data):
     email = data["email"]
     username = data['username']
     password = data['password']
     hashed_password = get_hash(password)
     if email in self.db or any(user['username'] == username
                                for user in self.db.values()):
         return error_response(409, 'User already registered')
     if not validate(email):
         return error_response(400, 'Invalid email address')
     id = self.generate_id()
     self.db[email] = {
         'id': id,
         'email': email,
         'password': hashed_password,
         'username': username,
         'profile': {}
     }
     response_data = {'id': id}
     return success_response(200, response_data)
示例#15
0
    def register():
        body = request.get_json()
        if 'username' not in body or 'password' not in body or 'email' not in body:
            return error_response(400, 'Fields are incomplete')

        auth_server = app.config['AUTH_SERVER']
        app.logger.debug("/register || Sending request to AuthServer %s ",
                         str(body))
        response = auth_server.register(body)
        app.logger.debug("/register || Auth Server response %d %s ",
                         response.status_code, response.data)
        return response
示例#16
0
    def oauth_login():
        body = request.get_json()
        if 'idToken' not in body:
            return error_response(400, 'Oauth data is missing')

        auth_server = app.config['AUTH_SERVER']
        app.logger.debug("/oauth2login || Sending request to AuthServer %s ",
                         str(body))
        response = auth_server.oauth_login(body)
        app.logger.debug("/oauth2login || Auth Server response %d %s ",
                         response.status_code, response.data)
        return response
示例#17
0
    def login():
        body = request.get_json()
        if 'email' not in body or 'password' not in body:
            return error_response(400, 'Email or password is missing')

        auth_server = app.config['AUTH_SERVER']
        app.logger.debug("/login || Sending request to AuthServer %s ",
                         str(body))
        response = auth_server.login(body)
        app.logger.debug("/login || Auth Server response %d %s ",
                         response.status_code, response.data)
        return response
示例#18
0
    def add_video(self, data):
        url = data['url']
        author = data['author']
        title = data['title']
        visibility = data['visibility']
        user_id = data['user_id']
        description = data['description'] if 'description' in data else ''
        thumb = data['thumb'] if 'thumb' in data else ''
 
        if any(video['url'] == url for video in self.db.values()):
            return error_response(409, 'Video already uploaded')

        date = datetime.strptime(data['date'], '%m/%d/%y %H:%M:%S')
        if date > datetime.now():
            return error_response(400, 'Invalid date')
        if not validate_visibility(data['visibility']):
            return error_response(400, 'Invalid visibility')

        id = self.generate_id()
        self.db[id] = {'author': author, 'title': title, 'description': description, 'date': date, 'visibility': visibility, 
        'url': url, 'thumb': thumb, 'user_id': user_id}
        response_data = {'id': id}
        return success_response(201, response_data)
示例#19
0
    def user_friends(user_info, user_id):
        if request.method == 'POST':
            response = users_service.getUserProfile(user_id)
            if response.status_code != 200:
                return error_response(404, "Can't befriend inexistent user")

            err = users_service.acceptFriendRequest(int(user_info["id"]),
                                                    user_id)
            if err:
                return error_response(400, err)

            notification_service.friendRequestAccepted(user_info,
                                                       response.get_json())
            return success_response(
                200, {"message": "Friend accepted successfully"})
        else:
            friends_ids = users_service.getFriends(user_id)
            app.logger.debug(
                "/users/%d/friends || %d user profiles to fetch from Auth Server",
                user_id, len(friends_ids))
            response_data = users_service.fetchUsersNames(friends_ids)
            app.logger.debug("/users/%d/friends || Fetched %d user profiles",
                             user_id, len(response_data))
            return success_response(200, response_data)
示例#20
0
    def getCommentsFromVideo(self, video_id):
        comments = self.db_handler.get_video_comments(video_id)
        if comments is None:
            return None, error_response(404, 'Video not found')

        result = []
        for comment in comments:
            result.append({
                'comment_id': comment.comment_id,
                'user_id': comment.user_id,
                'author': comment.author,
                'content': comment.content,
                'timestamp': comment.timestamp
            })
        result.sort(key=lambda d: datetime.strptime(d['timestamp'],
                                                    '%m/%d/%y %H:%M:%S'))
        return result, None
示例#21
0
 def oauth_login(self, data):
     if not "_" in data["idToken"]:
         return error_response(400, "Cant verify google credentials")
     email = data["idToken"].split("_")[1]
     if email not in self.db:
         id = self.generate_id()
         username = email.split('@')[0]
         username = "******" + username
         self.db[email] = {
             'id': id,
             'email': email,
             'username': username,
             'profile': {}
         }
     user = self.db[email]
     response_data = {'token': get_token(email), 'user': get_fields(user)}
     return success_response(200, response_data)
示例#22
0
 def delete_video(self, video_id):        
     if not video_id in self.db:
         return error_response(404, 'Video not found')
             
     self.db = {id:video for id, video in self.db.items() if id != video_id}
     return flask.Response('', status=204)
示例#23
0
 def get_video(self, video_id):
     if not video_id in self.db:
         return error_response(404, 'Video not found')
     video = self.db[video_id]
     response_data = get_fields(video_id, video)
     return success_response(200, response_data)
示例#24
0
 def get_user_profile(self, user_id_request):
     for v in self.db.values():
         if v['id'] == str(user_id_request):
             return success_response(200, get_fields(v))
     return error_response(404, "User not found")
示例#25
0
 def edit_user_profile(self, user_id, body):
     for v in self.db.values():
         if v['id'] == str(user_id):
             v['profile'] = body
             return success_response(200, get_fields(v))
     return error_response(404, "User not found")
示例#26
0
 def validate_code(self, code, email):
     if not email in self.db or self.db[email]['code'] != code:
         return error_response(401, 'Invalid code or email')
     return flask.Response('Valid code', status=200)