예제 #1
0
    def post(self):
        """
        학교에 가입 요청
        """
        school_id = request.json['schoolId']
        admission_year = request.json['admissionYear']

        if len(school_id) != 10:
            return Response('', 204)

        school = SchoolModel.objects(school_id=school_id).first()
        if not school:
            return Response('', 204)

        if AccountModel.objects(school=school).count() == 0:
            # 해당 학교의 첫 가입자가 관리자
            is_admin = True
            # school_parser.parse_school_schedules(school_id)
        else:
            is_admin = False

        user = AccountModel.objects(id=get_jwt_identity()).first()
        user.update(is_admin=is_admin,
                    requested=True,
                    signed=True if is_admin else False,
                    waiting=False if is_admin else True,
                    school=school,
                    admission_year=admission_year)

        return Response('', 201)
    def post(self):
        """
        가입 승인 요청자 목록 조회
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()

        if not user.is_admin:
            abort(403)

        return self.unicode_safe_json_response([{
            'id': user.id,
            'name': user.name,
            'admissionYear': user.admission_year
        } for user in AccountModel.objects(accepted=False, school=user.school)])
예제 #3
0
    def post(self):
        """
        회원가입
        """
        payload = request.json

        email = payload['email']
        pw = payload['pw']

        if AccountModel.objects(email=email):
            return Response('', 409)

        mail_client = current_app.config['MAIL_CLIENT']

        code = generate_email_certification_code(email)

        msg = Message('Please verify user email',
                      sender=current_app.config['MAIL_USERNAME'],
                      recipients=[email])
        msg.html = '<a href="http://{0}:{1}/certify/{2}">인증하기</a>'.format(
            current_app.config['REPRESENTATIVE_HOST']
            or current_app.config['HOST'],
            current_app.config['PORT'] if not current_app.testing else 80,
            code)

        mail_client.send(msg)

        AccountModel(email=email, pw=generate_password_hash(pw)).save()

        return Response('', 201)
예제 #4
0
    def post(self, id):
        """
        기본 정보 업로드
        """
        payload = request.json

        shortest_cycle = payload['shortestCycle']
        longest_cycle = payload['longestCycle']
        today_status = payload['todayStatus']

        account = AccountModel.objects(id=id).first()

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

        if all([
                account.shortest_cycle, account.longest_cycle,
                account.last_mens_start_date
        ]):
            return Response('', 208)

        if shortest_cycle > longest_cycle:
            abort(400)

        account.update(shortest_cycle=shortest_cycle,
                       longest_cycle=longest_cycle,
                       last_mens_start_date=datetime.strptime(
                           payload['lastMensStartDate'], '%Y-%m-%d'),
                       calendar={str(datetime.now().date()): today_status})

        redis_client = current_app.config['REDIS_CLIENT']
        redis_client.lpush('queue:requires_calendar_refresh', id)

        return Response('', 201)
    def post(self):
        """
        서비스 자체 계정 로그인
        """
        id = request.json['id']
        pw = request.json['pw']

        hashed_pw = generate_password_hash(pw)
        user = AccountModel.objects(id=id).first()

        if not user or check_password_hash(hashed_pw, user.pw):
            return abort(401)

        refresh_token = uuid4()
        RefreshTokenModel(
            token=refresh_token,
            token_owner=user,
            pw_snapshot=hashed_pw
        ).save()
        # Generate new refresh token made up of uuid4

        return {
            'accessToken': create_access_token(id),
            'refreshToken': create_refresh_token(str(refresh_token))
        }
예제 #6
0
    def post(self):
        payload = request.json

        email = payload['email']
        pw = payload['pw']

        user = AccountModel.objects(email=email).first()

        if user:
            if check_password_hash(user.pw, pw):
                if not user.email_certified:
                    return Response('', 204)

                elif not all((user.nickname, user.major_interests
                              or user.minor_interests)):
                    return Response('', 205)

                return {
                    'accessToken':
                    create_access_token(
                        TokenModel.generate_token(AccessTokenModel, user)),
                    'refreshToken':
                    create_refresh_token(
                        TokenModel.generate_token(RefreshTokenModel, user))
                }
            else:
                abort(401)
        else:
            abort(401)
예제 #7
0
    def post(self):
        """
        페이스북 계정 로그인
        """
        payload = request.json

        fb_id = payload['fbId']

        user = AccountModel.objects(id=fb_id).first()

        if not user:
            # 사용자가 미존재, 회원가입을 함께 시켜줌
            if self.is_available_fb_id(fb_id):
                user = AccountModel(id=fb_id).save()
            else:
                abort(401)

        return {
            'accessToken':
            create_access_token(
                TokenModel.generate_token(AccessTokenModel, user)),
            'refreshToken':
            create_refresh_token(
                TokenModel.generate_token(RefreshTokenModel, user))
        }
예제 #8
0
    def get(self, email):
        user = AccountModel.objects(email=email).first()

        if user.email_certified:
            return Response('', 200)
        else:
            return Response('', 204)
예제 #9
0
    def post(self):
        """
        자체 계정 로그인
        """
        payload = request.json

        user = AccountModel.objects(id=payload['id']).first()

        if not user:
            abort(401)
        else:
            if check_password_hash(user.pw, payload['pw']):
                if not all([
                        user.shortest_cycle, user.longest_cycle,
                        user.last_mens_start_date
                ]):
                    return Response('', 205)
                else:
                    return {
                        'accessToken':
                        create_access_token(
                            TokenModel.generate_token(AccessTokenModel, user)),
                        'refreshToken':
                        create_refresh_token(
                            TokenModel.generate_token(RefreshTokenModel, user))
                    }
            else:
                abort(401)
예제 #10
0
    def get(self):
        """
        학사일정 앨범 데이터 조회
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        school = user.school
        album = ScheduledAlbumModel.objects(school=school).first()
        folders = ScheduledFolderModel.objects(album=album)

        response = [{
            'date': date,
            'resource': {
                'scheduleNames': schedules,
                'folder': {}
            }
        } for date, schedules in school.schedules.items()]

        for folder in folders:
            if folder.assigned_date not in response:
                # TODO 기타로 넘겨야 함
                continue

            response[folder.assigned_date]['folder'].update({
                # 'folderId': folder.id,
                'imageNames':
                [image_name for image_name in folder.image_names],
                'imageCount':
                len(folder.image_names)
            })

        return self.unicode_safe_json_response(response)
