Example #1
0
    def delete(self, student_id):
        """
        특정 학생의 상벌점 내역 삭제
        """
        payload = request.json

        history_id = payload['historyId']

        student = StudentModel.objects(id=student_id).first()

        if not student:
            return Response('', 204)

        if len(history_id) != 24:
            return Response('', 205)

        history = student.point_histories.filter(id=history_id).first()
        if not history:
            return Response('', 205)

        student.point_histories = student.point_histories.exclude(
            id=history_id)
        if history.point_type:
            student.good_point = student.good_point - history.point
        else:
            student.bad_point = student.bad_point - history.point

        student.save()

        return Response('', 200)
Example #2
0
    def post(self):
        """
        새로운 관리자 계정 생성
        """
        id = request.form['id']
        pw = request.form['pw']
        name = request.form['name']

        student = StudentModel.objects(id=id).first()
        admin = AdminModel.objects(id=id).first()
        if any((student, admin)):
            return Response('', 204)

        # --- Create new admin account_admin

        pw = hexlify(pbkdf2_hmac(
            hash_name='sha256',
            password=pw.encode(),
            salt=current_app.secret_key.encode(),
            iterations=100000
        )).decode('utf-8')
        # pbkdf2_hmac hash with salt(secret key) and 100000 iteration

        AdminModel(id=id, pw=pw, name=name, signup_time=datetime.now()).save()

        return Response('', 201)
Example #3
0
    def post(self):
        """
        학생 로그인
        """
        id = request.form['id']
        pw = request.form['pw']

        pw = hexlify(
            pbkdf2_hmac(hash_name='sha256',
                        password=pw.encode(),
                        salt=current_app.secret_key.encode(),
                        iterations=100000)).decode('utf-8')

        # pbkdf2_hmac hash with salt(secret key) and 100000 iteration

        student = StudentModel.objects(id=id, pw=pw).first()

        if not student:
            abort(401)

        # --- Auth success

        return self.unicode_safe_json_response(
            {
                'access_token':
                create_access_token(
                    TokenModel.generate_token(AccessTokenModel, student,
                                              request.headers['USER-AGENT'])),
                'refresh_token':
                create_refresh_token(
                    TokenModel.generate_token(RefreshTokenModel, student,
                                              request.headers['USER-AGENT']))
            }, 200)
Example #4
0
    def delete(self):
        """
        학생 계정 제거
        """
        def generate_new_signup_waiting_student_account():
            while True:
                new_uuid = str(uuid4())[:4]

                if not SignupWaitingModel.objects(uuid=new_uuid):
                    break

            SignupWaitingModel(uuid=new_uuid,
                               name=student.name,
                               number=student.number).save()

            return new_uuid

        payload = request.json

        student_number = payload['number']

        student = StudentModel.objects(number=student_number).first()

        if not student:
            signup_waiting = SignupWaitingModel.objects(
                number=student_number).first()

            return {
                'uuid': signup_waiting.uuid
            } if signup_waiting else Response('', 204)
        else:
            student.delete()

            return {'uuid': generate_new_signup_waiting_student_account()}, 201
Example #5
0
    def testBadPointGivingSuccess(self):
        # (1) 벌점 부여
        resp = self._request(rule_id=self.bad_point_rule.id,
                             apply_good_point=False,
                             point=1)

        # (2) status code 201
        self.assertEqual(resp.status_code, 201)

        # (3) response data
        data = resp.json

        self.assertIsInstance(data, dict)

        self.assertIn('id', data)
        self.assertIsInstance(data['id'], str)

        # (4) 데이터베이스 확인
        student = StudentModel.objects(id=self.student_id).first()
        self.assertEqual(len(student.point_histories), 1)

        history = student.point_histories[0]
        self.assertEqual(history.point_type, False)
        self.assertEqual(history.point, 1)

        self.assertEqual(student.bad_point, 1)
Example #6
0
    def wrapper(*args, **kwargs):
        admin = AdminModel.objects(id=get_jwt_identity()).first()
        student = StudentModel.objects(id=get_jwt_identity()).first()

        if not any((admin, student)):
            abort(403)

        return fn(*args, **kwargs)
