Example #1
0
def update_account(request, pk):
    account = get_account_object(pk)
    serializer = AccountSerializer(account, data=request.DATA)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #2
0
 def get(self, request):
     try:
         current_account = CurrentAccount.objects.get(user=request.user)
         serializer = AccountSerializer(current_account.account)
     except CurrentAccount.DoesNotExist:
         account = Account.objects.filter(holders__in=[request.user]).first()
         CurrentAccount.objects.create(user=request.user, account=account)
         serializer = AccountSerializer(account)
     return redirect("accounts", slug=serializer.data["slug"])
Example #3
0
 def get(self, request):
     try:
         current_account = CurrentAccount.objects.get(user=request.user)
         serializer = AccountSerializer(current_account.account)
     except CurrentAccount.DoesNotExist:
         account = Account.objects.filter(
             holders__in=[request.user]).first()
         CurrentAccount.objects.create(user=request.user, account=account)
         serializer = AccountSerializer(account)
     return Response(serializer.data, status=status.HTTP_200_OK)
Example #4
0
 def get(self, request):
     slug = request.query_params.get('slug')
     if slug is not None:
         try:
             account = Account.objects.get(holders__in=[request.user], slug=slug)
             serializer = AccountSerializer(account)
         except Account.DoesNotExist:
             raise Http404
     else:
         accounts = Account.objects.filter(holders__in=[request.user]).order_by('slug')
         serializer = AccountSerializer(accounts, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Example #5
0
def account_create(request):
    """
    Creates a new Account and saves it in the database.

    Args:
            request (Request): An object containing data needed to create a new Account.

    Returns:
            Reponse: An HTTP response indicating that the new Account was successfully saved in the database or that there
            was an error and the Account object was not created.
    """
    data = request.data
    if 'loc' in data:
        loc_data = data.pop('loc')
        if type(
                loc_data
        ) == dict:  # If we've got a dict, that means the Location object should be created from the lat/lng
            loc_serializer = LocationSerializer(data=loc_data)
            if loc_serializer.is_valid():
                loc_obj = loc_serializer.save()
                data['cur_loc'] = loc_obj.loc_id
            else:
                return Response(
                    {
                        'STATUS': '1',
                        'REASON': 'LOCATION SERIALIZER ERROR',
                        'ERRORS': {
                            **loc_serializer.errors
                        }
                    },
                    status=status.HTTP_400_BAD_REQUEST)
        else:  # For testing purposes, don't create a Location object but just toss in an existing primary key
            data['cur_loc'] = loc_data
    acc_serializer = AccountSerializer(data=data)
    if acc_serializer.is_valid():
        acc_obj = acc_serializer.save()
        return Response(
            {
                'STATUS': '0',
                'REASON': 'SUCCESSFULLY CREATED ACCOUNT OBJECT',
                'user_id': acc_obj.user_id
            },
            status=status.HTTP_200_OK)
    else:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'ACCOUNT SERIALIZER ERROR',
                'ERRORS': {
                    **acc_serializer.errors
                }
            },
            status=status.HTTP_400_BAD_REQUEST)
Example #6
0
 def post(self, request, id, format=None):
     serializer = AccountSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         response = Response(serializer.data,
                             status=status.HTTP_201_CREATED)
         Log.objects.create(request=request.get_full_path,
                            response=response)
         return response
     response = Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     Log.objects.create(request=request.get_full_path, response=response)
     return response
Example #7
0
 def retrieve(self, request, user__username=None):
     account = get_account(username=user__username)
     if (self.request.user == account.user):
         serializer = AccountSerializer(account)
     else:
         serializer = AccountListSerializer(account)
     return Response(serializer.data)
Example #8
0
 def get(self, request, format=None):
     account = Account.objects.all()
     serializer = AccountSerializer(account,
                                    many=True,
                                    context={"request": request})
     response = Response(serializer.data)
     Log.objects.create(request=request.get_full_path, response=response)
     return response
