def deauthorize(): """ Deauthorize the user's Google API session. """ storage = Storage(credential_storage + user.username + '.dat') try: storage.delete() except OSError: pass # No credential file was found. return redirect(url_for('cal'))
def DeleteCred(): '''Remove stored Oauth credentials.''' home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.Drive-credentials') credential_path = os.path.join(credential_dir, 'credential.json') if not os.path.exists(credential_path): print 'No OAuth token found, all ok' return store = Storage(credential_path) store.delete() print 'Access removed' return
def deletecred(request): """ Process för att logga ut. Tar bort sparade credentials. """ try: storage = Storage('courses') storage.delete() except FileNotFoundError: print("Saknar Storage('courses')") try: storage = Storage('rosters') storage.delete() except FileNotFoundError: print("Saknar Storage('rosters')") return HttpResponseRedirect('/classroom')
def test_credentials_delete(self): access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) s = Storage(FILENAME) s.put(credentials) credentials = s.get() self.assertNotEquals(None, credentials) s.delete() credentials = s.get() self.assertEquals(None, credentials)
def test_credentials_delete(self): access_token = 'foo' client_id = 'some_client_id' client_secret = 'cOuDdkfjxxnv+' refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' credentials = OAuth2Credentials( access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) s = Storage(FILENAME) s.put(credentials) credentials = s.get() self.assertNotEquals(None, credentials) s.delete() credentials = s.get() self.assertEquals(None, credentials)
def list_files(self, request): user_id = request.body.get("userId") storage = Storage(CREDS_FILE) credentials = storage.get() now = datetime.now() year = str(now.year) month = '0' + str(now.month) if now.month < 10 else str(now.month) day = '0' + str(now.day) if now.day < 10 else str(now.day) tmp_path = os.path.join(settings.MEDIA_ROOT + str(user_id) + "/" + year + month + day + "/") http = httplib2.Http() http = credentials.authorize(http) drive_service = build("drive", "v2", http=http) print("drive_service", drive_service) for x in self.get_list(drive_service): labels = x.get('labels') if (x.get('title')) and x.get('alternateLink') and x.get( 'shared') == False and labels['trashed'] == False: # 구글 드라이브 관련 메타 데이타 저장 box_file = BoxFile() box_file.fi_bsusserid = user_id box_file.fi_bsdiv = "V" box_file.fi_bsname = "GD" box_file.fi_name = x.get('title') box_file.fi_path = x.get('alternateLink') print("구글 드라이브 내용", x) # 폴더 정보 가져오기 # for y in self.print_files_in_folder(drive_service, ) # 구글 드라이브에 파일이 저장되어 있을경우 파일을 다운로드 하여 S3에 업로드 # 그 외에 링크는 해당 링크 정보 저장 if x.get('webContentLink') is not None: # fileid를 가지고 구글드라이브에서 파일정보를 가져옴 file = drive_service.files().get_media(fileId=x.get('id')) print("tmp_path=================", tmp_path) if not os.path.isdir(tmp_path): os.mkdir(tmp_path) file_path = tmp_path + x.get('title') fh = io.FileIO(file_path, 'wb') downloader = MediaIoBaseDownload(fh, file) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%" % int(status.progress() * 100)) if done is True: with open(file_path, 'rb') as data: server_path = FileExplorer.fileUpload(file=data) data.close() box_file.fi_name = data.name.split("/")[-1] box_file.fi_path = server_path # 구글드라이브 관련 정보 별도로 저장 google_drive = Googledrivefiles() # 부모폴더 처리 parent_info = x.get('parents') if parent_info: parent = parent_info[0] if parent['isRoot'] == True: box_file.fi_is_root = True else: box_file.fi_is_root = False param = {} children = drive_service.children().list( folderId=x.get('id'), **param).execute() print("children===============", children) google_drive.parentid = parent['id'] # 폴더여부 확인 및 파일 아이콘 타입 설정 mimetype = x.get('mimeType') print("mimetype", mimetype) if mimetype == 'application/vnd.google-apps.folder': box_file.fi_is_folder = True box_file.fi_icon_type = 'folder' elif mimetype == 'application/vnd.google-apps.spreadsheet': box_file.fi_icon_type = 'spreadsheet' elif mimetype == 'application/vnd.google-apps.presentation': box_file.fi_icon_type = 'presentation' elif mimetype == 'application/vnd.google-apps.document': box_file.fi_icon_type = 'document' elif mimetype == 'application/vnd.ms-excel': box_file.fi_icon_type = 'ms-excel' elif mimetype == 'image/png' or mimetype == 'image/jpeg': box_file.fi_icon_type = 'image' elif mimetype == 'application/vnd.openxmlformats-officedocument.presentationml.presentation': box_file.fi_icon_type = 'presentation' else: box_file.fi_icon_type = 'etc' box_file.fi_status = "G" box_file.fi_createdate = x.get('createdDate') box_file.fi_modifydate = x.get('modifiedDate') box_file.fi_file_size = x.get('fileSize') box_file.fi_mimetype = mimetype box_file.fi_ext = x.get('fileExtension') box_file.save() google_drive.box_file_id = box_file google_drive.filename = box_file.fi_name google_drive.filepath = x.get('webContentLink') google_drive.modifydate = x.get('modifiedDate') google_drive.mimetype = mimetype google_drive.googledrivefileid = x.get('id') google_drive.save() storage.delete() # # 구글드라이브에 있는 파일을 다운로드후 삭제 # shutil.rmtree(tmp_path) return tmp_path
class Account(object): def __init__(self, persistent_dir): self.persistent_dir = persistent_dir self.storage = Storage(os.path.join(self.persistent_dir, 'oauth_storage')) self._user_info = None self._get_user_info() @property def is_logged_in(self): return True if self.storage.get() else False def get_credentials(self): return self.storage.get() def refresh_credentials(self): creds = self.get_credentials() if creds: creds.refresh(httplib2.Http()) def get_access_token(self): creds = self.get_credentials() token_info = creds.get_access_token() return token_info.access_token bearer_token = property(get_access_token) @property def id(self): return self._get_user_info()['id'] @property def name(self): return self._get_user_info()['name'] @property def email(self): return self._get_user_info()['email'] @property def roles(self): return self._get_user_info()['roles'] @property def legacy_id(self): return self._get_user_info()['legacy_id'] @property def _user_info_path(self): return os.path.join(self.persistent_dir, 'user_info') # hack to fix null token expiration def _set_expiration_to_long_time(self, creds): cred_str = creds.to_json() cred_json = json.loads(cred_str) # in case it might have an expiration if(cred_json['token_expiry'] is not None): return creds cred_json['token_expiry'] = '2100-01-01T00:00:01Z' cred_new_json = json.dumps(cred_json) return Credentials.new_from_json(cred_new_json) def login(self, args): creds = self._set_expiration_to_long_time(tools.run_flow(flow, self.storage, args)) self.storage.put(creds) self.user_info = self._get_user_info() def logout(self): self.storage.delete() os.unlink(self._user_info_path) def _get_user_info(self): if self._user_info is not None: return self._user_info if not self.is_logged_in: return None file_path = self._user_info_path try: with open(file_path) as f: return json.load(f) except (IOError, ValueError): with open(file_path, 'w') as f: result = requests.get(ME_URI, headers={'Authorization': 'Bearer %s' % self.get_access_token()}) result.raise_for_status() account_info = result.json() stored_info = { 'id': account_info['uid'], 'name': account_info['name'], 'roles': account_info['scopes'], 'legacy_id': None } json.dump(stored_info, f) self._user_info = stored_info return self._user_info
class Account(object): def __init__(self, persistent_dir): self.persistent_dir = persistent_dir self.storage = Storage(os.path.join(self.persistent_dir, 'oauth_storage')) self._user_info = None self._get_user_info() @property def is_logged_in(self): return True if self.storage.get() else False def get_credentials(self): return self.storage.get() def refresh_credentials(self): creds = self.get_credentials() if creds: creds.refresh(httplib2.Http()) def get_access_token(self): creds = self.get_credentials() token_info = creds.get_access_token() return token_info.access_token bearer_token = property(get_access_token) @property def id(self): return self._get_user_info()['id'] @property def name(self): return self._get_user_info()['name'] @property def email(self): return self._get_user_info()['email'] @property def roles(self): return self._get_user_info()['roles'] @property def legacy_id(self): return self._get_user_info()['legacy_id'] @property def _user_info_path(self): return os.path.join(self.persistent_dir, 'user_info') # hack to fix null token expiration def _set_expiration_to_long_time(self, creds): cred_str = creds.to_json() cred_json = json.loads(cred_str) # in case it might have an expiration if(cred_json['token_expiry'] is not None): return creds cred_json['token_expiry'] = '2100-01-01T00:00:01Z' cred_new_json = json.dumps(cred_json) return Credentials.new_from_json(cred_new_json) def login(self, args): creds = self._set_expiration_to_long_time(tools.run_flow(flow, self.storage, args)) self.storage.put(creds) self.user_info = self._get_user_info() def logout(self): self.storage.delete() os.unlink(self._user_info_path) def _get_user_info(self): if self._user_info is not None: return self._user_info if not self.is_logged_in: return None file_path = self._user_info_path try: with open(file_path) as f: return json.load(f) except (IOError, ValueError): with open(file_path, 'w') as f: result = requests.get(ME_URI, headers={'Authorization': 'Bearer %s' % self.get_access_token()}) result.raise_for_status() account_info = result.json() stored_info = { 'id': account_info['id'], 'name': account_info['name'], 'email': account_info['email'], 'roles': account_info['roles'], 'legacy_id': account_info.get('legacy_id', None) } json.dump(stored_info, f) self._user_info = stored_info return self._user_info