Beispiel #1
0
    def on_success_login(self, req, resp, conn, users_id, auth_token):
        ip_address = get_client_ip(req)
        headers = get_hashed_headers(req)
        csrf_token = gen_csrf_token()
        delta = timedelta(seconds=settings.USER_AUTH_COOKIE_EXPIRES)
        utc_expiry = datetime.utcnow() + delta
        values = {
            "users_id": users_id,
            "ip_address": ip_address,
            "headers": headers,
            "csrf_token": csrf_token,
            "cookie_expiry": utc_expiry
        }
        db_utils.update(conn,
                        "users_logins",
                        values={"cookie_expiry": datetime.utcnow()},
                        where={
                            "users_id": users_id,
                            "ip_address": ip_address,
                            "headers": headers,
                            "cookie_expiry__gt": datetime.utcnow()
                        })
        db_utils.insert(conn, "users_logins", values=values)

        # set cookie
        expiry = gen_cookie_expiry(utc_expiry)
        auth_cookie = make_auth_cookie(expiry, csrf_token, auth_token,
                                       users_id)
        set_cookie(resp, USER_AUTH_COOKIE_NAME, auth_cookie, expiry=expiry)
        self._set_basket_data(req, resp, users_id)
Beispiel #2
0
 def validate(self, attrs):
     request = self.context.get('request')
     user_ip = get_client_ip(request)
     attrs.update({
         'user_id': request.user.id,
         'ip_address': user_ip,
     })
     return attrs
Beispiel #3
0
    def get(self, request, pk, ext=None):
        obj = RetirementStatementOfAdvice.objects.get(pk=pk)
        client_ip = get_client_ip(request)

        if (ext.lower() == '.pdf'):
            response = HttpResponse(obj.render_pdf(self.template_name,
                                                   client_ip=client_ip),
                                    content_type='application/pdf')
            response[
                'Content-Disposition'] = 'inline; filename="statement_%s.pdf"' % obj.date
        else:
            response = HttpResponse(
                obj.render_template(self.template_name, client_ip=client_ip))
        return response
Beispiel #4
0
    def post(self, request, *args, **kwargs):
        self.request = request
        self.serializer = self.get_serializer(data=self.request.data,
                                              context={'request': request})

        try:
            # the real authenticate process
            # please refer to `rest_auth.serializer.LoginSerializer`
            self.serializer.is_valid(raise_exception=True)
        except ValidationError as e:
            logger.error(e)
            return Response({
                "data": None,
                "code": 0
            },
                            status=status.HTTP_401_UNAUTHORIZED)
        user = self.serializer.validated_data['user']
        user.company
        user.last_login_ip = get_client_ip(request)
        self.login()
        user.save(update_fields=['last_login_ip'])
        serializer = UserSerializer(user)
        return Response({"data": serializer.data, "code": 0})