def account_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        account = Account.objects.get(pk=pk)
    except Account.DoesNotExist:
        return HttpResponse(json.dumps({'responseCode': 404}), status=404)

    if request.method == 'GET':
        serializer = AccountSerializer(account)
        data = {
            'responseCode': 0,
            'responseDesc': 'Success',
            'accounts': serializer.data
        }
        return JsonResponse(data, safe=False)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = AccountSerializer(account, data=data)
        if serializer.is_valid():
            serializer.save()
            data = {'responseCode': 0, 'responseDesc': 'Success'}
            return JsonResponse(data, safe=False)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        account.delete()
        data = {'responseCode': 0, 'responseDesc': 'Success'}
        return JsonResponse(data, safe=False)
Example #10
0
class ChannelSerializer(serializers.ModelSerializer):
    owner = AccountSerializer(many=False)
    image_url = serializers.SerializerMethodField('get_image_url')

    def get_image_url(self, obj):
        return obj.image.url
    class Meta:
        model = apps.get_model('channel.Channel')
        fields = ('id', 'name', 'description', 'rules', 'owner', 'image_url')
Example #11
0
 def retrieve(self, request, pk):
     try:
         account = validate_account(pk)
         return Response(AccountSerializer(account).data)
     except KeyError as e:
         raise ValidationError({
             'code': -100,
             'message': '%s is required' % e
         })
Example #12
0
 def get(self, request):
     account = Account.get(request.GET.get('user'))
     if account and account.confirm_email(request.GET.get('code')):
         return Response({
             'account': AccountSerializer(account).data,
             'token': account.token(),
             'message': 'Email подтверждён'
         })
     return Response({'error': 'Неверная ссылка'})
