Ejemplo n.º 1
0
    def post(self, request):
        data = JSONParser().parse(request)
        access_token = data.get('access_token', '')
        gcm_token = data.get('gcm_token', '')

        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)

            # check token against facebook
            login = fb_complete_login(request, app, token)
            login.token = token
            login.user.gcm_token = gcm_token
            login.state = SocialLogin.state_from_request(request)

            # add or update the user into users table
            ret = complete_social_login(request, login)

            # if we get here we've succeeded
            return Response(status=200, data={
                'success': True,
                'username': request.user.username,
                'user_id': request.user.pk,
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email,
            })

        except:
 
            return Response(status=401 ,data={
                'success': False,
                'reason': "Bad Access Token",
            })
Ejemplo n.º 2
0
def update_name_about(request):
    """
    update name
    update about
    update contact No
    :param request:
    :return:
    """
    context = {}
    if request.method == 'POST':
        data = JSONParser().parse(request)
        user = str(request.user.id)
        name = data.get('name', None)
        about = data.get('about', None)
        contact = data.get('contact', None)
        update_about = ProfileDetails.objects.get(user_id=user)
        update_name = Account.objects.get(pk=user)
        if name is not None:
            name = name.split()
            update_name.first_name = name[0]
            update_name.last_name = name[1]
            update_name.save()
        if contact is not None:
            update_name.contact_number = contact
            update_name.save()
        if about is not None:
            update_about.about = about
            update_about.save()
        context['status'] = 'success'
        return HttpResponse(json.dumps(context))
    else:
        context['status'] = 'failed'
        return HttpResponse(json.dumps(context))
Ejemplo n.º 3
0
def update_password_new(request):

    if request.method == 'POST':
        data = JSONParser().parse(request)
        # if form.is_valid():
        password = data.get('password',None)
        confirm_password = data.get('confirm_password',None)
        key = data.get('key')
        log.info(key)
        if password != confirm_password:
            request.session['error1']= "passwords doesn't match"

        try:
            user = Account.objects.get(reset_password_key=key)
        except user.DoesNotExist:
            request.session['error1']="Invalid URL"

        if user is not None:
            user.set_password(password)
            user.reset_password_key = ''
            user.save()
            email_subject = 'Password changed for your commonproject account!'
            message = render_to_string('email/password_changed.html')
            msg = EmailMultiAlternatives(subject=email_subject, body=message,
                                         from_email="*****@*****.**", to=[user.email])
            msg.attach_alternative(message, "text/html")
            msg.send()
            request.session['error1']="password updated successfully"
            return redirect('/accounts/login/')

        else:
            request.session['error1']="password is not valid "
Ejemplo n.º 4
0
def login_user(request):
    """
    Login the current user, after authenticating the credentials.
    :param request:
    :return:
    """
    if request.method == 'POST':
        data = JSONParser().parse(request)
        email = data.get('email', None)
        password = data.get('password', None)
        account = authenticate(email=email, password=password)

        if account is not None:

            if not account.is_email_verified:
                return Response({
                    'status': 'Unverified',
                    'message': 'This account is not verified.'
                }, status=status.HTTP_401_UNAUTHORIZED)

            if not account.is_active:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)

            auth_login(request, account)
            serialized = LoginSerializer(account)
            return Response(serialized.data, status=status.HTTP_200_OK)

        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)
Ejemplo n.º 5
0
    def __init__(self, ip, *args, **kw):
        """
        :param ip: str of the ip address in the form of 1.22.333.444
        :param args: list of extra arguments, that are currently not being used
        :param kw: dict of extra arguments, that are currently not being used
        """
        # todo test that the ip is in range of 1-256
        raw, http_code = Reputation.get_details(ip)
        if raw and 200 <= http_code < 300:
            stream = BytesIO(raw)
            data = JSONParser().parse(stream)
            remote = serializers.RemoteDetailsSerializer(data=data)
            self.is_valid = remote.is_valid()
        else:
            self.is_valid = False
            data = {}

        try:
            self.http_code = http_code
            self.address = data.get('address',ip)
            self.id = data.get('id','')
            self.reputation_val = data.get('reputation_val',0)
            self.activities = [dict(activity_type=a['name'],
                                    first_date=a['first_date']['sec'],
                                    last_date=a['last_date']['sec']) for a in data.get('activities',[])
                                        if serializers.RemoteActivitiesSerializer(data=a).is_valid() ]
            self.invalid_activities_count = len(data.get('activities',[])) - len(self.activities)
            self.first_activity = self.get_activity(self.activities, 'first_date', less_than=True)
            self.last_activity = self.get_activity(self.activities, 'last_date', less_than=False)
            self.activity_types = list(set([a['activity_type'] for a in list(self.activities or [])]))
        except Exception as e:
            pass # todo more here one error handling
Ejemplo n.º 6
0
 def make_guess(self, request):
     """
     Following a player "buzzing in" this should be called to supply that
     players guess having been speech recognised. This adds the guess to the
     queued player.
     """
     data = JSONParser().parse(request)
     queue = GuessQueue.objects.all()[0]
     queue.guess = data.get('guess')
     queue.save()
     print 'Guess: %s' % data.get('guess')
     return Response({'status': 'ok'})
Ejemplo n.º 7
0
def sign_up(request):
    if request.method == 'POST':
        print("POST working")
        # serializer = AccountSerializer(data=request.data)
        request_data = JSONParser().parse(request)
        account = Account.objects.create_user(email=request_data.get('email'))
        account.first_name = request_data.get('first_name')
        account.last_name = request_data.get('last_name')
        account.gender = request_data.get('gender')
        account.set_password(request_data.get('password'))
        account.save()
        return JSONResponse(data=request_data, status=201)
