Beispiel #1
0
    def post(self):
        args = parser.parse_args()
        user_id = get_jwt_identity()['id']

        # Check if passwords are the same
        if args['password'] is not None and args['passwordConfirm'] != args[
                'password']:
            return response(
                {'errors': ['Password and Confirm Password must be same']},
                400)

        # Check if the email is already taken or not
        email = args['email']
        user = User().where('email', email).first()
        if user.exists() and user.ATTRIBUTES['id'] != user_id:
            return response({'errors': ['This email is already taken']}, 400)

        # Update user
        user = User().where('id', '=', user_id).first()
        if user.exists() is True:
            user.update({
                'name':
                args['name'],
                'email':
                args['email'],
                'slug':
                user.generateSlug(name=args['name']),
                'password':
                bcrypt.generate_password_hash(args['password']).decode('utf-8')
            })
            return response({'user': user.data()})

        return response({'errors': ['User could not found']}, 404)
Beispiel #2
0
    def post(self, user_id):
        args = parser.parse_args()

        # Check if the email is already taken or not
        email = args['email']
        user = User().where('email', email).first()
        if user.exists() and user.ATTRIBUTES['id'] != user_id:
            return response({
                'errors': 'This email is already taken'
            }, 400)

        # Update user
        user = User().where('id', '=', user_id).first()
        if user.exists() is True:
            user.update({
                'name': args['name'],
                'email': args['email'],
                'slug': user.generateSlug(name=args['name']),
            })
            return response({
                'user': user.data()
            })

        return response({
            'errors': [
                'User could not found'
            ]
        }, 404)
Beispiel #3
0
    def get(self):
        events = Event().where().orderBy().get().data()
        for event in events:
            user = User().where('id', event['user_id']).first()
            event['user'] = user.data()

        return response({'events': events}, 200)
Beispiel #4
0
    def validate(self):
        term = Term().where('id', self.ATTRIBUTES['term_id']).first()
        if term.exists() is False:
            self.setError('Term could not found')
        else:
            self.plus('term', term.data())

        lecturer = Lecturer().where('id',
                                    self.ATTRIBUTES['lecturer_id']).first()
        if lecturer.exists() is False:
            self.setError('Lecturer could not found')
        else:
            self.plus('lecturer', lecturer.data())

        course = Course().where('id', self.ATTRIBUTES['course_id']).first()
        if course.exists() is False:
            self.setError('Course could not found')
        else:
            self.plus('course', course)

        user = User().where('id', self.ATTRIBUTES['user_id']).first()
        if user.exists() is False:
            self.setError('User could not found')
        else:
            self.plus('user', user)

        if not self.getErrors():
            return True
        return False
Beispiel #5
0
    def get(self, type_id):
        comments = Comment().where([['type', '=', 'notes'],
                                    ['type_id', '=',
                                     type_id]]).orderBy().get().data()
        for comment in comments:
            user = User().where('id', comment['user_id']).first()
            comment['user'] = user.data()

        return response({'comments': comments}, 200)
Beispiel #6
0
    def get(self):
        notes = Note().where().orderBy().get().data()
        for note in notes:
            user = User().where('id', note['user_id']).first()
            note['user'] = user.data()

        return response({
            'notes': notes
        }, 200)
Beispiel #7
0
    def get(self, slug):
        user = User().where('slug', slug).first()
        if user.exists() is True:
            return response({
                'user': user.data()
            })

        return response({
            'errors': ['User could not found']
        })
Beispiel #8
0
 def get(self, note_slug):
     note = Note().where('slug', note_slug).first().data()
     user = User().where('id', note['user_id']).first()
     note['user'] = user.data()
     comments = Comment().where([['type', '=', 'notes'], ['type_id', '=', note['id']]]).get()
     for comment in comments.data():
         comment['user'] = User().where('id', comment['user_id']).first().data()
     note['comments'] = comments.data()
     return response({
         'notes': note
     }, 200)
Beispiel #9
0
    def post(self, user_id):
        user_id = get_jwt_identity()['id']
        user = User().where('id', user_id).first()
        if user.exists() is True:
            Comment().where('user_id', user_id).get().delete()
            GradeDistribution().where('user_id', user_id).get().delete()
            Lecturer().where('user_id', user_id).get().delete()
            Note().where('user_id', user_id).get().delete()
            user.delete()
            return response({'message': 'User deleted with success'}, 200)

        return response({'errors': ['User could not found!']}, 401)
Beispiel #10
0
 def validate(self):
     user = User().where('id', self.ATTRIBUTES['user_id']).first()
     if user is None:
         self.setError("User not found in the database!")
     if self.getErrors():
         return False
     return True
Beispiel #11
0
def before_request():
    path = request.path.split(sep='/')
    if path[2] == 'admin':
        if request.method != "OPTIONS":
            current_user = get_jwt_identity()
            if current_user is None or User().where('id', current_user['id']).first().hasRole('admin') is False:
                return response({'errors': ['Please login']}, 401)