Example #13
0
 def get(self, request):
     """
     Return a list of ALL IdentityMemberships found on provider_uuid
     """
     user = request.user
     memberships = IdentityMembership.objects.filter(
         identity__provider__cloudadministrator__user=user).order_by(
             'member__name')
     serializer = AccountSerializer(memberships, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Example #14
0
 def get(self, request, username):
     """
     Detailed view of all identities for provider,user combination.
     username -- The username to match identities
     """
     user = request.user
     memberships = IdentityMembership.objects.filter(
         identity__provider__cloudadministrator__user=user,
         identity__created_by__username=username).order_by('member__name')
     serializer = AccountSerializer(memberships, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
Example #15
0
 def create(self, request):
     try:
         identity_key = base64.b64decode(request.data['identity_key'])
         signed_pre_key = base64.b64decode(request.data['signed_pre_key'])
         account = Account(identity_key=identity_key,
                           signed_pre_key=signed_pre_key)
         account.save()
         return Response(AccountSerializer(account).data)
     except KeyError as e:
         raise ValidationError({
             'code': -100,
             'message': '%s is required' % e
         })
Example #16
0
 def get(self, request):
     account = Account.get(request.GET.get('user'))
     code = request.GET.get('code')
     token = account.token()[6:]
     if not account or not code or code != token:
         return Response({'error': 'Неверная ссылка'})
     return Response({
         'account':
         AccountSerializer(account).data,
         'token':
         account.token(new=True),
         'message':
         'Доступ восстановлен. Рекомендуем установить новый пароль'
     })
Example #17
0
def login(request):
    try:
        received_json_data = json.loads(request.body)
        u = User(spotify_id=received_json_data['spotifyId'])
        u.account_type = received_json_data['account_type']
        u.user_name = received_json_data["username"]
        u.email = received_json_data["email"]
    except ValueError:
        return HttpResponse("Inavlid Json", status=403)

    if u.last_token_spotify != received_json_data["spotifyToken"]:
        u.last_token_spotify = received_json_data["spotifyToken"]
        if u.check_token_spotify():
            u.save()
            serializer = AccountSerializer(u, many=False)
            return JSONResponse(serializer.data)

    return HttpResponse("Spotify user not valid", status=400)
Example #18
0
    def get(self, request):
        try:
            email = request.query_params.get('email')
            account = Account.objects.filter(email=email)

            serializer = AccountSerializer(account, many=True)
            return Response(data={
                "msg": 'Success!',
                "error_code": 0,
                "data": serializer.data
            },
                            status=status.HTTP_200_OK)

        except Exception as e:
            return Response(data={
                "msg": repr(e),
                "error_code": 500
            },
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def account_login(request):
    if request.method == 'POST':
        body = JSONParser().parse(request)
        username = body['username']
        password = body['password']
        print("username: {}, password: {}".format(username, password))
        try:
            account = AccountSerializer(
                Account.objects.get(username__exact=username))
            if (account.data['password'] == password):
                data = {
                    'responseCode': 0,
                    'responseDesc': 'Success',
                    'id': account.data['id'],
                    'username': account.data['username']
                }
            else:
                data = {
                    'responseCode': 1001,
                    'responseDesc': 'Incorrect password'
                }
        except ObjectDoesNotExist:
            data = {'responseCode': 404, 'responseDesc': 'User not found'}
        return JsonResponse(data, safe=False)
def account_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        accounts = Account.objects.all()
        serializer = AccountSerializer(accounts, many=True)
        data = {
            'responseCode': 0,
            'responseDesc': 'Success',
            'accounts': serializer.data
        }
        return JsonResponse(data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        print("JSON BODY: " + str(data))
        serializer = AccountSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            data = {'responseCode': 0, 'responseDesc': 'Success'}
            return JsonResponse(data, safe=False)
        return JsonResponse(serializer.errors, status=400)
def account_register(request):
    if request.method == 'POST':
        body = JSONParser().parse(request)
        username = body['username']
        password = body['password']
        username_available = False
        password_available = False
        try:
            AccountSerializer(Account.objects.get(username__exact=username))
        except ObjectDoesNotExist:
            username_available = True
        try:
            AccountSerializer(Account.objects.get(password__exact=password))
        except ObjectDoesNotExist:
            password_available = True

        if (username_available and password_available):
            serializer = AccountSerializer(data=body)
            if (serializer.is_valid()):
                serializer.save()
            data = {'responseCode': 0, 'responseDesc': 'Success'}
        elif (not username_available and not password_available):
            data = {
                'responseCode': 3,
                'responseDesc': 'Username and Password not available'
            }
        elif (not password_available):
            data = {
                'responseCode': 2,
                'responseDesc': 'Password not available'
            }
        else:
            data = {
                'responseCode': 1,
                'responseDesc': 'Username not available'
            }
        return JsonResponse(data, safe=False)
Example #22
0
def account_updatelocation(request):
    """
    Updates the location associated with an account.

    Args:
        request (Request): The HTTP Request containing the user_id and lat/lng field that needs to be updated.

    Returns:
        Reponse: The reponse denoting success or failure of the update.
    """

    data = request.data
    if 'user_id' not in data:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'MISSING REQUIRED USER_ID ARGUMENT'
            },
            status=status.HTTP_400_BAD_REQUEST)
    if 'lat' not in data or 'lng' not in data:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'MISSING REQUIRED LAT/LNG ARGUMENTS'
            },
            status=status.HTTP_400_BAD_REQUEST)
    try:
        acc_obj = Account.objects.get(user_id=data['user_id'])
        # No partial=True since we always need to specify a full location
        loc_serializer = LocationSerializer(acc_obj.cur_loc, data=data)
        if loc_serializer.is_valid():
            loc_obj = loc_serializer.save()
            # No location currently associated with account [either never existed or nothing currently there], assign the two together
            if acc_obj.cur_loc is None:
                acc_serializer = AccountSerializer(
                    acc_obj, data={'cur_loc': loc_obj.loc_id}, partial=True)
                if acc_serializer.is_valid():
                    acc_serializer.save()
                else:
                    return Response(
                        {
                            'STATUS': '1',
                            'REASON': 'ACCOUNT SERIALIZER ERROR',
                            'ERRORS': {
                                **acc_serializer.errors
                            }
                        },
                        status=status.HTTP_400_BAD_REQUEST)
            return Response(
                {
                    'STATUS': '0',
                    'REASON': 'ACCOUNT LOCATION SUCCESSFULLY UPDATED'
                },
                status=status.HTTP_200_OK)
        else:
            return Response(
                {
                    'STATUS': '1',
                    'REASON': 'LOCATION SERIALIZER ERROR',
                    'ERRORS': {
                        **loc_serializer.errors
                    }
                },
                status=status.HTTP_400_BAD_REQUEST)
    except Account.DoesNotExist:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'NO ACCOUNT EXISTS WITH GIVEN USER_ID'
            },
            status=status.HTTP_400_BAD_REQUEST)