Ejemplo n.º 8
0
def media_upload(request, id):
    if request.method == 'POST':
        user_id = str(request.user.id)
        user = get_object_or_404(Account, pk=user_id)
        project = user.projects_set.get(id=id)
        new_media = project.media_set.create(created=timezone.now())
        data = request.FILES.get('files')
        media_type = request.POST.get('type')
        # file_static_dir = "/static/user-temp-data/"+user_id+'/media/'+media_type+'/'
        file_static_dir = "/static/user-temp-data/{0}/projects/project_{1}/media/{2}/"\
            .format(user_id, project.id, media_type)
        name, ext = os.path.splitext(data.name)
        new_name = '{0}user_{1}_{2}_media_{3}{4}'.format(file_static_dir,
                                                         str(request.user.id),
                                                         media_type,
                                                         new_media.id,
                                                         ext)
        img_static_url = upload_save_get_url(data, new_name)
        if media_type == 'Images':
            media_type = 1
        elif media_type == 'Tracks':
            media_type = 2
        elif media_type == 'Videos':
            media_type = 3
        elif media_type == 'Articles':
            media_type = 4
        thumb_img = get_thumbnail(img_static_url, media_type)
        new_media.url=img_static_url
        new_media.thumb_img=thumb_img
        new_media.type=media_type
        new_media.save()
        db_media = Media.objects.get(pk=new_media.id)
        serial_media = MediaSerializer(db_media)
        return Response(serial_media.data, status=status.HTTP_200_OK)
    if request.method == 'PUT':
        # print 'put req'
        data = JSONParser().parse(request)
        title = data.get('title', None)
        description = data.get('description', None)
        try:
            media = Media.objects.get(pk=id)
            if title is not None:
                media.name = title
            if description is not None:
                media.description = description
            media.save()
            serial_media = MediaSerializer(media)
            return Response({'id': id, 'title': title, 'description': description})
        except Media.DoesNotExist:
            pass
            return Response({'error': 'media not available'})
Ejemplo n.º 9
0
    def buzz_in(self, request):
        """
        This method is called by the controller when a button is pressed and
        queues the player to await a guess to be made.
        """
        queue_size = len(GuessQueue.objects.all())
        if queue_size == 0:
            data = JSONParser().parse(request)
            print 'Queuing player %d' % data.get('player_id')
            new_queue = GuessQueue()
            new_queue.player = data.get('player_id')
            new_queue.save()

        return Response({'status': 'ok'})
Ejemplo n.º 10
0
def update_project_title(request, id):
    """
    create project from title;
    update of project title, type, desc(optional)

    :param request:
    :param id:
    :return:
    """
    context = {}
    if request.method == 'POST':
        data = JSONParser().parse(request)
        proj_id = id
        user_id = str(request.user.id)
        user = get_object_or_404(Account, pk=user_id)
        title = data.get('title', None)
        type = data.get('type', None)
        desc = data.get('desc', None)
        try:
            # print "try"
            update_title = Projects.objects.get(id=proj_id)
            if title is not None:
                update_title.title = title
                update_title.save()
            if type is not None:
                update_title.type = type
                update_title.save()
            if desc is not None:
                update_title.description = desc
                update_title.save()
            # print 'update'
            context['id']=id
        except Projects.DoesNotExist:
            new_project = user.projects_set.create(date_created=timezone.now(), title=data['title'])
            context['id'] = new_project.id
            file_static_dir = '{0}/static/user-temp-data/{1}/projects/project_{2}'\
                .format(PROJECT_ROOT, user.id, new_project.id)
            os.mkdir(file_static_dir)
            os.mkdir(file_static_dir + '/media')
            os.mkdir(file_static_dir + '/media/Articles')
            os.mkdir(file_static_dir + '/media/Images')
            os.mkdir(file_static_dir + '/media/Tracks')
            os.mkdir(file_static_dir + '/media/Videos')
        context['status'] = 'success'
        return HttpResponse(json.dumps(context))
    else:
        context['status'] = 'failed'
        return HttpResponse(json.dumps(context))