Beispiel #5
0
    def _get_user_info(self, req, resp):
        remote_resp = data_access(REMOTE_API_NAME.GET_USERINFO,
                                  req, resp)
        err = req.get_param('err') or ''
        user_profile = {}
        if remote_resp.get('res') == RESP_RESULT.F:
            err = remote_resp.get('err')
            first_time = False
        else:
            user_profile = remote_resp
            first_time = not user_profile['general']['values'][0].get('first_name')

            # translate name
            for fs_name, fs in user_profile.iteritems():
                if 'name' in fs:
                    fs['name'] = _(fs['name'])
                if 'fields' in fs:
                    for f_name, f in fs['fields']:
                        f['name'] = _(f['name'])
                        if f['type'] == 'radio':
                            f['accept'] = [[_(n), v] for n, v in f['accept']]

            # filter country list
            white_countries = allowed_countries()
            if white_countries:
                for f_name, f in user_profile['phone']['fields']:
                    if f_name == 'country_num':
                        f['accept'] = filter(lambda x:x[1]
                                             in white_countries, f['accept'])

            set_default_addr_country = not all(
                int(addr['id']) for addr in user_profile['address']['values'])
            set_default_phone_country = not all(
                int(p['id']) for p in user_profile['phone']['values'])
            if set_default_addr_country or set_default_phone_country:
                geolocation = get_location_by_ip(get_client_ip(req))

            # give geolocation country calling code if no values
            if set_default_phone_country:
                for p in user_profile['phone']['values']:
                    if not int(p['id']):
                        country_code = geolocation['country']['iso_code']
                        p['country_num'] = unicode2utf8(country_code)

            # give geolocation country/province if no address values.
            if set_default_addr_country:
                for address in user_profile['address']['values']:
                    if not int(address['id']):
                        country_code = geolocation['country']['iso_code']
                        province_name = geolocation['subdivision']['name']

                        if country_code and province_name:
                            remote_resp = data_access(REMOTE_API_NAME.AUX,
                                                      req, resp,
                                                      get='province_code',
                                                      ccode=country_code,
                                                      pname=province_name)
                            address['country_code'] = unicode2utf8(country_code)
                            if remote_resp and isinstance(remote_resp, str) \
                                    and RESP_RESULT.F not in remote_resp:
                                address['province_code'] = unicode2utf8(remote_resp)

        return {'user_profile': user_profile,
                'err': err,
                'succ_redirect_to': get_url_format(FRT_ROUTE_ROLE.MY_ACCOUNT),
                'first_time': first_time,
                'id_order': req.get_param('id_order') or ''}
Beispiel #6
0
    def _valid_check(self, conn):
        resp_code = self.request.get_param('RespCode')
        amount = float(self.request.get_param('Amt')) / 100
        order_id = self.request.get_param('Ref')
        auth = self.request.get_param('Auth')

        # for a rejected transaction, this parameter is not sent back.
        if not auth:
            logging.error(
                'paybox_valid_err: rejected transaction for '
                'request %s',
                self.request.query_string,
                exc_info=True)
            raise UserError(ErrorCode.PB_ERR_REJECTED_TRANS[0],
                            ErrorCode.PB_ERR_REJECTED_TRANS[1])

        # authorization number is alphanumeric.
        if not re.match(r'^[a-zA-Z0-9]+$', auth):
            logging.error(
                'paybox_valid_err: wrong authorization number %s for'
                ' request %s',
                auth,
                self.request.query_string,
                exc_info=True)
            raise UserError(ErrorCode.PB_ERR_WRONG_AUTH[0],
                            ErrorCode.PB_ERR_WRONG_AUTH[1])

        # TODO: check ip address
        ip_addr = get_client_ip(self.request)
        logging.info('Paybox IPN request address %s for request %s', ip_addr,
                     self.request.query_string)

        trans = get_trans_by_id(conn, self.id_trans)
        if len(trans) == 0:
            logging.error('paybox_valid_err: trans(%s) not exist %s',
                          self.id_trans,
                          self.request.query_string,
                          exc_info=True)
            raise UserError(ErrorCode.PB_ERR_NO_TRANS[0],
                            ErrorCode.PB_ERR_NO_TRANS[1])

        trans = trans[0]
        amount_due = float(trans['amount_due'])
        if amount_due != amount:
            logging.error(
                'paybox_valid_err: paybox amount %s is not same '
                'as expected amount due: %s for request: %s',
                amount,
                amount_due,
                self.request.query_string,
                exc_info=True)
            raise UserError(ErrorCode.PB_ERR_WRONG_AMOUNT[0],
                            ErrorCode.PB_ERR_WRONG_AMOUNT[1])

        if int(order_id) != int(trans['id_order']):
            logging.error(
                'paybox_valid_err: order_id %s is not same as '
                'expected order_id %s for request: %s',
                order_id,
                trans['id_order'],
                self.request.query_string,
                exc_info=True)
            raise UserError(ErrorCode.PB_ERR_WRONG_ORDER[0],
                            ErrorCode.PB_ERR_WRONG_ORDER[1])
        return trans
Beispiel #7
0
 def get(self, request, *args, **kwargs):
     self.ip = get_client_ip(request)
     get_location(request)
     return super(StatView, self).get(request, *args, **kwargs)