예제 #11
0
 def get(self, email):
     """
     이메일 중복체크
     """
     if AccountModel.objects(email=email):
         abort(409)
     else:
         return Response('', 200)
    def delete(self):
        """
        가입 요청 거절
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()

        if not user.is_admin:
            abort(403)

        id = request.json['id']

        user = AccountModel.objects(id=id).first()
        if not user:
            return Response('', 204)

        user.update(waiting=False, signed=False)

        return Response('', 200)
예제 #13
0
 def post(self):
     """
     로그인
     """
     id = request.form['id']
     pw = request.form['pw']
     user = AccountModel.objects(id=id, pw=pw).first()
     if user:
         return {'access_token': create_access_token(id)}, 200
     abort(401)
예제 #14
0
    def get(self):
        """
        자신의 학교 가입 상태 확인
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()

        return {
            'schoolName': user.school.name if user.school else None,
            'requested': user.requested,
            'signed': None if user.waiting else user.signed
        }
예제 #15
0
    def post(self, email):
        """
        기본 정보 업로드(초기화)
        """
        payload = request.json

        nickname = payload['nickname']
        categories = payload['categories']

        user = AccountModel.objects(email=email).first()

        if not user.email_certified:
            abort(401)

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

        if AccountModel.objects(nickname=nickname):
            abort(409)

        user.nickname = nickname

        for category_id in categories:
            major_interest = MajorInterestModel.objects(id=category_id).first()
            minor_interest = MinorInterestModel.objects(id=category_id).first()

            if major_interest:
                user.major_interests.append(major_interest)
            elif minor_interest:
                user.minor_interests.append(minor_interest)
            else:
                abort(400)

        user.save()

        return Response('', 201)
예제 #16
0
    def post(self):
        """
        자체 계정 회원가입
        """
        payload = request.json

        id = payload['id']

        if AccountModel.objects(id=id):
            abort(409)
        else:
            AccountModel(id=id,
                         pw=generate_password_hash(payload['pw'])).save()

            return Response('', 201)
예제 #17
0
    def post(self):
        """
        서비스 자체 회원가입
        """
        id = request.json['id']
        pw = request.json['pw']
        name = request.json['name']

        hashed_pw = generate_password_hash(pw)

        if AccountModel.objects(id=id).first():
            return Response('', 204)

        AccountModel(id=id, pw=hashed_pw, name=name).save()

        return Response('', 201)
예제 #18
0
    def post(self):
        """
        회원가입 
        """
        rq = request.form
        id = rq['id']
        pw = rq['pw']
        nickname = rq['nickname']
        phone = rq['phone']

        if AccountModel.objects(id=id).first():
            return Response('', 205)

        AccountModel(id=id, pw=pw, nickname=nickname, phone=phone).save()

        return Response('', 201)
예제 #19
0
    def delete(self):
        """
        자랑 글 삭제
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)
        id = request.form['id']

        boast = BoastModel.objects(id=id).first()
        if boast.author.id != user.id:
            abort(403)

        boast.delete()

        return Response('', 201)
예제 #20
0
    def post(self):
        """
        파티 글 작성
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        rq = request.json

        PartyModel(longitude=rq['longitude'],
                   latitude=rq['latitude'],
                   author=user,
                   title=rq['title'],
                   content=rq['content']).save()

        return Response('', 201)
