File: orgunit_quick_start_example.py

package info (click to toggle)
python-gdata 2.0.17%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 26,080 kB
  • sloc: python: 73,579; ansic: 150; sh: 33; makefile: 11
file content (473 lines) | stat: -rw-r--r-- 15,135 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Sample for the Orgunits Provisioning API to demonstrate all methods.

Usage:
  $ python orgunit_quick_start_example.py

You can also specify the  user credentials from the command-line

  $ python orgunit_quick_start_example.py
    --client_id [client_id] --client_secret [client_scret] --domain [domain]

You can get help for command-line arguments as

  $ python orgunit_quick_start_example.py --help
"""

__author__ = 'Shraddha Gupta <shraddhag@google.com>'

import getopt
import sys
import gdata.apps.client
from gdata.apps.organization.client import OrganizationUnitProvisioningClient
import gdata.client
import gdata.gauth

SCOPE = 'https://apps-apis.google.com/a/feeds/policies/'
USER_AGENT = 'OrgUnitProvisioningQuickStartExample'


class OrgUnitProvisioning(object):
  """Demonstrates all the functions of org units provisioning."""

  def __init__(self, client_id, client_secret, domain):
    """
    Args:
      client_id: [string] The clientId of the developer.
      client_secret: [string] The clientSecret of the developer.
      domain: [string] The domain on which the functions are to be performed.
    """
    self.client_id = client_id
    self.client_secret = client_secret
    self.domain = domain

  def _AuthorizeClient(self):
    """Authorize the client for making API requests."""

    self.token = gdata.gauth.OAuth2Token(
        client_id=self.client_id, client_secret=self.client_secret,
        scope=SCOPE, user_agent=USER_AGENT)
    uri = self.token.generate_authorize_url()
    print 'Please visit this URL to authorize the application:'
    print uri
    # Get the verification code from the standard input.
    code = raw_input('What is the verification code? ').strip()
    self.token.get_access_token(code)
    self.client = OrganizationUnitProvisioningClient(
        domain=self.domain, auth_token=self.token)

  def _PrintCustomerIdDetails(self, entry):
    """Prints the attributes for a CustomerIdEntry.

    Args:
      entry: [gdata.apps.organization.data.CustomerIdEntry]
    """
    print '\nCustomer Id: %s' % (entry.customer_id)
    print 'Org unit name: %s' % (entry.org_unit_name)
    print 'Customer org unit name: %s' % (entry.customer_org_unit_name)
    print 'Org unit description: %s' % (entry.org_unit_description)
    print 'Customer org unit description: %s' % (
        entry.customer_org_unit_description)

  def _PrintOrgUnitDetails(self, entry):
    """Prints the attributes for a OrgUnitEntry.

    Args:
      entry: [gdata.apps.organization.data.OrgUnitEntry]
    """
    if entry:
      print '\nOrg unit name: %s' % (entry.org_unit_name)
      print 'Org unit path: %s' % (entry.org_unit_path)
      print 'Parent org unit path: %s' % (entry.parent_org_unit_path)
      print 'organization unit description: %s' % (entry.org_unit_description)
      print 'Block inheritance flag: %s' % (entry.org_unit_block_inheritance)
    else:
      print 'null entry'

  def _PrintOrgUserDetails(self, entry):
    """Prints the attributes for a OrgUserEntry.

    Args:
      entry: [gdata.apps.organization.data.OrgUserEntry]
    """
    if entry:
      print 'Org user email: %s' % (entry.user_email)
      print 'Org unit path: %s' % (entry.org_unit_path)
    else:
      print 'null entry'

  def _GetChoice(self, for_field):
    """Gets input for boolean fields.
    
    Args:
      for_value : string field for which input is required

    Returns:
      boolean input for the given field
    """
    choice = raw_input(('(Optional) Enter a choice for %s\n'
                        '1-True 2-False ') % (for_field))
    if choice == '1':
      return True
    return False

  def _GetOrgUnitPath(self):
    """Gets org_unit_path from user.

    Returns:
      string org_unit_path entered by the user
    """

    org_unit_path = raw_input('Enter the org unit path ')
    if org_unit_path is None:
      print 'Organization path missing\n'
      return
    return org_unit_path

  def _RetrieveCustomerId(self):
    """Retrieves Groups Apps account customerId.

    Returns:
      CustomerIdEntry
    """

    response = self.client.RetrieveCustomerId()
    self._PrintCustomerIdDetails(response)
    return response

  def _CreateOrgUnit(self, customer_id):
    """Creates a new org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    name = raw_input('Enter a name for organization: ')
    parent_org_unit_path = raw_input('(default "/")'
        'Enter full path of the parentental tree: ')
    description = raw_input('(Optional) Enter description of organization: ')
    block_inheritance = self._GetChoice('(default: False) block_inheritance: ')
    if not parent_org_unit_path:
      parent_org_unit_path = '/'
    try:
      orgunit_entry = self.client.CreateOrgUnit(
          customer_id=customer_id, name=name,
          parent_org_unit_path=parent_org_unit_path,
          description=description, block_inheritance=block_inheritance)
      self._PrintOrgUnitDetails(orgunit_entry)
      print 'Org unit Created'
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _UpdateOrgUnit(self, customer_id):
    """Updates an org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    if org_unit_path is None:
      return
    try:
      org_unit_entry = self.client.RetrieveOrgUnit(customer_id=customer_id,
          org_unit_path=org_unit_path)
      print self._PrintOrgUnitDetails(org_unit_entry)
      attributes = {1: 'org_name', 2: 'parent_org_unit_path', 3: 'description',
                    4: 'block_inheritance'}
      print attributes
      while True:
        attr = int(raw_input('\nEnter number(1-4) of attribute to be updated'))
        updated_val = raw_input('Enter updated value ')
        if attr == 1:
          org_unit_entry.org_unit_name = updated_val
        if attr == 2:
          org_unit_entry.parent_org_unit_path = updated_val
        if attr == 3:
          org_unit_entry.org_unit_description = updated_val
        if attr == 4:
          org_unit_entry.login.org_unit_block_inheritance = updated_val
        choice = raw_input('\nDo you want to update more attributes y/n')
        if choice != 'y':
          break
      self.client.UpdateOrgUnit(customer_id=customer_id,
          org_unit_path=org_unit_path, org_unit_entry=org_unit_entry)
      print 'Updated Org unit'
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _RetrieveOrgUnit(self, customer_id):
    """Retrieves a single org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    if org_unit_path is None:
      return
    try:
      response = self.client.RetrieveOrgUnit(customer_id=customer_id,
          org_unit_path=org_unit_path)
      self._PrintOrgUnitDetails(response)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _RetrieveAllOrgUnits(self, customer_id):
    """Retrieves all org units.
    
    Args:
      customer_id : string customer_id of organization
    """    
    try:
      response = self.client.RetrieveAllOrgUnits(customer_id=customer_id)
      for entry in response.entry:
        self._PrintOrgUnitDetails(entry)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _RetrieveSubOrgUnits(self, customer_id):
    """Retrieves all sub org units of an org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    if org_unit_path is None:
      return
    try:
      response = self.client.RetrieveSubOrgUnits(customer_id=customer_id,
          org_unit_path=org_unit_path)
      if not response.entry:
        print 'No Sub organization units'
        return
      for entry in response.entry:
        self._PrintOrgUnitDetails(entry)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _MoveUsers(self, customer_id):
    """Moves users to an org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    if org_unit_path is None:
      return
    users = []
    while True:
      user = raw_input('Enter user email address ')
      if user:
        users.append(user)
      else:
        break
    if users is None:
      print 'No users given to move'
      return
    try:
      self.client.MoveUserToOrgUnit(customer_id=customer_id,
          org_unit_path=org_unit_path, users_to_move=users)
      print 'Moved users'
      print users
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _DeleteOrgUnit(self, customer_id):
    """Deletes an org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    if org_unit_path is None:
      return
    try:
      self.client.DeleteOrgUnit(customer_id=customer_id,
          org_unit_path=org_unit_path)
      print 'OrgUnit Deleted'
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _UpdateOrgUser(self, customer_id):
    """Updates the orgunit of an org user.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    user_email = raw_input('Enter the email address')
    if None in (org_unit_path, user_email):
      print 'Organization path and email are both required\n'
      return
    try:
      org_user_entry = self.client.UpdateOrgUser(customer_id=customer_id,
          user_email=user_email, org_unit_path=org_unit_path)
      print 'Updated org unit for user'
      print self._PrintOrgUserDetails(org_user_entry)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _RetrieveOrgUser(self, customer_id):
    """Retrieves an organization user.
    
    Args:
      customer_id : string customer_id of organization
    """
    user_email = raw_input('Enter the email address ')
    if user_email is None:
      print 'Email address missing\n'
      return
    try:
      response = self.client.RetrieveOrgUser(customer_id=customer_id,
          user_email=user_email)
      self._PrintOrgUserDetails(response)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _RetrieveOrgUnitUsers(self, customer_id):
    """Retrieves all org users of an org unit.
    
    Args:
      customer_id : string customer_id of organization
    """
    org_unit_path = self._GetOrgUnitPath()
    if org_unit_path is None:
      return
    try:
      response = self.client.RetrieveOrgUnitUsers(customer_id=customer_id,
          org_unit_path=org_unit_path)
      if not response.entry:
        print 'No users in this organization'
        return
      for entry in response.entry:
        self._PrintOrgUserDetails(entry)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def _RetrieveAllOrgUsers(self, customer_id):
    """Retrieves all org users.
    
    Args:
      customer_id : string customer_id of organization
    """
    try:
      response = self.client.RetrieveAllOrgUsers(customer_id=customer_id)
      for entry in response.entry:
        self._PrintOrgUserDetails(entry)
    except gdata.client.RequestError, e:
      print e.reason, e.body
      return

  def Run(self):
    """Runs the sample by getting user input and taking appropriate action."""

    self._AuthorizeClient()
    # CustomerId is required to perform any opertaion on org unit
    # Retrieve customerId beforehand.
    customer_id_entry = self._RetrieveCustomerId()
    customer_id = customer_id_entry.customer_id

    # List of all the functions and their descriptions
    functions_list = [
        {'function': self._CreateOrgUnit,
         'description': 'Create an org unit'},
        {'function': self._UpdateOrgUnit,
         'description': 'Update an org unit'},
        {'function': self._RetrieveOrgUnit,
         'description': 'Retrieve an org unit'},
        {'function': self._RetrieveAllOrgUnits,
         'description': 'Retrieve all org units'},
        {'function': self._RetrieveSubOrgUnits,
         'description': 'Retrieve sub org unit of a given org unit'},
        {'function': self._MoveUsers,
         'description': 'Move users to an org unit'},
        {'function': self._DeleteOrgUnit,
         'description': 'Delete an org unit'},
        {'function': self._UpdateOrgUser,
         'description': 'Update org unit of a user'},
        {'function': self._RetrieveOrgUser,
         'description': 'Retrieve an org user '},
        {'function': self._RetrieveOrgUnitUsers,
         'description': 'Retrieve users of an org unit'},
        {'function': self._RetrieveAllOrgUsers,
         'description': 'Retrieve all org users'}
    ]
    while True:
      print '\nChoose an option:\n0 - to exit'
      for i in range (0, len(functions_list)):
        print '%d - %s' % ((i+1), functions_list[i]['description'])
      choice = int(raw_input())
      if choice == 0:
        break
      if choice < 0 or choice > 11:
        print 'Not a valid option!'
        continue
      functions_list[choice-1]['function'](customer_id=customer_id)


def main():
  """A menu driven application to demo all methods of org unit provisioning."""

  usage = ('python orgunit_quick_start_example.py '
           '--client_id [clientId] --client_secret [clientSecret] '
           '--domain [domain]')
  # Parse command line options
  try:
    opts, args = getopt.getopt(sys.argv[1:], '', ['client_id=',
                                                  'client_secret=',
                                                  'domain='])
  except getopt.error:
    print 'Usage: %s' % usage
    return

  client_id = None
  client_secret = None
  domain = None
  # Parse options
  for option, arg in opts:
    if option == '--client_id':
      client_id = arg
    elif option == '--client_secret':
      client_secret = arg
    elif option == '--domain':
      domain = arg

  if None in (client_id, client_secret, domain):
    print 'Usage: %s' % usage
    return

  try:
    orgunit_provisioning = OrgUnitProvisioning(
        client_id, client_secret, domain)
  except gdata.service.BadAuthentication:
    print 'Invalid user credentials given.'
    return

  orgunit_provisioning.Run()


if __name__ == '__main__':
  main()