Beispiel #12
0
    def validate(self):
        user = User().where('id', self.ATTRIBUTES['user_id']).first()
        if user.exists() is False:
            self.setError("User not found in the database!")
        else:
            self.plus('user', user)

        lecturer = Lecturer().where('email', self.ATTRIBUTES['email']).first()
        if lecturer.exists() is True:
            self.setError("There is already a lecturer added with this email.")
        else:
            self.plus('lecturer', lecturer)

        if self.getErrors():
            return False
        return True
Beispiel #13
0
    def validate(self):
        # term id exist
        term = Term().where('id', self.ATTRIBUTES['term_id']).first()
        if term.exists() is False:
            self.setError("Term not found")

        course = Course().where('id', self.ATTRIBUTES['course_id']).first()
        if course.exists() is False:
            self.setError("Course not found")

        user = User().where('id', self.ATTRIBUTES['user_id']).first()
        if user.exists() is False:
            self.setError("You are not the owner of this note")

        if self.getErrors():
            return False
        return True
Beispiel #14
0
    def get(self, type_id):
        comments = Comment().where([['type', '=', 'lecturers'],
                                    ['type_id', '=',
                                     type_id]]).orderBy().get().data()
        for comment in comments:
            user = User().where('id', comment['user_id']).first()
            comment['user'] = {'id': user.ATTRIBUTES['id']}

        return response({'comments': comments}, 200)
Beispiel #15
0
def register():

    email = request.json.get('email', None)
    password = request.json.get('password', None)
    phone = request.json.get('phone', None)
    username = request.json.get('username', None)
    name = request.json.get('name', None)

    if not email:
        return {'status': 'error', 'msg': 'Email not provided'}, 400

    if not password:
        return {'status': 'error', 'msg': 'Password not provided'}, 400

    if not phone:
        return {'status': 'error', 'msg': 'Email not provided'}, 400

    if not name:
        return {'status': 'error', 'msg': 'Password not provided'}, 400

    user = User.query.filter_by(email=email.lower()).first()

    if user:
        return {
            'status': 'error',
            'msg': 'User with this email already exist. Please login'
        }, 400

    user = User(phone=phone, name=name, email=email, username=username)
    user.hashPassword(password=password)
    db.session.add(user)
    db.session.commit()

    mail = NewUserMail(user.name, user.email)
    mail.create_mail()
    mail = SupportNewUserMail(user.name, user.email)
    mail.create_mail()

    return jsonify({
        'status': 'success',
        'msg': 'Account created successful'
    }), 200
Beispiel #16
0
    def validate(self):
        user = User().where('id', self.ATTRIBUTES['user_id']).first()
        if user.exists() is False:
            self.setError("User not found in the database!")

        if self.ATTRIBUTES['type'] == 'lecturers':
            lecturer = Lecturer().where('id',
                                        self.ATTRIBUTES['type_id']).first()
            if lecturer.exists() is False:
                self.setError("Lecturer not found in the database!")
        elif self.ATTRIBUTES['type'] == 'notes':
            note = Note().where('id', self.ATTRIBUTES['type_id']).first()
            if note.exists() is False:
                self.setError("Note not found in the database!")
        else:
            self.setError("Comment type is not valid")

        if self.getErrors():
            return False
        return True
Beispiel #17
0
    def post(self, type_id):
        args = parser.parse_args()
        type = 'notes'
        type_id = type_id
        commentText = args['comment']
        user_id = get_jwt_identity()['id']

        comment = Comment()
        comment.create({
            'type': type,
            'type_id': type_id,
            'comment': commentText,
            'user_id': user_id
        })

        if comment.validate() is False:
            return response({'errors': comment.getErrors()}, 401)

        user = User().where('id', user_id).first()
        comment.save()
        return response({'comment': comment.plus('user', user.data()).data()},
                        200)
Beispiel #18
0
def register_user():
    email = request.json['email']
    is_already_registered = User.query.filter_by(email=email).first()
    if is_already_registered:
        return jsonify(message='This author already registered.'), 409
    else:
        name = request.json['name']
        password = request.json['password'].encode('utf-8')
        password = hashpw(password, gensalt())
        user = User(name=name, email=email, password=password)
        DB.session.add(user)
        DB.session.commit()
        return jsonify(message='New author added to the blog!'), 201
Beispiel #19
0
    def post(self):
        args = parser.parse_args()
        title = args['title']
        description = args['description']
        max_participant = args['max_participant']
        started_at = args['started_at']
        user_id = get_jwt_identity()['id']

        event = Event()
        event.create({
            'title': title,
            'description': description,
            'max_participant': max_participant,
            'started_at': started_at,
            'user_id': user_id
        })

        if event.validate() is False:
            return response({'errors': event.getErrors()}, 401)

        user = User().where('id', user_id).first()
        event.save()
        return response({'event': event.plus('user', user.data()).data()}, 200)
