コード例 #1
0
ファイル: views.py プロジェクト: tino1b2be/LARMAS
    def get(self, request, id=0):
        """
        Show user details
        :param request:
        :return:
        """
        try:
            if request.user.is_staff:
                try:
                    if id == 0:
                        id = request.user.id
                    s = User.objects.get(id=id)
                    user_profile = UserProfile.objects.get(user=s)
                    s = UserProfileSerializer(user_profile)
                    return Response(s.data, status=HTTP_200_OK)
                except ObjectDoesNotExist:
                    data = {'detail': 'User does not exist'}
                    return Response(data, status=HTTP_400_BAD_REQUEST)

            elif (id == 0) or (id == str(request.user.id)):
                user_profile = UserProfile.objects.get(user=request.user)
                s = UserProfileSerializer(user_profile)
                return Response(s.data, status=HTTP_200_OK)
            else:
                return Response(status=HTTP_403_FORBIDDEN)
        except Exception as e:
            data = {'detail': str(e) if DEBUG else 'Something went wrong.'}
            return Response(data, status=HTTP_500_INTERNAL_SERVER_ERROR)
コード例 #2
0
class FriendShipSerializer(serializers.ModelSerializer):
    user_1 = UserProfileSerializer(many=False, read_only=True)
    user_2 = UserProfileSerializer(many=False, read_only=True)

    class Meta:
        model = FriendShip
        fields = ("id", "user_1", "user_2", "status")
コード例 #3
0
ファイル: views.py プロジェクト: MrDiben/theplacetoeat
    def list(self, request):
        """ List all user friends based on accepted invitations """

        user_profile = get_object_or_404(UserProfile, user=request.user)
        #   Get all sent accepted invitations
        sent = user_profile.creator_friendships.filter(status=1)
        #   Get all received accepted invitations
        received = user_profile.invited_friendships.filter(status=1)
        #    Combine results to get all friends:
        friends = []
        for friendship in sent:
            friends.append(UserProfileSerializer(friendship.user_2).data)
        for friendship in received:
            friends.append(UserProfileSerializer(friendship.user_1).data)
        return Response(friends, status=rest_status.HTTP_200_OK)
