Edits history of script submission #22727 for ' Get Current User (servicenow)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    function authHeader(auth: RT.Servicenow) {
      return auth.token
        ? `Bearer ${auth.token}`
        : `Basic ${btoa(`${auth.username}:${auth.password}`)}`
    }
    
    /**
     * Get Current User
     * Return the sys_user record of the authenticated user (resolves current_user, then fetches the full record from sys_user).
     */
    export async function main(auth: RT.Servicenow) {
      const currentResponse = await fetch(
        `${auth.instance_url}/api/now/ui/user/current_user`,
        {
          method: "GET",
          headers: {
            Authorization: authHeader(auth),
            Accept: "application/json",
          },
        }
      )
      if (!currentResponse.ok) {
        throw new Error(`${currentResponse.status} ${await currentResponse.text()}`)
      }
      const { result } = (await currentResponse.json()) as {
        result: { user_sys_id: string }
      }
    
      const userResponse = await fetch(
        `${auth.instance_url}/api/now/table/sys_user/${result.user_sys_id}`,
        {
          method: "GET",
          headers: {
            Authorization: authHeader(auth),
            Accept: "application/json",
          },
        }
      )
      if (!userResponse.ok) {
        throw new Error(`${userResponse.status} ${await userResponse.text()}`)
      }
    
      return await userResponse.json()
    }
    

    Submitted by hugo989 5 days ago