Beispiel #20
0
    def post(self):
        login = request.get_json()
        username, password, uni = login.values()

        if uni not in [portal.name for portal in SupportedPortals]:
            return {
                'message':
                "Error, functionalities for '{}' portal not supported.".format(
                    uni)
            }, 400

        if uni == SupportedPortals.UNSW.name:
            portal = UnswScraper()
            login = portal.login

        try:
            sesh = login(username=username, password=password)
        except ConnectionError:
            return {'message': 'Error connecting to data source.'}, 404
        except ValueError:
            return {'message': 'Invalid username or password.'}, 400
        except:
            return {'message': 'Error logging in.'}, 400

        # TODO: sort out proper way to catch db errors, a general try catch will still crash server if error in db
        try:
            session = db_session()
            user_lookup = session.query(User).filter_by(username=username)
            if user_lookup.one_or_none() == None:
                session.add(
                    User(username=username,
                         last_session_cookie_jar=pickle.dumps(sesh.cookies),
                         uni=uni))
            else:
                session.query(User).filter_by(username=username).update(
                    {User.last_session_cookie_jar: pickle.dumps(sesh.cookies)})
            session.commit()
        except:
            return {'message': 'Error with database.'}, 400

        return {
            'token':
            jwt.encode(
                {
                    'username': username,
                    'exp': datetime.now() + timedelta(minutes=20)
                },
                key=scraper_token_key,
                algorithm='HS256').decode('utf-8'),
        }, 200
Beispiel #21
0
 def post(self, user_id):
     user = User().where('id', '=', user_id).first()
     print(user_id, file=sys.stderr)
     if user.exists():
         Comment().where('user_id', user_id).get().delete()
         Event().where('user_id', user_id).get().delete()
         GradeDistribution().where('user_id', user_id).get().delete()
         lecturers = Lecturer().where('user_id', user_id).get()
         for lecturer in lecturers.data():
             Comment().where([['type', '=', 'lecturers'], ['type_id', '=', lecturer['id']]]).get().delete()
             GradeDistribution().where('lecturer_id', '=', lecturer['id']).get().delete()
         lecturers.delete()
         notes = Note().where('user_id', user_id).get()
         for note in notes.data():
             Comment().where([['type', '=', 'notes'], ['type_id', '=', note['id']]]).get().delete()
         notes.delete()
         user.delete()
         return response({
             'message': 'User deleted successfully'
         }, 202)
     return response({
         'message': 'User does not exist'
     }, 404)
Beispiel #22
0
    def post(self):
        args = parser.parse_args()
        title = args['title']
        content = args['content']
        lecturer = args['lecturer']
        link = args['link']
        course_id = args['course_id']
        course_code = args['course_code']
        english = args['english']
        term_id = args['term_id']
        user_id = get_jwt_identity()['id']

        note = Note()
        note.create({
            'title': title,
            'content': content,
            'lecturer': lecturer,
            'link': link,
            'course_id': course_id,
            'course_code': course_code,
            'english': english,
            'term_id': term_id,
            'user_id': user_id,
            'slug': note.generateSlug(name=title)
        })

        if note.validate() is False:
            return response({
                'errors': note.getErrors()
            }, 401)

        user = User().where('id', user_id).first()
        note.save()
        return response({
            'note': note.plus('user', user.data()).data()
        }, 200)
Beispiel #23
0
    def post(self):
        args = parser.parse_args()
        email = args['email']
        password = args['password']

        user = User().where([['email', '=', email]]).first()

        if user.exists() and bcrypt.check_password_hash(
                user.HIDDEN['password'], password):
            return response({
                'user':
                user.plus('token',
                          user.generateToken()['jwt']).plus(
                              'admin', user.hasRole('admin')).data()
            })

        return response(
            {'errors': ['Credentials do not match with our records.']}, 401)
Beispiel #24
0
 def get(self):
     users = User().where().orderBy().get()
     return response({
         'users': users.data()
     })
Beispiel #25
0
    def post(self):
        args = parser.parse_args()
        password = args['password']
        password_confirm = args['passwordConfirm']

        if password != password_confirm:
            return response({'errors': ['Passwords do not match']}, 401)

        # Rule 2
        user = User()
        user.create({
            'name':
            args['name'],
            'email':
            args['email'],
            'password':
            bcrypt.generate_password_hash(args['password']).decode('utf-8'),
            'slug':
            user.generateSlug(args['name'])
        })
        if user.validate() is False:
            return response({'errors': user.getErrors()}, 401)

        user.save()
        return response({
            'user':
            user.plus('token',
                      user.generateToken()['jwt']).plus(
                          'admin', user.hasRole('admin')).data()
        })
Beispiel #26
0
    def post(self):
        user = User().where('id', 21).first()
        user.update({'email': '[email protected]', 'name': 'Yavuz Koca'})

        return response({'user': user.data()})
Beispiel #27
0
 def get(self, event_id):
     event = Event().where('id', event_id).first().data()
     user = User().where('id', event['user_id']).first()
     event['user'] = user.data()
     return response({'event': event}, 200)