Example #7
0
    def _create_fake_account(self):
        self.admin = AdminModel(id=self.admin_id,
                                pw=self.encrypted_pw,
                                name=self.admin_name).save()

        self.student = StudentModel(id=self.student_id,
                                    pw=self.encrypted_pw,
                                    name=self.student_name,
                                    number=self.student_number).save()
Example #8
0
    def testPatchSuccess(self):
        # (1) 벌점 교육 상태 변경
        resp = self._request()

        # (2) status code 200
        self.assertEqual(resp.status_code, 200)

        # (3) 데이터베이스 확인
        student = StudentModel.objects(id=self.student_id).first()

        self.assertTrue(student.penalty_training_status)
Example #9
0
    def post(self):
        """
        학생 로그인 
        """
        payload = request.json

        student = StudentModel.objects(id=payload['id'], pw=self.encrypt_password(payload['password'])).first()

        return ({
            'accessToken': AccessTokenModelV2.create_access_token(student, request.headers['USER-AGENT']),
            'refreshToken': RefreshTokenModelV2.create_refresh_token(student, request.headers['USER-AGENT'])
        }, 201) if student else Response('', 401)
Example #10
0
    def testDeleteSuccess(self):
        # (1) 상점 내역 삭제
        resp = self._request()

        # (2) status code 200
        self.assertEqual(resp.status_code, 200)

        # (3) 데이터베이스 확인
        student = StudentModel.objects(id=self.student_id).first()
        self.assertEqual(len(student.point_histories), 1)
        self.assertFalse(student.good_point)

        # (4) 벌점 내역 삭제
        resp = self._request(history_id=self.bad_point_history_id)

        # (5) status code 200
        self.assertEqual(resp.status_code, 200)

        # (6) 데이터베이스 확인
        student = StudentModel.objects(id=self.student_id).first()
        self.assertFalse(student.point_histories)
        self.assertFalse(student.bad_point)
Example #11
0
    def _create_fake_accounts(self):
        AdminModel(
            id=self.admin_id,
            pw=self.hashed_pw,
            name='fake'
        ).save()

        StudentModel(
            id=self.student_id,
            pw=self.hashed_pw,
            name='fake',
            number=1111
        ).save()
Example #12
0
    def testSignupFailure_uuidDoesntExist(self):
        # (1) 회원가입
        resp = self._request(uuid='0000')

        # (2) status code 204
        self.assertEqual(resp.status_code, 205)

        # (3) check database StudentModel
        student = StudentModel.objects(number=self.new_student_number)
        self.assertIsNone(student)

        # (4) check database SignupWaitingModel
        student = SignupWaitingModel.objects(uuid=self.new_student_uuid)
        self.assertIsNotNone(student)
Example #13
0
    def post(self):
        payload = request.json

        account = StudentModel.objects(username=payload['username']).first()

        if not account:
            return {}, 404
        if account.password != payload['password']:
            return {}, 401

        return {
            'access': AccessTokenModel.create_access_token(account),
            'refresh': RefreshTokenModel.create_refresh_token(account)
        }, 200
Example #14
0
    def get(self):
        """
        특정 학생의 상벌점 내역 조회
        """
        id = request.args['id']
        student = StudentModel.objects(id=id).first()
        if not student:
            return Response('', 204)

        response = [
            mongo_to_dict(history) for history in student.point_histories
        ]

        return self.unicode_safe_json_response(response)
Example #15
0
    def post(self):
        payload = request.json

        uuid = payload['uuid']
        id = payload['id']
        password = payload['password']

        if StudentModel.objects(id=id):
            abort(409)

        signup_waiting = SignupWaitingModel.objects(uuid=uuid).first()
        if not signup_waiting:
            return Response('', 204)

        StudentModel(
            id=id,
            pw=self.encrypt_password(password),
            name=signup_waiting.name,
            number=signup_waiting.number
        ).save()

        signup_waiting.delete()

        return Response('', 201)
Example #16
0
    def _create_fake_account(self):
        pw = hexlify(
            pbkdf2_hmac('sha256', b'pw', app.secret_key.encode(),
                        100000)).decode()

        AdminModel(signup_time=datetime.now,
                   id='admin',
                   pw=pw,
                   name='fake_admin').save()

        StudentModel(signup_time=datetime.now,
                     id='student',
                     pw=pw,
                     name='fake_student',
                     number=1111).save()
