Beispiel #1
0
def insert():
    data = request.json
    email = data.get('email')
    document = data.get('document')
    password = data.get('password')
    re_password = data.get('re_password')

    if password and re_password and password != re_password:
        return res_error(200, 'Password and verification required.')

    try:
        User.objects.get(Q(email=email) | Q(document=document))
        return res_error(200, 'Email or document already in use.')
    except User.DoesNotExist:
        pass

    try:
        data.update(friends=[],
                    groups=[],
                    events=[],
                    invites=[],
                    password=security.pbkdf2_hex(password, SALT, 69),
                    created_at=datetime.datetime.utcnow)
        user = User(**dissoc(data, 're_password'))
        user.validate()
        created = user.save().to_mongo().to_dict()
        return res_success(200, {'id': created['_id']})
    except Exception as e:
        print(e)
        return res_error(400, e)
Beispiel #2
0
def before_every_request():
    user_id = request.form.get('user_id', None)
    if not user_id:
        return json_err("user_id missing.")

    # Check if auth should be disabled
    disable_auth = config.DISABLE_AUTH

    # Check if user in session already
    session_expiry = session.get('user_exp', None)
    session_user = session.get('user_id', None)

    if (session_expiry
            and session_expiry <= datetime.now()) or user_id != session_user:
        if disable_auth:
            # user = User.authenticate('abcd')
            # user = User('5f627af0f6939c29ed2e2995')
            auth_resp = User('5f627af0f6939c29ed2e2995')
        else:
            auth_resp = User.authenticate(user_id, 'testing_user')

        if isinstance(auth_resp, tuple):
            # If tuple, it's an error message
            return auth_resp
        else:
            # Else it's a user object
            user = auth_resp

        session['user_exp'] = datetime.now() + timedelta(hours=2)
        session['user_id'] = str(user._id)
Beispiel #3
0
    def test_add(self):
        user = User()
        user.fullname = 'Jon Snow'

        session.add(user)
        session.commit()

        # 如果成功创建用户,id不应该为None
        self.assertIsNotNone(user.id)
        print(user)
Beispiel #4
0
def create_user_league():
    required = ['league_name']
    params = get_required_params(request, required, 'POST')
    if not params:
        return json_err("Missing required parameters.")

    user = User(session['user_id'])

    user_league = user.create_user_league(params['league_name'])

    return user_league.json(), 201
Beispiel #5
0
def profile():
    user = User.get_by_email(session['email'])
    name = user.name
    movieslist = Movie.movieAI(user._id)
    random.shuffle(movieslist)
    m = movieslist[0]
    return render_template("main.html", name=name, m=m)
Beispiel #6
0
    def new_request(self, data):
        """
        create new course watch request, after validation
        :param data:
        :return:
        """

        course = CourseRequest.fromJSON(data['course_request'])
        user = User.fromJSON(data['user'])
        order = data['order']

        try:
            self.request_service.is_valid_request(course)
            self.request_service.add_course_request(course, user)

        except InvalidRequestException as e:
            response = self.response_util.build_error_response(
                code=400, message="Course request not valid: " + e.message)
            logging.warning(e.message)
            return response

        except Exception as e:
            response = self.response_util.build_error_response(
                code=500, message="An Error Occurred: " + e.message)
            logging.error(e.message)
            return response

        response = self.response_util.build_success_response(
            code=200, message="Request Added", data={})
        logging.info(response)
        return response
Beispiel #7
0
 def get_all(self):
     cursor = Connection.open()
     try:
         cursor.execute(f'SELECT * FROM {Constants.User.TABLE}')
         users = []
         for x in cursor.fetchall():
             user = User(x[Constants.User.ID], x[Constants.User.NAME], x[Constants.User.PHONE], x[Constants.User.EMAIL])
             cursor.execute(f'''
                 SELECT * FROM {Constants.Loan.TABLE}
                 LEFT JOIN {Constants.Book.TABLE}
                 ON {Constants.Book.TABLE}.{Constants.Book.ID} = {Constants.Loan.TABLE}.{Constants.Loan.BOOK_ID}
                 WHERE {Constants.Loan.USER_ID} = {user.id}
                 AND {Constants.Loan.DATE_DEVOLUTION} IS null
             ''')
             for y in cursor.fetchall():
                 loan = Loan(
                     y[Constants.Loan.ID],
                     y[Constants.Loan.DATE_LOAN],
                     y[Constants.Loan.DATE_DEVOLUTION]
                 )
                 loan.book = Book(
                     y[Constants.Book.ID],
                     y[Constants.Book.TITLE],
                     y[Constants.Book.PAGES],
                     y[Constants.Book.VALUE_MULCT],
                 )
                 user.loans.append(loan)
             users.append(user)
         return users
     finally:
         Connection.close()
