or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdchange-feeds.mddatabase-management.mddocument-operations.mderror-handling.mdhttp-adapters.mdindex.mdquery-indexing.mdreplication.mdscheduler-monitoring.mdsecurity-document.mdviews-design-documents.md

authentication.mddocs/

0

# Client Connection and Authentication

1

2

Establish connections to Cloudant and CouchDB servers with comprehensive authentication support including basic authentication, IAM tokens, and Cloud Foundry service integration.

3

4

## Capabilities

5

6

### Context Manager Functions

7

8

Context managers provide automatic connection and disconnection handling with proper resource cleanup.

9

10

```python { .api }

11

def cloudant(user, passwd, **kwargs):

12

"""

13

Create Cloudant session context manager with basic authentication.

14

15

Parameters:

16

- user (str): Username for authentication

17

- passwd (str): Password or authentication token

18

- account (str): Cloudant account name for URL construction

19

- url (str): Fully qualified service URL (alternative to account)

20

- x_cloudant_user (str): Override X-Cloudant-User header for proxy authentication

21

- encoder (json.JSONEncoder): Custom JSON encoder for documents

22

- connect (bool): Auto-connect on context entry (default: True)

23

- auto_renew (bool): Automatic session renewal (default: False)

24

- timeout (float | tuple): Request timeout in seconds

25

- use_basic_auth (bool): Force basic authentication (default: False)

26

27

Returns:

28

Context manager yielding Cloudant client instance

29

"""

30

31

def cloudant_iam(account_name, api_key, **kwargs):

32

"""

33

Create Cloudant session context manager with IAM authentication.

34

35

Parameters:

36

- account_name (str): Cloudant account name

37

- api_key (str): IAM API key for authentication

38

- iam_client_id (str): IAM client ID (optional)

39

- iam_client_secret (str): IAM client secret (optional)

40

- encoder (json.JSONEncoder): Custom JSON encoder

41

- timeout (float | tuple): Request timeout

42

43

Returns:

44

Context manager yielding Cloudant client instance

45

"""

46

47

def cloudant_bluemix(vcap_services, instance_name=None, service_name=None, **kwargs):

48

"""

49

Create Cloudant session from Cloud Foundry VCAP_SERVICES.

50

51

Parameters:

52

- vcap_services (dict | str): VCAP_SERVICES environment variable

53

- instance_name (str): Specific service instance name

54

- service_name (str): Service name in VCAP_SERVICES

55

- encoder (json.JSONEncoder): Custom JSON encoder

56

57

Returns:

58

Context manager yielding Cloudant client instance

59

"""

60

61

def couchdb(user, passwd, **kwargs):

62

"""

63

Create CouchDB session context manager.

64

65

Parameters:

66

- user (str): Username for authentication

67

- passwd (str): Password for authentication

68

- url (str): CouchDB server URL

69

- encoder (json.JSONEncoder): Custom JSON encoder

70

71

Returns:

72

Context manager yielding CouchDB client instance

73

"""

74

75

def couchdb_admin_party(**kwargs):

76

"""

77

Create CouchDB session in Admin Party mode (no authentication).

78

79

Parameters:

80

- url (str): CouchDB server URL

81

- encoder (json.JSONEncoder): Custom JSON encoder

82

83

Returns:

84

Context manager yielding CouchDB client instance

85

"""

86

```

87

88

### Client Classes

89

90

Direct client instantiation for advanced use cases requiring manual connection management.

91

92

```python { .api }

93

class CouchDB(dict):

94

"""

95

CouchDB client with session and database management.

96

"""

97

98

def __init__(self, user, auth_token, admin_party=False, **kwargs):

99

"""

100

Initialize CouchDB client.

101

102

Parameters:

103

- user (str): Username for authentication

104

- auth_token (str): Authentication token/password

105

- admin_party (bool): Enable Admin Party mode

106

- url (str): Server URL

107

- encoder (json.JSONEncoder): Custom JSON encoder

108

- adapter (requests.HTTPAdapter): Custom HTTP adapter

109

- connect (bool): Auto-connect on initialization

110

- auto_renew (bool): Automatic session renewal

111

- timeout (float | tuple): Request timeout

112

- use_basic_auth (bool): Force basic authentication

113

- use_iam (bool): Use IAM authentication

114

- iam_client_id (str): IAM client ID

115

- iam_client_secret (str): IAM client secret

116

"""

117

118

def connect(self):

119

"""

120

Establish connection and authenticate session.

121

122

Returns:

123

None

124

125

Raises:

126

CloudantClientException: Authentication failure

127

"""

128

129

def disconnect(self):

130

"""

131

Close session and cleanup resources.

132

133

Returns:

134

None

135

"""

136

137

def change_credentials(self, user=None, auth_token=None):

138

"""

139

Update authentication credentials for active session.

140

141

Parameters:

142

- user (str): New username

143

- auth_token (str): New authentication token

144

145

Returns:

146

None

147

"""

148

149

def session(self):

150

"""

151

Get current session information.

152

153

Returns:

154

dict: Session details including user context and authentication info

155

"""

156

157

def session_cookie(self):

158

"""

159

Get session authentication cookie.

160

161

Returns:

162

str: Session cookie value

163

"""

164

165

def session_login(self, user=None, passwd=None):

166

"""

167

Perform explicit session login.

168

169

Parameters:

170

- user (str): Username (uses instance user if None)

171

- passwd (str): Password (uses instance token if None)

172

173

Returns:

174

dict: Login response with session details

175

"""

176

177

def session_logout(self):

178

"""

179

Perform explicit session logout.

180

181

Returns:

182

dict: Logout response

183

"""

184

185

def basic_auth_str(self):

186

"""

187

Generate basic authentication string.

188

189

Returns:

190

str: Base64 encoded basic auth header value

191

"""

192

193

class Cloudant(CouchDB):

194

"""

195

Cloudant-specific client with additional cloud features.

196

"""

197

198

@classmethod

199

def iam(cls, account_name, api_key, **kwargs):

200

"""

201

Create Cloudant client with IAM authentication.

202

203

Parameters:

204

- account_name (str): Cloudant account name

205

- api_key (str): IAM API key

206

- iam_client_id (str): IAM client ID (optional)

207

- iam_client_secret (str): IAM client secret (optional)

208

209

Returns:

210

Cloudant: Configured client instance

211

"""

212

213

@classmethod

214

def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs):

215

"""

216

Create Cloudant client from Cloud Foundry VCAP_SERVICES.

217

218

Parameters:

219

- vcap_services (dict | str): VCAP_SERVICES environment variable

220

- instance_name (str): Service instance name

221

- service_name (str): Service name

222

223

Returns:

224

Cloudant: Configured client instance

225

"""

226

227

@property

228

def is_iam_authenticated(self):

229

"""

230

Check if using IAM authentication.

231

232

Returns:

233

bool: True if using IAM authentication

234

"""

235

```