Example #17
0
    def get(self, student_id):
        """
        특정 학생의 상벌점 내역 조회
        """
        student = StudentModel.objects(id=student_id).first()

        return self.unicode_safe_json_dumps(
            [{
                'id': str(history.id),
                'date': history.time.strftime('%Y-%m-%d'),
                'reason': history.reason,
                'pointType': history.point_type,
                'point': history.point
            }
             for history in student.point_histories]) if student else Response(
                 '', 204)
Example #18
0
    def post(self, student_id):
        """
        특정 학생에게 상벌점 부여
        """
        def append_history(rule):
            point_history = PointHistoryModel(reason=rule.name,
                                              point_type=rule.point_type,
                                              point=point)

            student.point_histories.append(point_history)

            return point_history

        def update_penalty_level():
            if (
                    student.bad_point - 10
            ) // 5 > student.penalty_level and not student.penalty_training_status:
                student.penalty_level = (student.bad_point - 10) // 5
                student.penalty_training_status = True

        payload = request.json

        apply_good_point = payload['applyGoodPoint']
        point = payload['point']
        rule_id = payload['ruleId']

        student = StudentModel.objects(id=student_id).first()

        if not student:
            return Response('', 204)

        if len(rule_id) != 24 or not PointRuleModel.objects(id=rule_id):
            return Response('', 205)

        history = append_history(PointRuleModel.objects(id=rule_id).first())

        if apply_good_point:
            student.good_point += point
        else:
            student.bad_point += point

        update_penalty_level()

        student.save()

        return {'id': str(history.id)}, 201
Example #19
0
    def testSignupSuccess(self):
        # (1) 회원 가입
        resp = self._request()

        # (2) status code 201
        self.assertEqual(resp.status_code, 201)

        # (3) check database StudentModel
        student = StudentModel.objects(id=self.new_student_id)
        self.assertIsNotNone(student)

        self.assertEqual(student.name, self.new_student_name)
        self.assertEqual(student.number, self.new_student_number)

        # (4) check database SignupWaitingModel
        student = SignupWaitingModel.objects(uuid=self.new_student_uuid)
        self.assertIsNone(student)
Example #20
0
    def patch(self):
        """
        학생 벌점 교육 완료
        """
        id = request.form['id']
        student = StudentModel.objects(id=id).first()
        if not student:
            return Response('', 204)

        if not student.penalty_training_status:
            return Response('', 205)

        # 상벌점 삭감
        good_point = student.good_point
        penalty_level = student.penalty_level

        point_decrease = 4 + penalty_level if penalty_level < 4 else 7

        if good_point > point_decrease:
            deleted_point = point_decrease
        else:
            deleted_point = good_point

        student.update(good_point=student.good_point - deleted_point,
                       bad_point=student.bad_point - deleted_point,
                       penalty_training_status=False)

        # 상벌점 삭감

        student.point_histories.append(
            PointHistoryModel(reason='벌점 봉사 수료 상점 삭감',
                              point_type=True,
                              point=-deleted_point,
                              time=datetime.now(),
                              id=ObjectId()))
        student.point_histories.append(
            PointHistoryModel(reason='벌점 봉사 수료 벌점 삭감',
                              point_type=False,
                              point=-deleted_point,
                              time=datetime.now(),
                              id=ObjectId()))
        student.save()

        return Response('', 200)
Example #21
0
    def testSignupSuccess(self):
        # (1) 회원가입
        resp = self._request()

        # (2) status code 201
        self.assertEqual(resp.status_code, 201)

        # (3) 데이터베이스 확인
        student = StudentModel.objects(
            id=self.new_student_data['id'],
            pw=self.encrypt_password(self.new_student_data['pw']),
            name=self.new_student_data['name'],
            number=self.new_student_data['number']
        ).first()
        # 조건을 고의적으로 많이 달아서, 별도의 assertion 코드를 줄임

        self.assertTrue(student)

        self.assertFalse(SignupWaitingModel.objects(uuid=self.new_student_data['uuid']))
