Specify the user data sent to Intercom API
763323
def get_intercom_data(self):
        """"""
        return {
            "user_id": self.intercom_id,
            "email": self.email,
            "name": self.get_full_name(),
            "last_request_at": self.last_login.strftime("%s") if self.last_login else "",
            "created_at": self.date_joined.strftime("%s"),
            "custom_attributes": {
                "is_admin": self.is_superuser
            }
        }
176524
def device_text_string_request(self):
        
        msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01)
        self._send_msg(msg)
1033331
function(userId, appId) {
        if(!appId){
            return userId + '-' + config.creds.appId + '@' + config.endpoints.chat;
        }
        return userId + '-' + appId + '@' + config.endpoints.chat;
    }
764604
def HandleRequest(self, request):
    """"""
    impersonated_username = config.CONFIG["AdminUI.debug_impersonate_user"]
    if impersonated_username:
      logging.info("Overriding user as %s", impersonated_username)
      request.user = config.CONFIG["AdminUI.debug_impersonate_user"]

    if not aff4_users.GRRUser.IsValidUsername(request.user):
      return self._BuildResponse(
          403, dict(message="Invalid username: %s" % request.user))

    try:
      router, method_metadata, args = self._router_matcher.MatchRouter(request)
    except access_control.UnauthorizedAccess as e:
      error_message = str(e)
      logging.exception("Access denied to %s (%s): %s", request.path,
                        request.method, e)

      additional_headers = {
          "X-GRR-Unauthorized-Access-Reason": error_message.replace("\n", ""),
          "X-GRR-Unauthorized-Access-Subject": utils.SmartStr(e.subject)
      }
      return self._BuildResponse(
          403,
          dict(
              message="Access denied by ACL: %s" % error_message,
              subject=utils.SmartStr(e.subject)),
          headers=additional_headers)

    except ApiCallRouterNotFoundError as e:
      error_message = str(e)
      return self._BuildResponse(404, dict(message=error_message))
    except werkzeug_exceptions.MethodNotAllowed as e:
      error_message = str(e)
      return self._BuildResponse(405, dict(message=error_message))
    except Error as e:
      logging.exception("Can't match URL to router/method: %s", e)

      return self._BuildResponse(
          500, dict(message=str(e), traceBack=traceback.format_exc()))

    request.method_metadata = method_metadata
    request.parsed_args = args

    # SetUID() is called here so that ACL checks done by the router do not
    # clash with datastore ACL checks.
    # TODO(user): increase token expiry time.
    token = self.BuildToken(request, 60).SetUID()

    if data_store.AFF4Enabled():
      # TODO:
      # AFF4 edge case: if a user is issuing a request, before they are created
      # using CreateGRRUser (e.g. in E2E tests or with single sign-on),
      # AFF4's ReadGRRUsers will NEVER contain the user, because the creation
      # done in the following lines does not add the user to the /users/
      # collection. Furthermore, subsequent CreateGrrUserHandler calls fail,
      # because the user technically already exists.

      # We send a blind-write request to ensure that the user object is created
      # for a user specified by the username.
      user_urn = rdfvalue.RDFURN("aff4:/users/").Add(request.user)
      # We can't use conventional AFF4 interface, since aff4.FACTORY.Create will
      # create a new version of the object for every call.
      with data_store.DB.GetMutationPool() as pool:
        pool.MultiSet(
            user_urn, {
                aff4_users.GRRUser.SchemaCls.TYPE:
                    [aff4_users.GRRUser.__name__],
                aff4_users.GRRUser.SchemaCls.LAST:
                    [rdfvalue.RDFDatetime.Now().SerializeToDataStore()]
            },
            replace=True)

    if data_store.RelationalDBEnabled():
      data_store.REL_DB.WriteGRRUser(request.user)

    handler = None
    try:
      # ACL checks are done here by the router. If this method succeeds (i.e.
      # does not raise), then handlers run without further ACL checks (they're
      # free to do some in their own implementations, though).
      handler = getattr(router, method_metadata.name)(args, token=token)

      if handler.args_type != method_metadata.args_type:
        raise RuntimeError("Handler args type doesn't match "
                           "method args type: %s vs %s" %
                           (handler.args_type, method_metadata.args_type))

      binary_result_type = (
          api_call_router.RouterMethodMetadata.BINARY_STREAM_RESULT_TYPE)

      if (handler.result_type != method_metadata.result_type and
          not (handler.result_type is None and
               method_metadata.result_type == binary_result_type)):
        raise RuntimeError("Handler result type doesn't match "
                           "method result type: %s vs %s" %
                           (handler.result_type, method_metadata.result_type))

      # HEAD method is only used for checking the ACLs for particular API
      # methods.
      if request.method == "HEAD":
        # If the request would return a stream, we add the Content-Length
        # header to the response.
        if (method_metadata.result_type ==
            method_metadata.BINARY_STREAM_RESULT_TYPE):
          binary_stream = handler.Handle(args, token=token)
          return self._BuildResponse(
              200, {"status": "OK"},
              method_name=method_metadata.name,
              no_audit_log=method_metadata.no_audit_log_required,
              content_length=binary_stream.content_length,
              token=token)
        else:
          return self._BuildResponse(
              200, {"status": "OK"},
              method_name=method_metadata.name,
              no_audit_log=method_metadata.no_audit_log_required,
              token=token)

      if (method_metadata.result_type ==
          method_metadata.BINARY_STREAM_RESULT_TYPE):
        binary_stream = handler.Handle(args, token=token)
        return self._BuildStreamingResponse(
            binary_stream, method_name=method_metadata.name)
      else:
        format_mode = GetRequestFormatMode(request, method_metadata)
        result = self.CallApiHandler(handler, args, token=token)
        rendered_data = self._FormatResultAsJson(
            result, format_mode=format_mode)

        return self._BuildResponse(
            200,
            rendered_data,
            method_name=method_metadata.name,
            no_audit_log=method_metadata.no_audit_log_required,
            token=token)
    except access_control.UnauthorizedAccess as e:
      error_message = str(e)
      logging.warning("Access denied for %s (HTTP %s %s): %s",
                      method_metadata.name, request.method, request.path,
                      error_message)

      additional_headers = {
          "X-GRR-Unauthorized-Access-Reason": error_message.replace("\n", ""),
          "X-GRR-Unauthorized-Access-Subject": utils.SmartStr(e.subject)
      }
      return self._BuildResponse(
          403,
          dict(
              message="Access denied by ACL: %s" % error_message,
              subject=utils.SmartStr(e.subject)),
          headers=additional_headers,
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except api_call_handler_base.ResourceNotFoundError as e:
      error_message = str(e)
      return self._BuildResponse(
          404,
          dict(message=error_message),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except NotImplementedError as e:
      error_message = str(e)
      return self._BuildResponse(
          501,
          dict(message=error_message),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except Exception as e:  # pylint: disable=broad-except
      error_message = str(e)
      logging.exception("Error while processing %s (%s) with %s: %s",
                        request.path, request.method,
                        handler.__class__.__name__, e)
      return self._BuildResponse(
          500,
          dict(message=error_message, traceBack=traceback.format_exc()),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
787791
def on_connect(client):
    """"""
    client.nick(client.user.nick)
    client.userinfo(client.user.username, client.user.realname)
549967
def api(self, name):
        ''''''

        assert name, 'name is none'
        if flow.__name__ == name:
            api = flow.FlowApi()
        elif sign.__name__ == name:
            api = sign.SignApi()
        elif sms.__name__ == name:
            api = sms.SmsApi()
        elif tpl.__name__ == name:
            api = tpl.TplApi()
        elif user.__name__ == name:
            api = user.UserApi()
        elif voice.__name__ == name:
            api = voice.VoiceApi()

        assert api, "not found api-" + name

        api._init(self._clnt)
        return api
882242
def token_reply_info(client, scope, user = nil, state = nil, refresh = false)
    interval = client[:access_token_validity] || 3600
    token_body = { jti: SecureRandom.uuid, aud: scope, scope: scope,
        client_id: client[:client_id], exp: interval + Time.now.to_i }
    if user
      token_body[:user_id] = user[:id]
      token_body[:email] = primary_email(user[:emails])
      token_body[:user_name] = user[:username]
    end
    info = { access_token: TokenCoder.encode(token_body, :algorithm => 'none'),
        token_type: 'bearer', expires_in: interval, scope: scope}
    info[:state] = state if state
    info[:refresh_token] = 'universal_refresh_token' if refresh
    inject_error(info)
    info
  end
314277
def userInformation(MoreData_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x20)  # 000100000
    c = UserUser()
    packet = a / b / c
    if MoreData_presence is 1:
        d = MoreDataHdr(ieiMD=0xA0, eightBitMD=0x0)
        packet = packet / d
    return packet
233932
def call(payload=None):
    '''
    
    '''
    r = None
    try:
        if DETAILS['method'] == 'dev_key':
            # Pass the api key without the target declaration
            conditional_payload = {'key': DETAILS['apikey']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'dev_pass':
            # Pass credentials without the target declaration
            r = __utils__['http.query'](DETAILS['url'],
                                        username=DETAILS['username'],
                                        password=DETAILS['password'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'pan_key':
            # Pass the api key with the target declaration
            conditional_payload = {'key': DETAILS['apikey'],
                                   'target': DETAILS['serial']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
        elif DETAILS['method'] == 'pan_pass':
            # Pass credentials with the target declaration
            conditional_payload = {'target': DETAILS['serial']}
            payload.update(conditional_payload)
            r = __utils__['http.query'](DETAILS['url'],
                                        username=DETAILS['username'],
                                        password=DETAILS['password'],
                                        data=payload,
                                        method='POST',
                                        decode_type='plain',
                                        decode=True,
                                        verify_ssl=False,
                                        status=True,
                                        raise_error=True)
    except KeyError as err:
        raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")

    if not r:
        raise salt.exceptions.CommandExecutionError("Did not receive a valid response from host.")

    if six.text_type(r['status']) not in ['200', '201', '204']:
        if six.text_type(r['status']) == '400':
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request due to a client error.")
        elif six.text_type(r['status']) == '401':
            raise salt.exceptions.CommandExecutionError(
                "The server cannot process the request because it lacks valid authentication "
                "credentials for the target resource.")
        elif six.text_type(r['status']) == '403':
            raise salt.exceptions.CommandExecutionError(
                "The server refused to authorize the request.")
        elif six.text_type(r['status']) == '404':
            raise salt.exceptions.CommandExecutionError(
                "The requested resource could not be found.")
        else:
            raise salt.exceptions.CommandExecutionError(
                "Did not receive a valid response from host.")

    xmldata = ET.fromstring(r['text'])

    # If we are pulling the candidate configuration, we need to strip the dirtyId
    if payload['type'] == 'config' and payload['action'] == 'get':
        xmldata = (_strip_dirty(xmldata))

    return xml.to_dict(xmldata, True)
1260786
function setClientInfo(req) {

	let client = req.client = {};

	initUserAgendAndOS(req.headers, client);
	initClientIp(req, client);
}
674819
def set_item_data(self, item, filename, line_number):
        """"""
        set_item_user_text(item, '%s%s%d' % (filename, self.SEP, line_number))
912344
def user_to_uid(user):
    '''
    
    '''
    if user is None:
        user = salt.utils.user.get_user()

    return salt.utils.win_dacl.get_sid_string(user)
438808
def extended_status_request(self):
        """"""
        self._status_received = False
        user_data = Userdata({'d1': self.group,
                              'd2': 0x00})
        cmd = ExtendedSend(self._address,
                           COMMAND_EXTENDED_GET_SET_0X2E_0X00,
                           userdata=user_data)
        cmd.set_checksum()
        self._send_method(cmd, self._status_message_received, True)
131745
def get_user(id, opts = {})
      data, _status_code, _headers = get_user_with_http_info(id, opts)
      return data
    end
629321
def _build_request(self, type, commands):
        '''
        
        '''
        request = {}
        headers = {
            'content-type': 'application/json',
        }
        if self.nxargs['connect_over_uds']:
            user = self.nxargs['cookie']
            headers['cookie'] = 'nxapi_auth=' + user + ':local'
            request['url'] = self.NXAPI_UDS_URI_PATH
        else:
            request['url'] = '{transport}://{host}:{port}{uri}'.format(
                transport=self.nxargs['transport'],
                host=self.nxargs['host'],
                port=self.nxargs['port'],
                uri=self.NXAPI_REMOTE_URI_PATH,
            )

        if isinstance(commands, (list, set, tuple)):
            commands = ' ; '.join(commands)
        payload = {}
        payload['ins_api'] = {
            'version': self.NXAPI_VERSION,
            'type': type,
            'chunk': '0',
            'sid': '1',
            'input': commands,
            'output_format': 'json',
        }
        request['headers'] = headers
        request['payload'] = json.dumps(payload)
        request['opts'] = {
            'http_request_timeout': self.nxargs['timeout']
        }
        log.info('request: %s', request)
        return request
784343
def from_raw_message(cls, rawmessage):
        """"""
        userdata_dict = Userdata(rawmessage[8:22])
        return ExtendedSend(rawmessage[2:5],
                            {'cmd1': rawmessage[6],
                             'cmd2': rawmessage[7]},
                            userdata_dict,
                            flags=rawmessage[5],
                            acknak=rawmessage[22:23])
536365
def sendoff_current_user(self):
        
        msgs = self.task_data.get('LANE_CHANGE_MSG', DEFAULT_LANE_CHANGE_MSG)
        self.msg_box(title=msgs['title'], msg=msgs['body'])