Beispiel #8
0
def insert_user():
    try:
        user = User(0, f'{request.json["name"]} {request.json["surname"]}',
                    request.json['phone'], request.json['email'])
        return service.insert(user)
    except KeyError as e:
        return 'json invalido'
Beispiel #9
0
def getmovies():
    name = User.get_by_email(session['email']).name
    searchlist = []
    query = request.form['search']
    movies = Movie.get_all_movies()
    for m in movies:
        if search(query, m.title):
            print(m.title)
            searchlist.append(m)
    request1 = youtube.search().list(part="snippet",
                                     maxResults=5,
                                     q=query + "movie trailer",
                                     topicId="/m/02vxn",
                                     regionCode="US")
    responselist = request1.execute()
    responselist1 = responselist["items"]
    print(responselist1)

    for response in responselist1:
        try:
            videoId = response["id"]["videoId"]
        except:
            print("something went wrong")
            videoId = None
        title = response["snippet"]["title"]
        poster = response["snippet"]["thumbnails"]["high"]["url"]
        if videoId != None and poster != None and title != None:
            link = "https://www.youtube.com/watch?v=" + videoId
            movie = Movie(title, "search", "search", "", poster, link)
            searchlist.append(movie)
    return render_template("search.html", movies=searchlist, name=name)
Beispiel #10
0
def update_user():
    try:
        user = User(request.json["id"],
                    f'{request.json["name"]} {request.json["surname"]}',
                    request.json['phone'], request.json['email'])
        return service.update(user)
    except KeyError as e:
        return 'json invalido'
Beispiel #11
0
def add_to_unwatched(movieid):
    user = User.get_by_email(session['email'])
    userunwatched = user.getunwatched()
    for u in userunwatched:
        if u["_id"] == movieid:
            print("already added to favourites")
            return redirect("/profile")
    user.addtounwatched(movieid)
    return redirect("/profile")
Beispiel #12
0
def user_login():
    email = request.form['email']
    password = request.form['password']
    if User.login(email, password):
        session['email'] = email
        return redirect('/profile')
    else:
        session['email'] = None
        return "<h1>Invalid email address or password. Please try again! :( </h1>"
Beispiel #13
0
def add_to_favourites(movieid):
    user = User.get_by_email(session['email'])
    userfavourites = user.getfavourites()
    for u in userfavourites:
        if u["_id"] == movieid:
            print("already added to favourites")
            return redirect("/profile")
    user.addtofavorites(movieid)
    return redirect("/profile")
Beispiel #14
0
def unlike(movieid):
    user = User.get_by_email(session['email'])
    userunliked = user.getunliked()
    for u in userunliked:
        if u["_id"] == movieid:
            print("already added to unliked")
            return redirect("/profile")
    user.addtounliked(movieid)
    return redirect("/profile")
Beispiel #15
0
def user_register():
    name = request.form['name']
    email = request.form['email']
    password = request.form['password']
    check = User.register_user(name, email, password)
    if check:
        session['email'] = email
        return redirect('/profile')
    else:
        return "User already exists"
Beispiel #16
0
def get(id):
    user_id = request_user_id(request)
    user = User.objects(_id=user_id)

    if not user:
        return res_success(200)

    if id == user_id:
        return res_success(200, user)
    else:
        data = {'id': str(user.get('_id')), 'email': user.get('email')}
        return res_success(200, data)
Beispiel #17
0
def join_user_league():
    required = ['league_id']
    params = get_required_params(request, required, 'POST')
    if not params:
        return json_err("Missing required parameters.")

    user = User(session['user_id'])

    # TODO check if league exists
    user_league = UserLeague(params['league_id'])

    user_league.add_user(user)

    return user_league.json()
Beispiel #18
0
 def get_current_requests(self, data):
     """
     Simply returns a list of all the course watch requests in firebase.
     :return:
     """
     logging.info("getting current requests for {0}".format(data))
     try:
         user = User.fromJSON(data)
         current_courses = self.request_service.get_requests_for_user(user)
         data = [course.toJSON() for course in current_courses]
     except Exception as e:
         response = self.response_util.build_error_response(
             code=500, message="An Error Occurred: " + e.message)
         return response
     return self.response_util.build_success_response(
         code=200, message="Retrieved current requests", data=data)