コード例 #4
0
    def create_github_user(self, request):
        github_data = get_github_data(request.data.get("github_token"))
        if github_data is None or github_data.get("id") is None:
            return Response(
                {"message": "Invalid github token"}, status=status.HTTP_400_BAD_REQUEST
            )
        github_id = int(github_data["id"])
        if UserProfile.objects.filter(github_id=github_id).exists():
            return Response(
                {"message": "User already signed up"},
                status=status.HTTP_400_BAD_REQUEST,
            )

        user = User.objects.create_user(
            username=f"{GITHUB}_{github_id}",
            password="******",
            email=github_data.get("email", ""),
        )
        request_data = request.data.copy()
        request_data["nickname"] = github_data["login"]
        request_data["github_id"] = github_id
        request_data["user_id"] = user.id
        Token.objects.create(user=user)
        serializer = UserProfileProduceSerializer(data=request_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        data = UserProfileSerializer(user.profile).data
        data["token"] = user.auth_token.key
        return Response(data, status=status.HTTP_201_CREATED)
コード例 #5
0
    def get_location(self, request, pk=None):

        if pk != 'me':
            return Response({"error": "Can't get other Users location"},
                            status=status.HTTP_400_BAD_REQUEST)

        data = get_area_information(request.data)

        if data['error_occured'] == "latlng_miss":
            return Response({"message": "latalang information is required"},
                            status=status.HTTP_400_BAD_REQUEST)

        if data['error_occured'] == "api response not OK":
            return Response({"error": "Can't get location"},
                            status=status.HTTP_400_BAD_REQUEST)

        if data['error_occured'] == "something is wrong":
            return Response({"error": "Can't get location"},
                            status=status.HTTP_400_BAD_REQUEST)

        user = request.user
        userprofile_data = UserProfileSerializer(user.userprofile).data

        user_area = userprofile_data["area"]
        cur_area = data["formatted_address"]

        #print(user_area)
        #print(cur_area)

        if user_area != cur_area:
            return Response({"error": "Could not match area"},
                            status=status.HTTP_400_BAD_REQUEST)

        return Response(data, status=status.HTTP_200_OK)
コード例 #6
0
ファイル: views.py プロジェクト: DarrenTian/instyle
 def get_profile(self, request):
     user = request.user
     token, created = Token.objects.get_or_create(user=user)
     return Response({
         'token': token.key,
         'profile': UserProfileSerializer(user).data,
     }, status=status.HTTP_200_OK)
コード例 #7
0
class UploadPhotoSerializer(serializers.ModelSerializer):

    owner = UserProfileSerializer(required=False)
    store = StoreSerializer(required=False)

    class Meta:
        model = UploadPhoto
        fields = ('file', 'created_at', 'store', 'owner')
コード例 #8
0
ファイル: views.py プロジェクト: KinKir/VirtualJudge
 def get(self, request, **kwargs):
     if request.user and request.user.is_authenticated:
         user_profile = UserProfile.objects.get(username=request.user)
         serializer = UserProfileSerializer(user_profile)
         res_data = serializer.data
         res_data['email'] = hashlib.md5(
             str(res_data['email']).encode('utf-8')).hexdigest()
         return Response(res_format(res_data, status=Message.SUCCESS))
     return Response(res_format('Login required', status=Message.ERROR))
コード例 #9
0
def get_about_me(request):
    if request.user.is_authenticated():
        # PATCH = update username
        if request.method == "PATCH":
            serializer = UserProfileSerializer(
                request.user,
                request.data,
                partial=True,
            )
            if serializer.is_valid():
                serializer.save()
        # generate user's data (username + stats)
        user_stats = Game.get_user_stats(request.user)
        return Response(user_stats, status=200)
    else:
        return Response(
            {'detail': 'Authentication credentials were not provided.'},
            status=403)
コード例 #10
0
ファイル: views.py プロジェクト: DarrenTian/instyle
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data,
                                        context={'request': request})
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     token, created = Token.objects.get_or_create(user=user)
     return Response({
         'token': token.key,
         'profile': UserProfileSerializer(user).data,
     })
コード例 #11
0
 def get(self, request, *args, **kwargs):
     if request.user and request.user.is_authenticated:
         try:
             user = UserProfile.objects.get(username=request.user)
             return Response(
                 res_format(UserProfileSerializer(user).data,
                            status=Message.SUCCESS))
         except:
             return Response(res_format('System Error', Message.ERROR))
     return Response(res_format('Login required', Message.ERROR))
コード例 #12
0
ファイル: serializers.py プロジェクト: MrDiben/theplacetoeat
class MealSerializer(serializers.ModelSerializer):
    creator = UserProfileSerializer(many=False, read_only=True)
    restaurant = LightRestaurantSerializer(many=False, read_only=True)
    closed = serializers.SerializerMethodField()

    class Meta:
        model = Meal
        fields = ("creator", "datehour", "restaurant", "closed")

    def get_closed(self, meal):
        return not meal.datehour.date() == datetime.today().date()
コード例 #13
0
ファイル: serializers.py プロジェクト: MrDiben/theplacetoeat
class InvitationMealSerializer(serializers.ModelSerializer):
    user = UserProfileSerializer(many=False, read_only=True)
    meal = MealSerializer(many=False, read_only=True)
    is_creator = serializers.SerializerMethodField()

    class Meta:
        model = InvitationMeal
        fields = ("pk", "user", "meal", "status", "note", "is_creator")

    def get_is_creator(self, invitation_meal):
        return invitation_meal.meal.creator == invitation_meal.user
コード例 #14
0
class SubCommentSerializer(serializers.ModelSerializer):
    """
    子评论以list显示出来
    """
    # article = serializers.PrimaryKeyRelatedField(read_only=True)
    all_sub_comment = CommentSerializer(many=True)
    user = UserProfileSerializer()

    class Meta:
        model = Comment
        fields = '__all__'