Example #22
0
    def post(self):
        """
        특정 학생에 대한 상벌점 부여
        """
        id = request.form['id']
        student = StudentModel.objects(id=id).first()
        if not student:
            return Response('', 204)

        rule_id = request.form['rule_id']
        if len(rule_id) != 24:
            return Response('', 205)

        rule = PointRuleModel.objects(id=rule_id).first()
        if not rule:
            return Response('', 205)

        point = int(request.form['point'])

        student.point_histories.append(
            PointHistoryModel(reason=rule.name,
                              point_type=rule.point_type,
                              point=point,
                              time=datetime.now(),
                              id=ObjectId()))
        # Append history

        if rule.point_type:
            student.good_point += point
        else:
            student.bad_point += point

        if (
                student.bad_point - 10
        ) // 5 > student.penalty_level and not student.penalty_training_status:
            student.penalty_level = student.penalty_level + 1
            student.penalty_training_status = True

        student.save()

        return Response('', 201)
Example #23
0
    def post(self):
        """
        학생 계정 비밀번호 변경
        """
        number = int(request.form['number'])
        student = StudentModel.objects(number=number).first()
        pw = request.form['pw']

        if not student:
            return Response('', 204)

        pw = hexlify(pbkdf2_hmac(
            hash_name='sha256',
            password=pw.encode(),
            salt=current_app.secret_key.encode(),
            iterations=100000
        )).decode('utf-8')

        student.update(pw=pw)

        return Response('', 201)
Example #24
0
    def post(self):
        payload = request.json

        if StudentModel.objects.filter(
                Q(username=payload['username'])
                or Q(student_id=payload['studentId'])).first():
            return {}, 409
        else:
            try:
                student = StudentModel(
                    username=payload['username'],
                    password=payload['password'],
                    name=payload['name'],
                    student_id=payload['studentId'],
                    birth=datetime.strptime(payload['birth'],
                                            "%Y-%m-%d").date(),
                    profile_image=payload['profileImage']).save()
                return {
                    'access': AccessTokenModel.create_access_token(student),
                    'refresh': RefreshTokenModel.create_refresh_token(student)
                }, 201
            except NotUniqueError:
                return {}, 409
Example #25
0
    def delete(self):
        """
        상벌점 내역 삭제
        """
        student_id = request.form['student_id']
        point_id = request.form['point_id']

        student = StudentModel.objects(id=student_id).first()
        if not student:
            return Response('', 204)

        point = student.point_histories.filter(id=point_id).first()
        if not point:
            return Response('', 205)

        student.point_histories = student.point_histories.exclude(id=point_id)

        if point.point_type:
            student.update(good_point=student.good_point - point.point)
        else:
            student.update(bad_point=student.bad_point - point.point)
        student.save()

        return Response('', 200)
Example #26
0
    def patch(self, student_id):
        """
        학생 벌점 교육 상태 변경
        """
        payload = request.json

        status = payload['status']

        student = StudentModel.objects(id=student_id).first()

        if not student:
            return Response('', 204)
        
        if not status:
            decrease_point = student.penalty_level + 4 if student.penalty_level < 3 else 7

            student.good_point = student.good_point - decrease_point
            student.bad_point = student.bad_point - decrease_point

            student.point_histories.append(PointHistoryModel(
                reason='벌점 봉사 수료 상점 삭감',
                point_type=True,
                point=-decrease_point,
            ))

            student.point_histories.append(PointHistoryModel(
                reason='벌점 봉사 수료 벌점 삭감',
                point_type=False,
                point=-decrease_point,
            ))

        student.penalty_training_status = status

        student.save()

        return Response('', 200)
Example #27
0
 def tearDown(self):
     StudentModel.objects(id=self.new_student_id).delete()
     SignupWaitingModel.objects(id=self.new_student_id).delete()
Example #28
0
 def post(self):
     return Response('', 409 if StudentModel.objects(id=request.json['id']) else 200)
Example #29
0
    def wrapper(*args, **kwargs):
        student = StudentModel.objects(id=get_jwt_identity()).first()
        if not student:
            abort(403)

        return fn(*args, **kwargs)