Example #23
0
def account_update(request):
    """
    Updates the information in an existing Account within the database.

    Args:
        request (Request): An object containing the new data to be placed into the Account object.

    Returns:
        Response: An HTTP response that indicates whether the Account was successfully updated or if there was an error.
    """

    data = request.data
    if 'email' not in data:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'MISSING REQUIRED EMAIL ARGUMENT'
            },
            status=status.HTTP_400_BAD_REQUEST)
    try:
        acc_obj = Account.objects.get(email=data['email'])
    except Account.DoesNotExist:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'NO ACCOUNT EXISTS WITH GIVEN USER_ID'
            },
            status=status.HTTP_400_BAD_REQUEST)
    if 'loc' in data:
        loc_data = data.pop('loc')
        loc_serializer = LocationSerializer(acc_obj.cur_loc, data=loc_data)
        if loc_serializer.is_valid():
            loc_obj = loc_serializer.save()
            if acc_obj.cur_loc is None:  # Since location is optional on registration, we might need to assign a location ID if it's null in the existing object
                data['cur_loc'] = loc_obj.loc_id
        else:
            return Response(
                {
                    'STATUS': '1',
                    'REASON': 'LOCATION SERIALIZER ERROR',
                    'ERRORS': {
                        **loc_serializer.errors
                    }
                },
                status=status.HTTP_400_BAD_REQUEST)
    acc_serializer = AccountSerializer(acc_obj, data=data, partial=True)
    if acc_serializer.is_valid():
        acc_serializer.save()
        return Response(
            {
                'STATUS': '0',
                'REASON': 'SUCCESSFULLY UPDATED ACCOUNT'
            },
            status=status.HTTP_200_OK)
    return Response(
        {
            'STATUS': '1',
            'REASON': 'ACCOUNT SERIALIZER ERROR',
            'ERRORS': {
                **acc_serializer.errors
            }
        },
        status=status.HTTP_400_BAD_REQUEST)
Example #24
0
 def get(self, request, id, format=None):
     account = self.get_object(id)
     serializer = AccountSerializer(account, context={"request": request})
     response = Response(serializer.data)
     Log.objects.create(request=request.get_full_path, response=response)
     return response
Example #25
0
def create_account(request):
    serializer = AccountSerializer(data=request.DATA)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #26
0
 def post(self, request):
     serializer = AccountSerializer(data=request.data)
     if serializer.is_valid():
         result = serializer.save()
         return Response(result, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #27
0
 def response(account):
     return Response({
         'token': account.token(),
         'account': AccountSerializer(account).data
     })
Example #28
0
 def post(self, request):
     account = request.user.account.update(**request.data)
     if request.data.get('password'):
         return Response({'token': account.token()})
     return Response(AccountSerializer(account).data)
Example #29
0
 def get(self, request):
     account = request.user.account
     return Response(AccountSerializer(account).data)