コード例 #15
0
ファイル: views.py プロジェクト: DarrenTian/instyle
    def sign_up(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            if user:
                token = Token.objects.create(user=user)
                return Response({
                    'token': token.key,
                    'profile': UserProfileSerializer(user).data,
                }, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
コード例 #16
0
ファイル: views.py プロジェクト: KinKir/VirtualJudge
 def post(self, request, **kwargs):
     serializer = LoginSerializer(data=request.data)
     if serializer.is_valid():
         user = serializer.login(request)
         if user:
             return Response(res_format(
                 UserProfileSerializer(user).data, Message.SUCCESS),
                             status=status.HTTP_200_OK)
         else:
             return Response(
                 res_format('Incorrect username or password',
                            Message.ERROR))
     return Response(res_format(serializer.errors, Message.ERROR))
コード例 #17
0
ファイル: views.py プロジェクト: KinKir/VirtualJudge
 def post(self, request, *args, **kwargs):
     if request.user and request.user.is_authenticated:
         serializer = ChangePasswordSerializer(data=request.data)
         if serializer.is_valid():
             user = serializer.save()
             if user is not None:
                 return Response(
                     res_format(UserProfileSerializer(user).data,
                                status=Message.SUCCESS))
             return Response(
                 res_format('Change password failed', status=Message.ERROR))
         return Response(res_format(serializer.errors,
                                    status=Message.ERROR))
     return Response(res_format('Login required', status=Message.ERROR))
コード例 #18
0
def jwt_response_payload_handler(token, user=None, request=None):
    """
    登录成功后自定义返回
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        "status": "ok",
        'user': UserProfileSerializer(user, context={
            'request': request
        }).data,
        "token": token
    }
コード例 #19
0
    def update(self, request, pk=None):
        if pk != "me":
            return Response(
                {"message": "Not allowed to edit user not me"},
                status=status.HTTP_403_FORBIDDEN,
            )

        user = request.user
        data = request.data

        serializer = self.get_serializer(user, data=data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        data = UserProfileSerializer(user.profile).data
        return Response(data, status=status.HTTP_200_OK)
コード例 #20
0
ファイル: views.py プロジェクト: DarrenTian/instyle
 def update_profile(self, request):
     user = request.user
     profile = request.data
     user.nickname = profile['nickname']
     user.biography = profile['biography']
     token, created = Token.objects.get_or_create(user=user)
     try:
         user.save()
     except Exception as e:
         return Response({
             'error': "Please try another one",
         }, status=status.HTTP_400_BAD_REQUEST)
     return Response({
         'token': token.key,
         'profile': UserProfileSerializer(user).data,
     }, status=status.HTTP_200_OK)
コード例 #21
0
    def create(self, request):
        request_data = request.data.copy()

        github_token = request_data.get("github_token")

        if github_token is not None:
            return self.create_github_user(request)

        request_data.pop("github_id", None)
        serializer = self.get_serializer(data=request_data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        data = UserProfileSerializer(user.profile).data
        data["token"] = user.auth_token.key
        return Response(data, status=status.HTTP_201_CREATED)
コード例 #22
0
class ReportDataPOSTSerializer(serializers.ModelSerializer):

    owner = UserProfileSerializer(required=False)
    store = StoreSerializer(required=False)
    assortment = ReportItemPOSTSerializer(many=True)

    class Meta:
        model = ReportData
        fields = ('id', 'name', 'owner', 'store', 't_start', 't_finish',
                  't_delta', 'assortment_percent', 'assortment', 'created_at')

    def create(self, validated_data):
        assortments_data = validated_data.pop('assortment')
        report = ReportData.objects.create(**validated_data)
        for assortment_data in assortments_data:
            ReportItem.objects.create(report=report, **assortment_data)
        return report
コード例 #23
0
ファイル: custom_jwt.py プロジェクト: Safoniks/Seamstress
def jwt_response_payload_handler(token, user=None, request=None):
    url_name = request.resolver_match.url_name

    if url_name == 'login-worker':
        if MyUser.is_worker(user):
            return {
                'token': token,
                'worker': PublicWorkerDetailSerializer(user.worker).data,
                'scope': MyUser.get_scope(user),
            }
        raise ValidationError({"detail": "Must be a worker."})
    elif url_name == 'login-admin':
        if MyUser.is_director(user) or MyUser.is_technologist(user):
            return {
                'token': token,
                'user': UserProfileSerializer(user).data,
                'scope': MyUser.get_scope(user),
            }
        raise ValidationError({"detail": "Must be an admin."})
コード例 #24
0
ファイル: views.py プロジェクト: tino1b2be/LARMAS
    def post(self, request):
        """
        View to update user's details
        :param request:
        :return:
        """
        try:
            if request.user.is_staff:
                note = 'Admin users cannot modify their details via API'
                data = {'detail': note}
                return Response(data, status=HTTP_400_BAD_REQUEST)
            d = request.POST
            user = request.user
            user_profile = UserProfile.objects.get(user=user)
            user.email = d.get('email', user.email)
            user.first_name = d.get('first_name', user.first_name)
            user.last_name = d.get('last_name', user.last_name)

            l1 = d.get('first_language', 0)
            l2 = d.get('second_language', 0)
            l3 = d.get('third_language', 0)

            if l1 != 0:
                l11 = Language.objects.get(code=l1)
                user_profile.first_language = l11
            if l2 != 0:
                l22 = Language.objects.get(code=l2)
                user_profile.second_language = l22
            if l3 != 0:
                l33 = Language.objects.get(code=l3)
                user_profile.third_language = l33

            user.save()
            user_profile.save()
            s = UserProfileSerializer(user_profile)
            return Response(s.data, status=HTTP_200_OK)
        except ObjectDoesNotExist:
            data = {'detail': 'Language does not exist.'}
            return Response(data, status=HTTP_400_BAD_REQUEST)
        except Exception as e2:
            data = {'detail': str(e2) if DEBUG else 'Something went wrong'}
            return Response(data, status=HTTP_500_INTERNAL_SERVER_ERROR)
コード例 #25
0
ファイル: views.py プロジェクト: iamonuwa/BountiesAPI
    def post(self, request, public_address):
        user = request.current_user

        user.profile_touched_manually = True

        serializer = UserProfileSerializer(user, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        user.save_and_clear_skills(request.data.get('skills'))
        user.save_and_clear_languages(request.data.get('languages'))

        user.save()

        notification_client.profile_updated(user.public_address.lower())
        seo_client.profile_preview_screenshot(user.id)

        return JsonResponse(UserProfileSerializer(user).data)
コード例 #26
0
ファイル: views.py プロジェクト: mmisiewicz/BountiesAPI
    def post(self, request, public_address):
        user = request.current_user

        user.profile_touched_manually = True
        user.is_profile_image_dirty = request.data.get('profileDirectoryHash') != str(user.profileDirectoryHash)

        serializer = UserProfileSerializer(user, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        user.save_and_clear_skills(request.data.get('skills'))
        user.save_and_clear_languages(request.data.get('languages'))

        user.save()

        notification_client.profile_updated(user.public_address.lower())

        return JsonResponse(UserProfileSerializer(user).data)
コード例 #27
0
ファイル: views.py プロジェクト: MrDiben/theplacetoeat
    def accept_invitation(self, request):
        pk = request.GET.get("pk")
        if not pk:
            return Response(status=rest_status.HTTP_404_NOT_FOUND)

        user = get_object_or_404(UserProfile, user=request.user)
        friendship = get_object_or_404(FriendShip, pk=pk)

        #    Avoid self friendship
        if not friendship.user_2 == user:
            return Response(status=rest_status.HTTP_404_NOT_FOUND)

        #   Accept friend invitation
        friendship.status = 1
        friendship.save()

        serializer = UserProfileSerializer(friendship.user_1)
        data = {"message": "OK", "content": serializer.data}

        return Response(data, status=rest_status.HTTP_200_OK)
コード例 #28
0
ファイル: views.py プロジェクト: DarrenTian/instyle
    def set_avatar_image(self, request):
        user = request.user
        token, created = Token.objects.get_or_create(user=user)
        file = request.data['file']
        name, extension = os.path.splitext(file.name)
        thumbnail_file = self._compress_image(file)

        if user.avatar_image!="default/logo_transparent.png":
            user.avatar_image.delete()

        time_suffix = str(int(time.time()))
        avatar_image_url = 'avatar/'+user.user_id + '-' + time_suffix
        avatar_image_thumbnail = 'avatar/'+user.user_id + '-' + time_suffix + '-' + 'thumbnail'
        if settings.PROD_ENV == 'DEV':
            avatar_image_url = 'dev/' + avatar_image_url
            avatar_image_thumbnail = 'dev/' + avatar_image_thumbnail
        user.avatar_image.save(avatar_image_url + extension, file)
        user.avatar_image_thumbnail.save(avatar_image_thumbnail + extension, thumbnail_file)
        user.save()
        return Response({
            'token': token.key,
            'profile': UserProfileSerializer(user).data,
        }, status=status.HTTP_200_OK)
コード例 #29
0
ファイル: views.py プロジェクト: Liiuliu/vulfocus
 def get(self, request):
     user_info = User.objects.get(pk=request.user.id)
     serializer = UserProfileSerializer(user_info)
     return JsonResponse(serializer.data)
コード例 #30
0
ファイル: views.py プロジェクト: tino1b2be/LARMAS
    def post(self, request):
        data = {'detail': 'username field is required'}

        # check for username field
        if not request.data.__contains__('username'):
            return Response(data, status=HTTP_400_BAD_REQUEST)

        # check if username is unique
        if User.objects.filter(username=request.data['username']).exists():
            data['detail'] = 'That username already exists.'
            return Response(data, status=HTTP_400_BAD_REQUEST)

        # check for password field
        if not request.data.__contains__('password'):
            data['detail'] = 'password field is required'
            return Response(data, status=HTTP_400_BAD_REQUEST)

        # check for first language
        if not request.data.__contains__('first_language'):
            data['detail'] = 'first_language field is required'
            return Response(data, status=HTTP_400_BAD_REQUEST)

        # check if first language is valid
        code = request.data['first_language']
        if not Language.objects.filter(code=code).exists():
            data['detail'] = 'first_language entered does not exist'
            return Response(data, status=HTTP_400_BAD_REQUEST)

        try:
            # create user
            new_user = User(
                username=request.data['username'],
                email=request.data.get('email', ""),
                first_name=request.data.get('first_name', ""),
                last_name=request.data.get('last_name', ""),
            )
            new_user.set_password(request.data['password'])
            new_user.save()

            # create profile
            new_profile = UserProfile(
                user=new_user,
                first_language=Language.objects.get(code=code),
                age=request.data.get('age', 0),
            )
            try:

                code = request.data.get('second_language', 'X')
                if code == 'X':
                    # second language not entered.
                    new_profile.save()
                    s = UserProfileSerializer(new_profile)
                    return Response(s.data, status=HTTP_201_CREATED)

                # second language entered
                second_language = Language.objects.get(code=code)
                new_profile.second_language = second_language

                # add third language
                code = request.data.get('third_language', 'X')
                if code == 'X':
                    # third language not entered.
                    new_profile.save()
                    s = UserProfileSerializer(new_profile)
                    return Response(s.data, status=HTTP_201_CREATED)

                # third language entered
                third_language = Language.objects.get(code=code)
                new_profile.third_language = third_language
                new_profile.save()
                s = UserProfileSerializer(new_profile)
                return Response(s.data, status=HTTP_201_CREATED)

            except ObjectDoesNotExist:
                new_user.delete()
                data['detail'] = code + ' language code is invalid.'
                return Response(data, status=HTTP_400_BAD_REQUEST)

        except Exception as e2:
            data['detail'] = str(e2) if DEBUG else 'Something went wrong'
            return Response(data, status=HTTP_500_INTERNAL_SERVER_ERROR)