236

237

### Cloud Foundry Service Utility

238

239

```python { .api }

240

class CloudFoundryService:

241

"""

242

Parse and access Cloud Foundry service credentials.

243

"""

244

245

def __init__(self, vcap_services, instance_name=None, service_name=None):

246

"""

247

Parse VCAP_SERVICES for Cloudant credentials.

248

249

Parameters:

250

- vcap_services (dict | str): VCAP_SERVICES environment variable

251

- instance_name (str): Specific service instance name

252

- service_name (str): Service name in VCAP_SERVICES

253

"""

254

255

@property

256

def username(self):

257

"""Service username"""

258

259

@property

260

def password(self):

261

"""Service password"""

262

263

@property

264

def url(self):

265

"""Service URL"""

266

267

@property

268

def iam_api_key(self):

269

"""IAM API key if available"""

270

```

271

272

## Usage Examples

273

274

### Basic Authentication

275

276

```python

277

from cloudant import cloudant

278

279

# Using context manager (recommended)

280

with cloudant('myusername', 'mypassword', account='myaccount') as client:

281

print(f"Connected to: {client.server_url}")

282

print(f"Session: {client.session()}")

283

284

# List databases

285

databases = client.all_dbs()

286

print(f"Databases: {databases}")

287

288

# Manual connection management

289

from cloudant.client import Cloudant

290

291

client = Cloudant('myusername', 'mypassword', account='myaccount')

292

client.connect()

293

try:

294

# Work with client

295

pass

296

finally:

297

client.disconnect()

298

```

299

300

### IAM Authentication

301

302

```python

303

from cloudant import cloudant_iam

304

305

with cloudant_iam('myaccount', 'my-iam-api-key') as client:

306

print(f"IAM authenticated: {client.is_iam_authenticated}")

307

databases = client.all_dbs()

308

```

309

310

### Cloud Foundry Integration

311

312

```python

313

import os

314

from cloudant import cloudant_bluemix

315

316

# Automatic parsing of VCAP_SERVICES

317

with cloudant_bluemix(os.getenv('VCAP_SERVICES'), 'Cloudant NoSQL DB') as client:

318

databases = client.all_dbs()

319

320

# Manual service parsing

321

from cloudant._common_util import CloudFoundryService

322

323

service = CloudFoundryService(os.getenv('VCAP_SERVICES'), service_name='cloudantNoSQLDB')

324

print(f"Service URL: {service.url}")

325

print(f"Username: {service.username}")

326

```

327

328

### CouchDB Admin Party Mode

329

330

```python

331

from cloudant import couchdb_admin_party

332

333

# Connect to CouchDB in Admin Party mode (no authentication)

334

with couchdb_admin_party(url='http://localhost:5984') as client:

335

print("Connected to CouchDB in Admin Party mode")

336

337

# Admin Party mode allows unrestricted access

338

databases = client.all_dbs()

339

print(f"Databases: {databases}")

340

341

# Create database without authentication

342

db = client.create_database('admin_party_test')

343

344

# Create documents without authentication

345

doc = db.create_document({'message': 'Admin Party enabled'})

346

print(f"Created document: {doc['_id']}")

347

348

# Manual CouchDB client with Admin Party

349

from cloudant.client import CouchDB

350

351

client = CouchDB(None, None, admin_party=True, url='http://localhost:5984')

352

client.connect()

353

try:

354

# Work with CouchDB in Admin Party mode

355

all_dbs = client.all_dbs()

356

finally:

357

client.disconnect()

358

```

359

360

### Connection Options

361

362

```python

363

from cloudant import cloudant

364

365

# With custom timeout and auto-renewal

366

with cloudant('user', 'pass',

367

account='myaccount',

368

timeout=(10, 60), # 10s connect, 60s read

369

auto_renew=True) as client:

370

# Long-running operations with automatic session renewal

371

pass

372

373

# With custom encoder

374

import json

375

376

class CustomEncoder(json.JSONEncoder):

377

def default(self, obj):

378

# Custom encoding logic

379

return super().default(obj)

380

381

with cloudant('user', 'pass',

382

account='myaccount',

383

encoder=CustomEncoder) as client:

384

# Documents will use custom encoder

385

pass

386

```

387

388

## Error Handling

389

390

Authentication-related errors are raised as `CloudantClientException`:

391

392

```python

393

from cloudant import cloudant

394

from cloudant.error import CloudantClientException

395

396

try:

397

with cloudant('invalid_user', 'invalid_pass', account='myaccount') as client:

398

databases = client.all_dbs()

399

except CloudantClientException as e:

400

print(f"Authentication failed: {e}")

401

```