Beispiel #19
0
    def test_addAll(self):
        user1 = User()
        user1.fullname = 'Jon1'
        user2 = User()
        user2.fullname = 'Jon2'

        session.add_all([user1, user2])
        session.commit()
        self.assertIsNotNone(user1.id)
        self.assertIsNotNone(user2.id)

        print(user1, user2)
Beispiel #20
0
    def movieAI(user_id):
        user = User.get_by_id(user_id)
        movielist = []
        liked = user.getliked()
        unliked = user.getunliked()
        unwatched = user.getunwatched()
        favourites = user.getfavourites()
        print(favourites)
        all = Movie.get_topmovies()
        likedgenre = []
        likedcategory = []
        likedids = []
        unlikedids = []
        favouriteids = []
        unwatchedids = []
        for i in liked:
            likedgenre.append(i["genre"])
            likedcategory.append(i["category"])
            likedids.append(i["_id"])
        for i in unliked:
            unlikedids.append(i["_id"])
        for i in favourites:
            favouriteids.append(i["_id"])
        for i in unwatched:
            unwatchedids.append(i["_id"])

        likedgenre = list(dict.fromkeys(likedgenre))
        likedcategory = list(dict.fromkeys(likedcategory))

        for i in all:
            if i.genre in likedgenre and i.category in likedcategory:
                movielist.append(i)

        for i in all:
            movielist.append(i)

        new_list = []
        for v in movielist:
            if v._id not in favouriteids and v._id not in likedids and v._id not in unlikedids and v._id not in unwatchedids:
                new_list.append(v)

        new_list = list(dict.fromkeys(new_list))
        return new_list
Beispiel #21
0
 def createUser():
     try:
         global service, response
         logger.info('Calling createUser')
         data = request.json
         user = User(username=data.get('username'),
                     user_type=data.get('user_type'),
                     name=data['user_details']['name'],
                     dob=data['user_details']['dob'],
                     email=data['user_details']['email'],
                     gender=data['user_details']['gender'],
                     street=data['user_details']['address']['street'],
                     province=data['user_details']['address']['province'],
                     country=data['user_details']['address']['country'],
                     phonenumber=data['user_details']['phonenumber'])
         dashboard = Dashboard(
             total_visits=data['dashboard']['total_visits'],
             cancelled_visits=data['dashboard']['cancelled_visits'],
             upcoming_visits=data['dashboard']['upcoming_visits'],
             bookings_history=data.get('bookings_history'),
             messages=data['dashboard']['messages'])
         if (data.get('user_type') == 'store_owner'):
             store = Store(
                 name=data['store_details']['name'],
                 establishedon=data['store_details']['establishedon'],
                 email=data['store_details']['email'],
                 size=data['store_details']['size'],
                 street=data['store_details']['street'],
                 province=data['store_details']['province'],
                 country=data['store_details']['country'],
                 phonenumber=data['store_details']['phonenumber'])
             response = service.handleService(user, dashboard, store)
         response = service.handleService(user, dashboard)
         if (response != ""):
             return 'User created'
         else:
             return 'User not created'
     except (Exception) as e:
         return e.response
Beispiel #22
0
def getunwatchedcache():
    user = User.get_by_email(session['email'])
    userunwatched = user.getunwatched()
    return userunwatched
Beispiel #23
0
def getunwatched():
    user = User.get_by_email(session['email'])
    name = user.name
    userunwatched = getunwatchedcache()
    print(userunwatched)
    return render_template("unwatched.html", movies=userunwatched, name=name)
Beispiel #24
0
def gettopmovies():
    user = User.get_by_email(session['email'])
    movies = Movie.get_topmovies()
    name = user.name
    return render_template("topmovies.html", movies=movies, name=name)
Beispiel #25
0
def get_user():
    user = User(session['user_id'])

    return user.json()
Beispiel #26
0
 def setUp(self):
     self.exercise = Exercise("Barbell curl", 135, 3, 12, 500, 11)
     self.workout = Workout("the day!!", 0, 0, 0, 0)
     self.user = User("Jake")
     self.firebase_test_client = FirebaseClient()
Beispiel #27
0
def getbolly():
    user = User.get_by_email(session['email'])
    name = user.name
    movies = Movie.get_bollywood()
    return render_template("bollywood.html", movies=movies, name=name)
Beispiel #28
0
def getfavcache():
    user = User.get_by_email(session['email'])
    userfavourites = user.getfavourites()
    return userfavourites
Beispiel #29
0
def getliked():
    user = User.get_by_email(session['email'])
    name = user.name
    userliked = getlikedcache()
    return render_template("liked.html", movies=userliked, name=name)
Beispiel #30
0
def getlikedcache():
    user = User.get_by_email(session['email'])
    userliked = user.getliked()
    return userliked