예제 #21
0
    def delete(self):
        """
        파티 글 삭제
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        party_id = request.form['party_id']
        party = PartyModel.objects(id=party_id).first()
        if not party:
            return Response('', 204)

        if party.author.id != user.id:
            abort(403)

        party.delete()
        return Response('', 201)
예제 #22
0
    def post(self):
        """
        파티 참가
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        party_id = request.form['party_id']
        party = PartyModel.objects(id=party_id).first()
        if not party:
            return Response('', 204)
        for participant in party.participants:
            if participant.id == user.id:
                return Response('', 205)
        party.participants.append(user)
        party.save()
        return Response('', 201)
예제 #23
0
    def post(self):
        """
        자랑 글 작성
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        rq = request.form
        if len(rq['title']) < 5:
            return Response('', 205)

        boast = BoastModel(
            title=rq['title'],
            author=user,
            content=rq['content'],
        ).save()

        return Response(str(boast.id), 201)
예제 #24
0
    def post(self):
        """
        대여 글 작성
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        rq = request.form

        if len(rq['title']) < 5:
            return Response('', 205)

        rent = RentModel(category=rq['category'],
                         author=user,
                         hour_price=rq['hour_price'],
                         day_price=rq['day_price'],
                         title=rq['title'],
                         content=rq['content']).save()

        return Response(str(rent.id), 201)
예제 #25
0
    def get(self, code):
        """
        이메일 인증 URL
        """
        redis_client = current_app.config['REDIS_CLIENT']

        email = redis_client.get(code)

        if not email:
            abort(401)

        user = AccountModel.objects(email=email).first()

        if not user:
            abort(401)

        user.update(email_certified=True)

        redis_client.delete(code)

        return Response('Welcome!', 201)
예제 #26
0
    def get(self):
        """
        파티 글 읽기
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        party_id = request.form['party_id']
        party = PartyModel.objects(id=party_id).first()
        if not party:
            return Response('', 204)

        response = {
            'id':
            party.id,
            'longitude':
            party.longitude,
            'latitude':
            party.latitude,
            'author_id':
            party.author.id,
            'author_nickname':
            party.author.nickname,
            'author_phone':
            party.author.phone,
            'title':
            party.title,
            'content':
            party.content,
            'participants': [{
                'participant_id': participant.id,
                'participant_nickname': participant.nickname,
                'participant_phone': participant.phone
            } for participant in party.participants]
        }

        return Response(json.dumps(response, ensure_ascii=False),
                        200,
                        content_type='application/json; charset=utf8')
예제 #27
0
    def get(self):
        """
        파티 리스트 불러오기
        """
        user = AccountModel.objects(id=get_jwt_identity()).first()
        if not user:
            abort(403)

        parties = PartyModel.objects()
        if not parties.first():
            return Response('', 204)

        response = [{
            'id': party.id,
            'latitude': party.latitude,
            'longitude': party.longitude,
            'title': party.title,
        } for party in parties]

        return Response(json.dumps(response, ensure_ascii=False),
                        200,
                        content_type='application/json; charset=utf8')
예제 #28
0
    def get(self, email):
        """
        이메일 재전송
        """
        if not AccountModel.objects(email=email):
            return Response('', 204)

        mail_client = current_app.config['MAIL_CLIENT']

        code = generate_email_certification_code(email)

        msg = Message('Please verify user email',
                      sender=current_app.config['MAIL_USERNAME'],
                      recipients=[email])
        msg.html = '<a href="http://{0}:{1}/certify/{2}">인증하기</a>'.format(
            current_app.config['REPRESENTATIVE_HOST']
            or current_app.config['HOST'],
            current_app.config['PORT'] if not current_app.testing else 80,
            code)

        mail_client.send(msg)

        return Response('', 200)
예제 #29
0
    def testAuthSuccessWithSignup(self):
        # (1) 로그인
        resp = self._request()

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

        # (3) response data
        data = resp.json

        self.assertIn('accessToken', data)
        self.assertIn('refreshToken', data)

        access_token = data['accessToken']
        refresh_token = data['refreshToken']

        self.assertIsInstance(access_token, str)
        self.assertIsInstance(refresh_token, str)

        self.assertRegex(data['accessToken'], self.token_regex)
        self.assertRegex(data['refreshToken'], self.token_regex)

        # (4) 데이터베이스 확인
        user = AccountModel.objects(id=self.fb_id).first()

        access_token_obj = AccessTokenModel.objects(owner=user).first()
        self.assertTrue(access_token_obj)
        self.assertEqual(
            jwt.decode(access_token, self.app.secret_key, 'HS256')['identity'],
            str(access_token_obj.identity))

        refresh_token_obj = RefreshTokenModel.objects(owner=user).first()
        self.assertTrue(refresh_token_obj)
        self.assertEqual(
            jwt.decode(refresh_token, self.app.secret_key,
                       'HS256')['identity'], str(refresh_token_obj.identity))
예제 #30
0
 def get(self, id):
     """
     자체 계정 ID 중복체크
     """
     return Response('', 409 if AccountModel.objects(id=id) else 200)