Ejemplo n.º 11
0
def forgot_password(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        email = data.get('email', None)
        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
        activation_key = hashlib.sha1(email+salt).hexdigest()
        try:
            # user = User.objects.get(email=email)
            user=Account.objects.get(email=email)
            log.info(user)
        except user.DoesNotExist:
            request.session['error1']="Email Id Doesn't exist"
        user.reset_password_key = activation_key
        user.save()

        email_subject = 'Reset Password.'
        activation_url = "{1}/accounts/update_password/{0}".format(activation_key, os.environ.get('HOST_NAME'))

        rendertxt = render_to_string('email/reset_password.html', {'user': user, 'activation_url': activation_url})
        msg = EmailMultiAlternatives(subject=email_subject, body=rendertxt,
                                     from_email="*****@*****.**", to=[email])
        msg.attach_alternative(rendertxt, "text/html")
        msg.send()
        response = msg.mandrill_response[0]
        mandrill_status = response['status']
        return redirect('/accounts/forget_pwd/')
Ejemplo n.º 12
0
def bo_administrator_login(self):
    try:
        logger.info('Handling /backoffice/users/login.')
        if self.method == 'POST':
            stream = BytesIO(self.body)
            data = JSONParser().parse(stream)

            credentials = dict()

            credentials['email'] = data.get('email', None)
            credentials['password'] = data['password'].encode('utf-8')

            try:
                administrator = Administrator.objects.get(email=credentials['email'], password__isnull=False, active=True)
            except Administrator.DoesNotExist:
                logger.warning('Login with administrator ({email}) failed. Administrator not found.'.format(email=credentials['email']))
                raise CustomException(CustomErrorMessages.USER_NOT_FOUND)

            if not bcrypt.hashpw(credentials['password'], administrator.password.encode('utf-8')) == administrator.password.encode('utf-8'):
                logger.warning('Login with administrator ({email}) failed. Password doesn\'t match.'.format(email=credentials['email']))
                raise CustomException(CustomErrorMessages.INVALID_CREDENTIALS)

            response = dict()
            response['token'] = jwt_util.jwt_auth_generate_token(credentials)

            return HttpResponse(json.dumps(response), status=200)
        else:
            return HttpResponse(status=405)
    except CustomException as ce:
        return HttpResponse(ce.message, status=450)
    except:
        logger.error(traceback.format_exc())
        return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
Ejemplo n.º 13
0
def bo_administrator_set_password(self):
    try:
        logger.info('Handling /backoffice/users/set-password.')
        if self.method == 'POST':
            stream = BytesIO(self.body)
            data = JSONParser().parse(stream)

            if not 'token' in data or not 'new_password' in data:
                return HttpResponse(status=401)

            token = data.get('token', None)
            new_password = data['new_password'].encode('utf-8')

            user = jwt_util.jwt_auth_get_user(token)

            hashed_password = bcrypt.hashpw(new_password, bcrypt.gensalt())

            user.password = hashed_password
            user.save()

            return HttpResponse(status=200)
        else:
            return HttpResponse(status=405)

    except CustomException as ce:
        return HttpResponse(ce.message, status=450)
    except:
        logger.error(traceback.format_exc())
        return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
Ejemplo n.º 14
0
def bo_administrator_recover_password(self):
    try:
        logger.info('Handling /backoffice/users/recover-password.')
        if self.method == 'POST':
            stream = BytesIO(self.body)
            data = JSONParser().parse(stream)

            if 'email' not in data:
                return HttpResponse(status=401)

            user_credentials = dict()

            user_credentials['email'] = data.get('email', None)

            if not Administrator.objects.filter(email=user_credentials['email']).exists():
                raise CustomException(CustomErrorMessages.USER_NOT_FOUND)

            token = jwt_util.jwt_recovery_generate_token(user_credentials)
            thread.start_new_thread(email_sender.send_password_recovery_email, (user_credentials['email'], token))
            logger.info('Recovery token: ' + str(token))

            return HttpResponse(status=200)
        else:
            return HttpResponse(status=405)

    except CustomException as ce:
        return HttpResponse(ce.message, status=450)
    except:
        logger.error(traceback.format_exc())
        return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
Ejemplo n.º 15
0
def login_user(request):
    print 'login_user call'
    if request.method == 'POST':
        data = JSONParser().parse(request)
        email = data.get('email', None)
        password = data.get('password', None)
        ac = authenticate(email=email, password=password)
        if ac is not None:
            auth_login(request, ac)
            serial = UserSerializer(ac)
            return Response(serial.data, status=status.HTTP_200_OK)
        else:
            return Response({
                'status': 'Unauthorised',
                'message': 'Wrong Username/password combination.'
            }, status=status.HTTP_401_UNAUTHORIZED)
Ejemplo n.º 16
0
	def post (self,request):
		
		original_request = request._request
		data = JSONParser().parse(request)
		access_token = data.get('access_token', '')

		try:
			app = SocialApp.objects.get(provider='facebook')
			fb_auth_token = SocialToken(app=app, token=access_token)

			login = fb_complete_login(original_request, app, fb_auth_token)
			login.token = fb_auth_token
			login.state = SocialLogin.state_from_request(original_request)

			complete_social_login(original_request, login)
			token, _ = Token.objects.get_or_create(user=original_request.user)

			
			data_response ={
			'username': original_request.user.username,
			'objectId': original_request.user.pk,
			'firstName': original_request.user.first_name,
			'lastName': original_request.user.last_name,
			'email': original_request.user.email,
			'sessionToken': token.key,
			}
			return Response(status=status.HTTP_200_OK, data=data_response)
		except:
			return Response(status=status.HTTP_401_UNAUTHORIZED,data={
				'detail': 'Bad Access Token',
				})
Ejemplo n.º 17
0
def sentiments_endpoint(request):
    """
    List all sentiments or create a new one.
    """

    if request.method == 'POST':
        data = JSONParser().parse(request)
        data['ip_address'] = get_ip(request)
        data['created'] = data.get('created') or datetime.datetime.now()
        data['twitter_user'] = '******'
        location_match = geolite2.lookup(data['ip_address'])
        if location_match:
            print(location_match.location)
            data['latitude'], data['longitude'] = location_match.location
        serializer = models.SentimentSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'GET':
        max_items = request.GET.get('max_items') or 100
        do_analyze = request.GET.get('analyze') or False

        if do_analyze:
            _do_analysis()

        sentiments = models.Sentiment.objects.filter(latitude__isnull=False)[:max_items]
        serializer = models.SentimentSerializer(sentiments, many=True)
        return JSONResponse(serializer.data)

    return JSONResponse([], status=400)
Ejemplo n.º 18
0
    def post(self, request):        
        data = JSONParser().parse(request)
        access_token = data.get('access_token', '')    
        
        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)
                            
            # return SocialLogin(account)                    
            login = fb_complete_login(app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
        
            # add or update the user
            ret = complete_social_login(request, login)

            # if we get here we've succeeded
            return Response(status=200, data={
                'success': True,
                'username': request.user.username,
                'user_id': request.user.pk,
                'csrf_token': unicode(csrf(request)['csrf_token'])
            })
            
        except:
            
            # FIXME: Catch only what is needed
            #, HttpForbidden
            return Response(status=401 ,data={
                'success': False,
                'reason': "Bad Access Token",
            })
Ejemplo n.º 19
0
    def post(self, request):
        ''' check user token '''
        token = TokenMiddleware.get_token(request)
        if token is None:
            raise NotAuthenticated("Token invalid or expired!")

        try:
            data = JSONParser().parse(request)
            data = data.get(PARAMETER_DATA)
        except JSONDecodeError:
            raise ParseError(detail="No data found on the request")
        game_type = WebRequestParameter.get_data(PARAMETER_TYPE, data)

        ''' extract user from token '''
        if not token.has_key(PARAMETER_USER):
            raise NotAuthenticated()
        ''' get user object from request '''
        user = token.get(PARAMETER_USER)
        if user is None:
            raise NotAuthenticated("User not exists!")

        score = WebRequestParameter.get_data(PARAMETER_SCORE, data)
        if not isinstance(score, list):
            raise APIException("Object must be an instance of list")
        
        ''' update user score '''
        user, score_detail = self.update_score(user, score, game_type)
        if score_detail.has_key("levelup"):
            token = TokenMiddleware.get_token(request)
            if token:
                from engine.util.const import ten_minutes_in_seconds
                cache_data = dict(uid=user.id, name=user.name, user=user)
                cache.set(user.auth_token, cache_data, ten_minutes_in_seconds)
        return Response(score_detail)
Ejemplo n.º 20
0
 def post(self, request):
     try:
         data = JSONParser().parse(request)
         data = data.get(PARAMETER_DATA)
     except JSONDecodeError:
         raise ParseError(detail="No data found on the request")
     
     ''' check all values '''
     catid    = WebRequestParameter.get_data(PARAMETER_CATEGORY, data)
     question = WebRequestParameter.get_data(PARAMETER_QUESTION, data)
     options  = WebRequestParameter.get_data(PARAMETER_OPTIONS, data)
     answer   = WebRequestParameter.get_data(PARAMETER_ANSWER, data)
     
     if not all( (catid, question, options, answer ) ):
         raise ParseError(detail="Some parameters are missing from request")
     
     ''' search for category '''
     category = Category.objects(catid = int(catid)).first()
     if category is None:
         raise APIException("Category not exists!")
     
     try:
         self.add_question(category, question, options, answer)
     except:
         traceback.print_exc()
         raise APIException("Unable to add question. Try again later!")
     return Response(True)
Ejemplo n.º 21
0
def message(request):
    identifier = request.GET.get('identifier')
    data = JSONParser().parse(request)
    iccid = data.get("iccid")
    message = data.get("message")
    if not Phone.check_auth(identifier, iccid):
        data = {"errcode": ErrCode.NOT_AUTHORIZED, "errmsg": "not authorized"}
        return JSONResponse(data=data, status=200)
    if not identifier or not Phone.objects.filter(identifier=identifier).exists():
        data = {"errcode": ErrCode.IDENTIFIER_NOT_VALID, "errmsg": "identifier not valid"}
        return JSONResponse(data=data, status=200)
    else:
        phone = Phone.objects.get(identifier=identifier)
        Message.objects.create(content=message, owner=phone.owner)
        data = {"success": True, "errorcode": ErrCode.OK}
        return JSONResponse(data=data, status=200)
Ejemplo n.º 22
0
 def post(self, request):  
      print "posting data"      
      data = JSONParser().parse(request)
      access_token = data.get('access_token', '')    
    
      try:
           print request
           app = SocialApp.objects.get(provider="facebook")
           token = SocialToken(app=app, token=access_token)
                        
           login = fb_complete_login(app, token)
           login.token = token
           login.state = SocialLogin.state_from_request(request)
           print login
           ret = complete_social_login(request, login)
           return Response(status=200, data={
            'success': True,
            'username': request.user.username,
            'user_id': request.user.pk,
        })
      except:
           return Response(status=401 ,data={
            'success': False,
            'reason': "Bad Access Token",
        })
Ejemplo n.º 23
0
    def post(self, request):
        data = JSONParser().parse(request)
        response = Response()
        email = data.get('email','')
        password = data.get('password','')

        try:
            user = authenticate(email=email, password=password)

            if user is not None:
                if user.is_active:


                  return Response(status=200, data={

                      'success': True,
                      'id':user.id,
                      'first_name':user.first_name,
                      'last_name':user.last_name,
                      'email':user.email,
                      'address':user.address,
                      'city':user.city,
                      'state':user.state,





                  })
                else:
                     return Response(status=401, data={
                      'success': False,
                      'reason' : "Please check password"
                  })

            else:
                     return Response(status=401, data={
                      'success': False,
                      'reason' : "User does not exist"
                  })

        except Exception,e:

           return Response(status=401, data={
                      'success': False,
                      'reason' : e
                  })
Ejemplo n.º 24
0
def login(request):
    data = JSONParser().parse(request)
    user = data.get('user', None)
    password = data.get('password', None)
    if user is None or password is None:
        return HttpResponse(status=400)

    try:
        user = User.objects.get(
            name=user,
            password=password,
            active=True,
        )
    except User.DoesNotExist:
        return HttpResponse(status=404)


    return JSONResponse(UserSerializer(user).data, status=200)
Ejemplo n.º 25
0
 def __call__(self, request, content_object, **kwargs):
     submit_data = {'authenticated_username': request.user.username}
     ws_delete_content_uri = settings.ZTREE_WS_BASE_URL + request.tree_context.node.absolute_path + '/delete'
     resp = dispatch_request_json(ws_delete_content_uri, method='POST', data=submit_data) 
     #resp_py = simplejson.load(StringIO(resp))
     resp_py = JSONParser().parse( BytesIO(resp) )
     if resp_py.get('status'):
         return 1 
     return 0 
Ejemplo n.º 26
0
    def post(self, request):
        """
        Create ServiceArea details

        :param request:
        :return:
        ---
        # YAML (must be separated by `---`)

        type:
            name:
                required: true
                type: string
            price:
                required: true
                type: float
            loc:
                required: true
                type: string
            provider:
                required: true
                type: string

        serializer: ServiceAreaSerializer
        omit_serializer: false

        parameters_strategy: merge
        omit_parameters:
            - path

        responseMessages:
            - code: 400
              message: Invalid Params
            - code: 201
              message: Successfully fetches the record
        """
        data = JSONParser().parse(request)
        data["name"] = data.get("loc",{}).get("properties", "").get("name", "")
        data["price"] = data.get("loc",{}).get("properties", "").get("price", "")
        serializer = ServiceAreaSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 27
0
def login_view(request):
    if request.method == 'GET':
        next = request.GET.get('next', reverse('index'))
        context = {'LogStatus': True, 'next': next}
        context.update(getCommonContext(request))
        return render(request, 'nomnom/login.html', context)
    else:
        data = JSONParser().parse(request)
        username = data.get('username')
        password = data.get('password')
        next = data.get('next', reverse('index'))
        user = authenticate(username=username, password=password)
        if (user is not None) and (user.is_active):
            login(request, user)
            return HttpResponseRedirect(next)
        else:
            context = {'LogStatus': True, 'next': next}
            context.update(getCommonContext(request))
            return render(request, 'nomnom/login.html', context, status=status.HTTP_401_UNAUTHORIZED)
Ejemplo n.º 28
0
def comment_approve(request):
    if request.method=='POST':
        try:
            data = JSONParser().parse(request)
            
            action = data.get('action')
            pks = data.get("selection")
            comment_ids =[]
            for pk in pks:
                comment_ids.append(int(pk))
            
            print action
            if len(comment_ids):
                objs = Comment.objects.filter(pk__in=comment_ids)

                if action == u'Approve':
                    print "LOGS: Promote the given comments"
                    for obj in objs:
                        obj.published = True
                        obj.save()
                elif action == u'Unpublish':
                    print "LOGS: Unpublish the given comments"
                    for obj in objs:
                        obj.published = False
                        obj.save()
                elif action == u'Delete':
                    print "LOGS: Delete the given comments"
                    for obj in objs:
                        obj.delete()
                else:
                    print "LOGS: Nothing"
                    return JSONResponse(pks, status=HTTP_400_BAD_REQUEST)
            return JSONResponse(pks, status=HTTP_200_OK)
        
        except:
            print 'Some exception occurred.'
            print "Unexpected error:", sys.exc_info()[0]
            for frame in traceback.extract_tb(sys.exc_info()[2]):
                fname,lineno,fn,text = frame
                print "Error in %s on line %d" % (fname, lineno)
            return JSONResponse(None, status=HTTP_400_BAD_REQUEST)
Ejemplo n.º 29
0
def guest_login(request):
    if request.method == "GET":
        content = JSONRenderer().render(
            [{"name": "firstName", "type": "text", "label": "First Name"},
             {"name": "lastName", "type": "password", "label": "Last Name"},
             {"name": "image", "type": "number", "label": "Avatar"}])
        return HttpResponse(content=content, status=400)

    if request.method == "POST":
        # try:
        #     request.POST = json.loads(request.body.decode("utf-8"))
        # except json.JSONDecodeError:
        #     pass
        data = JSONParser().parse(request)
        profile = Profile(firstName=data.get("firstName"), lastName=data.get("lastName"), image=data.get("image"))
        try:
            profile.save()
            profile.login(request)
            content = JSONRenderer().render(ProfileSerializer(profile).data)
            return HttpResponse(content)
        except Exception as e:
            return HttpResponse("", status=400)
Ejemplo n.º 30
0
def get_bind_status(request):
    identifier = request.GET.get('identifier')
    data = JSONParser().parse(request)
    iccid = data.get("iccid")
    if not Phone.check_auth(identifier, iccid):
        data = {"errcode": ErrCode.NOT_AUTHORIZED, "errmsg": "not authorized"}
        return JSONResponse(data=data, status=200)
    if not identifier or not Phone.objects.filter(identifier=identifier).exists():
        data = {"errcode": ErrCode.IDENTIFIER_NOT_VALID, "errmsg": "identifier not valid"}
        return JSONResponse(data=data, status=200)
    else:
        phone = Phone.objects.get(identifier=identifier)
        data = {"is_bind": phone.is_bind(), "errcode": ErrCode.OK}
        return JSONResponse(data=data, status=200)
Ejemplo n.º 31
0
def ArticleCreateView(request, pk=None):
    context = {}
    get_author = None
    try:
        get_author = Author.objects.get(pk=pk)
    except:
        get_author = None

    if get_author:
        if request.method == 'POST':
            data = JSONParser().parse(request)
            article = None
            try:
                article = Article.objects.create(author=get_author,
                                                 title=data.get('title'),
                                                 body=data.get('body'),
                                                 active=True)
            except:
                data = json.dumps({'message': 'Server Error', 'status': 500})
                return HttpResponse(data, content_type='application/json')

            serializer = ArticleSerializer(article, many=False)
            context['status'] = '200'
            context['data'] = serializer.data
            context['message'] = 'Succesfully Created Article'
            to_send = json.dumps(context)
            return HttpResponse(to_send, content_type='application/json')
        else:
            data = json.dumps({'message': 'Access Denied', 'status': 401})
            return HttpResponse(data, content_type='application/json')
    else:
        to_send = json.dumps({
            'message': 'Author does not exist',
            'status': 404
        })
        return HttpResponse(to_send, content_type='application/json')
Ejemplo n.º 32
0
def task_apply(request, pk):
    try:
        task = Task.objects.get(pk=pk)
    except Task.DoesNotExist:
        return HttpResponse(status=404)

    data = JSONParser().parse(request)
    user_id = str(data.get("user_id"))

    arr = task.persons_applied.split(",") + [user_id]

    task.persons_applied = ",".join(set(arr))
    task.save()

    return HttpResponse(status=200)
Ejemplo n.º 33
0
    def delete(self, request, *args, **kwargs):
        json_data = request.body

        #Converting Json data into Python Dictionary
        stream = io.BytesIO(json_data)
        python_data = JSONParser().parse(stream)

        id = python_data.get('id')
        emp = Employee.objects.get(id=id)

        emp.delete()

        msg = {'msg': 'Resource Deleted successfully'}
        json_data = JSONRenderer().render(msg)
        return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 34
0
 def put(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     python_data = JSONParser().parse(stream)
     id = python_data.get('id', None)
     if id is not None:
         stu = Student.objects.get(id=id)
         serializer = StudentSerializer(stu, data=python_data, partial=True)
         if serializer.is_valid():
             serializer.save()
             resp = {'Success': 'Data Updated Successfully'}
             json_data = JSONRenderer().render(resp)
             return HttpResponse(json_data, content_type="application/json")
     json_data = JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data, content_type="application/json")
Ejemplo n.º 35
0
def create_book(request):
    data = JSONParser().parse(request)
    # convert keys from camelCase to snake_case
    data = converts_keys(data, case='snake')
    serializer = BookSerializer(data=data)
    if serializer.is_valid():
        category, publisher, author = None, None, None
        category_id = data.get("category_id", None)
        publisher_id = data.get("publisher_id", None)
        author_id = data.get("author_id", None)
        if category_id:
            category = Category.objects.get(pk=category_id)
        if publisher_id:
            publisher = Publisher.objects.get(pk=publisher_id)
        if author_id:
            author = Author.objects.get(pk=author_id)
        serializer.save(
            category=category,
            publisher=publisher,
            author=author,
        )
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 36
0
 def post(self, request):
     data = JSONParser().parse(request)
     username = data.get('username')
     password = data.get('password')
     store_admin = StoreAdmin.objects.get(username=username)
     print('password ', password, ' store_admin ', store_admin.password)
     valid = hashers.check_password(password, store_admin.password)
     print('valid ', valid)
     if valid:
         data = {'message': 'success'}
         return JsonResponse(data=data,
                             status=status.HTTP_200_OK,
                             safe=False)
     else:
         raise AuthenticationError('Please login with valid credentials.')
Ejemplo n.º 37
0
    def get(self,*args, **kwargs):
        json_data = request.body
        stream = io.BytesIO(json_data)     # A stream implementation using an in-memory bytes buffer.It inherits BufferedIoBase.The Buffer is discarded when the close() method is called 
        pythondata = JSONParser().parse(stream)
        id = pythondata.get('id',None)
        if id is not None:
            stu = Student.objects.get(id =id)
            serializer = studentSerializer(stu)
            json_data = JSONRenderer().render(serializer.data)
            return HttpResponse(json_data, content_type = 'application/json')

        stu = Student.objects.get(id =id)
        serializer = studentSerializer(stu)
        json_data = JSONRenderer().render(serializer.data)
        return HttpResponse(json_data, content_type = 'application/json')
    def get(self, request, *args, **kwargs):
        json_data = request.body
        stream = io.BytesIO(json_data)
        pythondata = JSONParser().parse(stream)
        id = pythondata.get('id', None)
        if id is not None:
            stu = student.objects.get(id=id)
            serializer = stuSerializer(stu)
            json_data = JSONRenderer().render(serializer.data)
            return HttpResponse(json_data, content_type='application/json')

        stu = student.objects.all()
        serializer = stuSerializer(stu, many=True)
        json_data = JSONRenderer().render(serializer.data)
        return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 39
0
 def delete(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     python_data = JSONParser().parse(stream)
     id = python_data.get('id')
     try:
         data = Student.objects.get(id=id)
         data.delete()
         res = {'msg': 'Record Deleted Successfully!!'}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type='application/json')
     except Exception:
         res = {'msg': 'Instance Object Not Found!!!'}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 40
0
    def put(self, request, *args, **kwargs):
        # Deserialization
        json_data = request.body # Json Object
        stream = io.BytesIO(json_data)
        pdata = JSONParser().parse(stream) # Converting json data to python dictionary
        emp = Employee.objects.get(id = pdata.get('id'))
        serializer = EmployeeSerializer(emp, data=pdata, partial = True) # Converting python data to DB supported object
        if serializer.is_valid():
            serializer.save() # Saving the db supported object to Database
            msg = {'msg':'Resource Updated Successfully'}
            json_data = JSONRenderer().render(msg)
            return HttpResponse(json_data, content_type = 'application/json')

        json_data = JSONRenderer().render(serializer.errors)
        return HttpResponse(json_data, content_type='application/json', status = 400)
Ejemplo n.º 41
0
def strategy_field_list(request):
    """
    展示所以snippets,或创建新的snippet.
    """
    if request.method == 'GET':
        field = StrategyFiled.objects.all()
        serializer = StrategyFiledSerializer(field, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':

        data = JSONParser().parse(request)
        field = StrategyFiled.objects.get(id=data.get('id'))

        serializer = StrategyFiledSerializer(field, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
    elif request.method == 'DELETE':
        data = JSONParser().parse(request)
        field = StrategyFiled.objects.get(id=data.get('id'))
        field.delete()
        return HttpResponse(status=204)
Ejemplo n.º 42
0
 def put(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     pythondata = JSONParser().parse(stream)
     serializer = StudentSerializer(data=pythondata)
     id = pythondata.get('id')
     stu = Student.objects.get(id=id)
     serializer = StudentSerializer(stu, data=pythondata, partial=True)
     if serializer.is_valid():
         serializer.save()
         res = {'msg': 'Data Updated'}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type='application/json')
     json_data = JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 43
0
    def get(self, request, *args, **kwargs):
        data = request.body  # json
        stream = io.BytesIO(data)
        p_data = JSONParser().parse(stream)

        emp_id = p_data.get("id", None)
        if emp_id:
            emp_info = Employee.objects.get(id=emp_id)
            eserial_data = EmployeeSerializer(emp_info)
            json_data = JSONRenderer().render(eserial_data.data)
            return HttpResponse(json_data, content_type='application/json')
        qs = Employee.objects.all()
        eserial_data = EmployeeSerializer(qs, many=True)
        json_data = JSONRenderer().render(eserial_data.data)
        return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 44
0
 def put(self,request,*args,**kwargs):
     json_data=request.body
     stream=io.BytesIO(json_data)
     data=JSONParser().parse(stream)
     id=data.get('id',None)
     if id is not None:
         emp=Employee.objects.get(id=id)
         serializer=EmployeeSerializer(emp,data=data)
         if serializer.is_valid():
             serializer.save()
             msg={'msg':'resource updated'}
             json_data=JSONRenderer().render(msg)
             return HttpResponse(json_data,content_type='application/json')
         json_data = JSONRenderer().render(serializer.errors)
         return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 45
0
    def post(self, request):
        data = JSONParser().parse(request)
        customer_data = data.get("customer")
        shipping_address_data = data.get("shipping_address")
        prints_data = data.get("prints")
        payment_data = data.get("payment")

        serializers = {
            "customer": CustomerSerializer(data=customer_data),
            "address": AddressSerializer(data=shipping_address_data),
            "prints": PrintSerializer(data=prints_data, many=True),
            "payment": PaymentSerializer(data=payment_data)
        }

        good_data = True
        ret_data = {}

        for s in serializers.values():
            if not s.is_valid():
                good_data = False

        if good_data:
            order = self.create_order(serializers)
            self.create_prints_for_order(serializers, order)

            billing_summary = {}
            self.add_payment_info(billing_summary, payment_data)
            self.add_shipping_info(billing_summary, shipping_address_data)
            self.add_prints_info(billing_summary, prints_data)

            ret_data["order_num"] = order.id
            ret_data["billing_summary"] = billing_summary

        response_status = 201 if good_data else 422

        return Response(data=ret_data, status=response_status)
Ejemplo n.º 46
0
    def patch(self, request, pk):
        try:
            data = JSONParser().parse(request)
            wallet_name = data.get('wallet_name')
            network = data.get('network')
            print('Started ' + self.__class__.__name__ + ' patch method ')
            print('Started ' + self.__class__.__name__ +
                  ' patch method network= %s, name= %s' %
                  (network, wallet_name))
            if network == 'bitcoin':
                wallet = rename_wallet(wallet_id=pk,
                                       db_uri=db_uri,
                                       name=wallet_name)
            elif network == 'litecoin':
                wallet = rename_wallet(wallet_id=pk,
                                       db_uri=db_uri,
                                       name=wallet_name)

            return JsonResponse(wallet, safe=False)
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            print("error" + str(e))
            raise e
Ejemplo n.º 47
0
 def get(self,request,*args,**kwargs):
     json_data=request.body
     stream=io.BytesIO(json_data)
     pdata=JSONParser().parse(stream)
     print(pdata)
     id=pdata.get('id',None)
     if id is not None:
         emp=Employee.objects.get(id=id)
         serialize=EmployeeSerializer(emp)
         json_data=JSONRenderer().render(serialize.data)
         return HttpResponse(json_data,content_type='application/json')
     qs=Employee.objects.all()
     serialize=EmployeeSerializer(qs,many=True)
     json_data=JSONRenderer().render(serialize.data)
     return HttpResponse(json_data,content_type='application/json')
Ejemplo n.º 48
0
    def update_message(self, request, pk=None):
        data = JSONParser().parse(request)
        message_id = data.get("id")
        new_text = data.get("text")
        if not message_id or not new_text:
            return HttpResponse(content="Bad request", status=400)
        if not new_text or new_text == "":
            return HttpResponse(
                "Bad request, no message text provided",
                status=400
            )

        try:
            message = Message.objects.get(pk=message_id)
            serializer = MessageSerializer(
                message,
                data={
                    "text": new_text},
                partial=True
            )
            initial = MessageSerializer(message)
        except Message.DoesNotExist:
            return HttpResponse("404", status=404)

        if not initial.data.get("sender_id") == pk:
            return HttpResponse("404", status=404)
        if not serializer.is_valid():
            return HttpResponse("Bad request", status=400)

        serializer.save()
        updated_message = Message.objects.get(pk=message_id)

        return JsonResponse(
            MessageSerializer(updated_message).data,
            status=200
        )
Ejemplo n.º 49
0
def api_login(request):
    data = JSONParser().parse(request)
    username = data.get('username', '')
    password = data.get('password', '')
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)

        ret_dict = {'id': user.id, 'username': user.username, 'error': ''}
        return HttpResponse(json.dumps(ret_dict),
                            content_type="application/json")
    else:
        ret_dict = {'id': '', 'username': '', 'error': '用户名或密码错误'}
        return HttpResponse(json.dumps(ret_dict),
                            content_type="application/json")
Ejemplo n.º 50
0
 def put(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     python_data = JSONParser().parse(stream)
     id = python_data.get('id')
     stu = Student.objects.get(id=id)
     # partial update i.e. here not provide roll no
     serializer = StudentSerializer(stu, data=python_data, partial=True)
     if serializer.is_valid():
         serializer.save()
         res = {"msg": "Data updated"}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type="application/json")
     #catching error, and return errors
     json_data = JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data, content_type="application/json")
Ejemplo n.º 51
0
    def put(self, request, *args, **kwargs):
        json_data = request.body
        stream = io.BytesIO(json_data)
        python_data = JSONParser().parse(stream)
        _id = python_data.get("id")
        stu = Student.objects.get(id=_id)
        serialize = StudentSerializer(stu, data=python_data, partial=True)
        # partial is set to True when we are updating only partial data

        if serialize.is_valid():
            serialize.save()
            res = {"status": "Data updated !"}
            return JsonResponse(res, safe=False)

        json_response = JSONRenderer.render(serialize.errors)
        return HttpResponse(json_response, content_type="application/json")
Ejemplo n.º 52
0
def UpdateStudent(request):

    if request.method == 'PUT':
        r_body = request.body
        stream = io.BytesIO(r_body)
        py_data = JSONParser().parse(stream)
        id = py_data.get('id')
        stu = Student.objects.get(id=id)
        serialize_up = CreateSerializer(stu, data=py_data, partial=True)
        if serialize_up.is_valid():
            serialize_up.save()
            return JsonResponse({"msg": "Data Updated Sucessfully."})
        else:
            return JsonResponse(serialize_up.errors)
    else:
        return HttpResponse("Its PUT Respone")
Ejemplo n.º 53
0
def student_api(request):
    if request.method == "GET":
        json_data = request.body
        stream = io.BytesIO(json_data)
        pythondata = JSONParser().parse(stream)
        id = pythondata.get("id", None)
        if id is not None:
            stu = Student.objects.get(id=id)
            serializer = StudentSerializer(stu)
            json_data = JSONRenderer().render(serializer.data)
            return HttpResponse(json_data, content_type="application/json")

        stu = Student.object.all()
        serializer = StudentSerializer(stu, many=True)
        json_data = JSONRenderer().render(serializer.data)
        return HttpResponse(json_data, content_type="application/json")
Ejemplo n.º 54
0
 def get(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     pdata = JSONParser().parse(stream)
     id = pdata.get('id')
     if id is not None:
         emp = Student.objects.get(id=id)
         print(emp)
         serializer = StudentSerializers(emp)
         json_data = JSONRenderer().render(serializer.data)
         return HttpResponse(json_data, content_type='application/json')
     emp = Student.objects.all()
     print(emp)
     serializer = StudentSerializers(emp, many=True)
     json_data = JSONRenderer().render(serializer.data)
     return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 55
0
 def put(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     pdata = JSONParser().parse(stream)
     id = pdata.get('id')
     emp = EmployeeModel.objects.get(id=id)
     serializer = EmployeeSerializer(emp, data=pdata, partial=True)
     if serializer.is_valid():
         serializer.save()  #internally it calles update inside serialser
         msg = {'msg': 'Resource updated successfully.'}
         json_data = JSONRenderer().render(msg)
         return HttpResponse(json_data, content_type='application/json')
     json_data = JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data,
                         content_type='application/json',
                         status=400)
Ejemplo n.º 56
0
def student_update(request):
    if request.method == 'PUT':
        json_data = request.body
        stream = io.BytesIO(json_data)
        pydata = JSONParser().parse(stream)
        id = pydata.get('id')
        stu = Student.objects.get(id=id)
        serializer = StudentSerializer(stu, data=pydata, partial=True)
        if serializer.is_valid():
            serializer.save()
            response = {'msg': 'Data Updates'}
            json_data = JSONRenderer().render(response)
            return HttpResponse(json_data, content_type='application/json')
        else:
            json_data = JSONRenderer.render(serializer.errors)
            return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 57
0
    def get(self, request, *args, **kwargs):
        json_data = request.body
        stream = io.BytesIO(json_data)
        pythondata = JSONParser().parse(stream)
        #get the id if id is present in request else return none in id
        id = pythondata.get('id', None)
        if id is not None:
            story = Story.objects.get(id=id)
            serializer = StorySerializer(story)
            json_data = JSONRenderer().render(serializer.data)
            return HttpResponse(json_data, content_type='application/json')

        story = Story.objects.all()
        serializer = StorySerializer(story, many=True)
        json_data = JSONRenderer().render(serializer.data)
        return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 58
0
 def put(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     python_data = JSONParser().parse(stream)
     id = python_data.get('id')
     data = Student.objects.get(id=id)
     serializer = StudentSerializer(
         instance=data, data=python_data, partial=True
     )  # if partial is not passed or set to False, then it will work like PATCH
     if serializer.is_valid():
         serializer.save()
         res = {'msg': 'Record Updated Successfully!'}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type='application/json')
     json_data = serializer.errors
     return HttpResponse(json_data, content_type='application/json')
Ejemplo n.º 59
0
 def put(self , request,*args,**kwargs):
     json_data=request.body     
     stream = io.BytesIO(json_data)   # get json data 
     # parse json data to python native data type
     python_data =JSONParser().parse(stream)   #converted json data to python native data type(dictionary)
     roll= python_data.get('roll')
     stu=Student.objects.get(roll=roll)
     serializer=StudentSerializer(stu,data=python_data,partial=True)
     if serializer.is_valid():
         serializer.save()
         res={'msg':'data updated successfully'}
         # converted python data into json 
         json_data=JSONRenderer().render(res)
         return HttpResponse(json_data,content_type='application/json') 
     json_data=JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data,content_type='application/json') 
Ejemplo n.º 60
0
def employee_list(request):
    if request.method == 'GET':
        logger.debug("inside get method")
        employee = Employee.objects.all()
        firstname = request.GET.get('firstname', None)
        if firstname is not None:
            logger.debug("firstname is {}".format(firstname))
            employee = employee.filter(firstname=firstname)
        employee_serializer = EmployeeSerializer(employee, many=True)
        return JsonResponse(employee_serializer.data, safe=False)

    elif request.method == 'POST':
        logger.debug("inside post method")
        employee_data = JSONParser().parse(request)
        employee_serializer = EmployeeSerializer(data=employee_data)
        if employee_serializer.is_valid():
            employee_serializer.save()
            return JsonResponse({"message": "valid"})
        else:
            return JsonResponse({"message": "not valid"})

    elif request.method == 'DELETE':
        logger.debug("inside delete method")
        firstname = request.GET.get('firstname', None)
        employee = Employee.objects.filter(firstname=firstname)
        if firstname is not None:
            employee.delete()
            return JsonResponse({"message": "deleted successfully"})
        else:
            return JsonResponse({"message": "deletion not successful"})

    elif request.method == 'PUT':
        logger.debug("inside put method")
        employee_data = JSONParser().parse(request)
        firstname = employee_data.get("firstname")
        if firstname is not None:
            employee = Employee.objects.filter(firstname=firstname)
            employee.update(**employee_data)
            return JsonResponse({"message": "updated successful"})
        else:
            return JsonResponse({"message": "update failed"})


#    try:
#        employee = TEmployee.objects.get(id=10)
#    except TEmployee.DoesNotExist:
#        return HttpResponse("EXCEPTION")