Esempio n. 1
0
 def start_auth_telegram(self, client_config):
     if self.telegram_bot is None:
         t.log_message('telegram bot is None. Telegram auth canceled.')
         return
     auth = GoogleAuth()
     auth.LoadClientConfigFile(client_config_file=client_config)
     if auth.flow is None:
         auth.GetFlow()
     auth.flow.redirect_uri = OOB_CALLBACK_URN
     self.telegram_bot.send_message(
         'Please go to the following link in your browser and send me a Google verification code. \nAuth url: '
         + auth.GetAuthUrl())
     dirty = False
     code = None
     save_credentials = auth.settings.get('save_credentials')
     if auth.credentials is None and save_credentials:
         auth.LoadCredentials()
     if auth.credentials is None:
         code = self.telegram_bot.get_code()
         dirty = True
     else:
         if auth.access_token_expired:
             if auth.credentials.refresh_token is not None:
                 auth.Refresh()
             else:
                 code = self.telegram_bot.get_code()
             dirty = True
     if code is not None:
         auth.Auth(code)
     if dirty and save_credentials:
         auth.SaveCredentials()
     return auth
Esempio n. 2
0
def google_sign(request):
    gauth = GoogleAuth()
    scope = {'oauth_scope': ['https://www.googleapis.com/auth/drive']}
    gauth.DEFAULT_SETTINGS.update(scope)

    try:
        access = AccessToken.objects.get(user=request.user)

        if access.token is '':
            print('nothing to worry here')
        else:
            gauth.credentials = client.Credentials.new_from_json(access.token)

    except ObjectDoesNotExist:
        return "<h1> You did not setup any SasS account</h1>"

    if gauth.credentials is None:
        # Authenticate if they're not there
        authorize_url = gauth.GetAuthUrl()
        webbrowser.open(authorize_url, new=1, autoraise=True)

        return render(request, 'google_form.html')

    elif gauth.access_token_expired:
        # Refresh them if expired
        print('Refresh')
        gauth.Refresh()
    else:
        # Initialize the saved creds
        print('Authorized')
        gauth.Authorize()

    return redirect('/dashboard/config/')
Esempio n. 3
0
def backupData(dataPath, night):
    """
    backup raw images to ashleys google drive
    """
    # Collect data files to upload
    files = glob.glob(dataPath + "/*.fits")

    # Start pydrive instance
    gauth = GoogleAuth()
    auth_url = gauth.GetAuthUrl(
    )  # Create authentication url user needs to visit
    gauth.LocalWebserverAuth(
    )  #will this require me to click a button every time?????
    #http://pythonhosted.org/PyDrive/oauth.html#customizing-authentication-with-settings-yaml
    drive = GoogleDrive(gauth)

    # Check if folder in CAMAL_data for night
    camalid = '0BxAnuNxRgJ3vcWN5TVV4Q0J3NUE'  # id of CAMAL data folder
    file_list = drive.ListFile({
        'q':
        "'%s' in parents and trashed=false" % camalid
    }).GetList()
    folders = {}
    for f in file_list:
        if f['mimeType'] == 'application/vnd.google-apps.folder':  # if folder
            folders[str(f['title'])] = str(f['id'])
    logging.info('Create Folder in Google Drive for Back Up')
    if night in folders.keys():
        nightid = folders[night]  # store night id
    else:
        # Create folder
        nightfolder = drive.CreateFile({
            'title':
            night,
            "parents": [{
                "id": camalid
            }],
            "mimeType":
            "application/vnd.google-apps.folder"
        })
        nightfolder.Upload()

    # Upload Files to night's folder
    for filepath in files:
        fname = filepath.split('\\')[-1]
        f = drive.CreateFile({
            'title':
            fname,
            "parents": [{
                "kind": "drive#fileLink",
                "id": nightid
            }]
        })
        f.SetContentFile(filepath)
        f.Upload()

    logging.info('Successfully Uploaded Files from %s' % night)
Esempio n. 4
0
def ask_for_credentials():

    logger.log( 'Asking user for credentials' )
    
    client_secrets_path = BASE_DIR + "/client_secrets.json" 
    
    GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = client_secrets_path
        
    # Create google account authentication objects
    gauth = GoogleAuth()
    return gauth.GetAuthUrl()
def oauth2callback(request):
    gauth = GoogleAuth()
    if not request.GET.get('code', False):
        auth_url = gauth.GetAuthUrl()
        redirect_view = request.GET.get('redirect_view', '')
        auth_url += "&state={0}".format(redirect_view)
        return redirect(auth_url)
    else:
        code = request.GET.get('code')
        gauth.Authenticate(code)
        request.session['credentials'] = gauth.credentials.to_json()
        redirect_view = request.GET.get('state', '')
        return redirect(redirect_view)
    def start(self, update: Update, context: CallbackContext) -> int:
        user = update.message.from_user
        user_params = self.m_driver.get_user_params(user.id)
        if bool(user_params):
            update.message.reply_text(already_onboarded_message)
            return ConversationHandler.END

        g_login = GoogleAuth(settings_file)
        context.user_data['auth_object'] = g_login
        auth_url = g_login.GetAuthUrl()

        update.message.reply_text(follow_link_message + f'{auth_url}')
        return ACCESS_CODE
Esempio n. 7
0
 def __init__(self):
     gauth = GoogleAuth()
     gauth.LoadCredentialsFile("credentials.txt")
     if gauth.credentials is None:
         print(gauth.GetAuthUrl())
         gauth.CommandLineAuth()
     elif gauth.access_token_expired:
         logger.info('refresh token')
         gauth.Refresh()
     else:
         logger.info('authorized')
         gauth.Authorize()
     gauth.SaveCredentialsFile("credentials.txt")
     self._gauth = gauth
     self._drive = GoogleDrive(self._gauth)
def drive_auth():
    gauth = GoogleAuth()
    # Try to load saved client credentials
    #gauth.client_config_file = client_secrets_path
    print(gauth.client_config)

    if (os.path.exists(creds_path)):
        gauth.LoadCredentialsFile(creds_path)
    if gauth.credentials is None:
        with open(client_secrets_path) as f:
            data = json.load(f)
            data = data['web']
            print(data)
            client_id = data['client_id']
            client_secret = data['client_secret']
            redirect_ris = data['redirect_uris']
            auth_uri = data['auth_uri']
            '''
            gauth.client_config['client_id']=client_id
            gauth.client_config['client_secret']=client_secret
            #gauth.client_config['redirect_uris']=redirect_uris
            gauth.client_config['auth_uri']=auth_uri
            gauth.client_config['access_type']='offline'
            '''

            # print(gauth.client_config)
            # Authenticate if they're not there
            url = "https:www.google.com"
            #webbrowser.open_new_tab(url)
            auth_url = gauth.GetAuthUrl()
            # Create authentication url user needs to visit
            code = CustomLocalWebserverAuth(auth_url)
            # Your customized authentication flow
            gauth.Auth(code)  # Authorize and build service from the code
            #gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        # Initialize the saved creds
        gauth.Authorize()
    # Save the current credentials to a file
    gauth.SaveCredentialsFile(creds_path)

    print(gauth.credentials)
    drive = GoogleDrive(gauth)

    return drive
    def onchange_backup_destination(self):
        if self.backup_destination == 'ftp':
            self.ftp_port = 21

        if self.backup_destination == 'sftp':
            self.ftp_port = 22
            if no_pysftp:
                raise exceptions.Warning(
                    _('Missing required pysftp python package\n'
                      'https://pypi.python.org/pypi/pysftp'))

        if self.backup_destination == 'dropbox':
            if no_dropbox:
                raise exceptions.Warning(
                    _('Missing required dropbox python package\n'
                      'https://pypi.python.org/pypi/dropbox'))
            flow = dropbox.DropboxOAuth2FlowNoRedirect('jqurrm8ot7hmvzh',
                                                       '7u0goz5nmkgr1ot')
            self.dropbox_authorize_url = flow.start()
            self.dropbox_authorize_url_rel = self.dropbox_authorize_url

            self.dropbox_flow = self.env['ir.attachment'].create(
                dict(
                    datas=base64.b64encode(pickle.dumps(flow)),
                    name='dropbox_flow',
                    # datas_fname='dropbox_flow',
                    description='Automatic Backup File')).id

        if self.backup_destination == 'google_drive':
            if no_pydrive:
                raise exceptions.Warning(
                    _('Missing required PyDrive python package\n'
                      'https://pypi.python.org/pypi/PyDrive'))
            secrets_path = os.path.dirname(
                os.path.realpath(__file__)
            ) + os.sep + '..' + os.sep + 'data' + os.sep + 'client_secrets.json'
            GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = secrets_path
            gauth = GoogleAuth()
            self.dropbox_authorize_url = gauth.GetAuthUrl()
            self.dropbox_authorize_url_rel = self.dropbox_authorize_url
            self.dropbox_flow = self.dropbox_flow = self.env[
                'ir.attachment'].create(
                    dict(
                        datas=base64.b64encode(pickle.dumps(gauth)),
                        name='dropbox_flow',
                        # datas_fname='dropbox_flow',
                        description='Automatic Backup File')).id
Esempio n. 10
0
def auth(server, info):
    gauth = GoogleAuth(DriveAPISecerts)
    gauth.LoadCredentialsFile(CredentialsFilePath)
    if gauth.credentials is None:
        auth_url = gauth.GetAuthUrl()
        server.execute(
            'tellraw ' + info.player +
            ' {"text":"[GDB]: 請前往 §6此網站§r 進行Google Drive取得登入金鑰","underlined":"false","clickEvent":{"action":"open_url","value":"'
            + auth_url + '"}}')
        print_message(server, info, "並使用!!gdb setToken <金鑰>進行登入設定")
        return None
    elif gauth.access_token_expired:
        gauth.Refresh()
    else:
        gauth.Authorize()
    gauth.SaveCredentialsFile(CredentialsFilePath)
    return gauth
Esempio n. 11
0
    def setup(self):
        #create authorization helper and load default settings
        gauth = GoogleAuth(
            xbmc.validatePath(
                xbmc.translatePath(utils.addon_dir() +
                                   '/resources/lib/pydrive/settings.yaml')))
        gauth.LoadClientConfigSettings()

        #check if this user is already authorized
        if (not xbmcvfs.exists(
                xbmc.translatePath(utils.data_dir() + "google_drive.dat"))):
            settings = {
                "client_id": self.CLIENT_ID,
                'client_secret': self.CLIENT_SECRET
            }

            drive_url = gauth.GetAuthUrl(settings)

            utils.log("Google Drive Authorize URL: " + drive_url)

            code = xbmcgui.Dialog().input(
                'Google Drive Validation Code',
                'Input the Validation code after authorizing this app')

            gauth.Auth(code)
            gauth.SaveCredentialsFile(
                xbmc.validatePath(
                    xbmc.translatePath(utils.data_dir() + 'google_drive.dat')))
        else:
            gauth.LoadCredentialsFile(
                xbmc.validatePath(
                    xbmc.translatePath(utils.data_dir() + 'google_drive.dat')))

        #create the drive object
        self.drive = GoogleDrive(gauth)

        #make sure we have the folder we need
        xbmc_folder = self._getGoogleFile(self.root_path)
        print xbmc_folder
        if (xbmc_folder == None):
            self.mkdir(self.root_path)
Esempio n. 12
0
 def onchange_backup_destination(self):
     if self.backup_destination == 'dropbox':
         if no_dropbox:
             raise exceptions.Warning(
                 _('Missing required dropbox python package\n'
                   'https://pypi.python.org/pypi/dropbox'))
         flow = dropbox.DropboxOAuth2FlowNoRedirect('jqurrm8ot7hmvzh',
                                                    '7u0goz5nmkgr1ot')
         self.dropbox_authorize_url = flow.start()
         self.dropbox_authorize_url_rel = self.dropbox_authorize_url
         self.dropbox_flow = pickle.dumps(flow)
     if self.backup_destination == 'google_drive':
         if no_pydrive:
             raise exceptions.Warning(
                 _('Missing required PyDrive python package\n'
                   'https://pypi.python.org/pypi/PyDrive'))
         secrets_path = os.path.dirname(
             os.path.realpath(__file__)
         ) + os.sep + '..' + os.sep + 'data' + os.sep + 'client_secrets.json'
         GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = secrets_path
         gauth = GoogleAuth()
         self.dropbox_authorize_url = gauth.GetAuthUrl()
         self.dropbox_authorize_url_rel = self.dropbox_authorize_url
         self.dropbox_flow = pickle.dumps(gauth)
Esempio n. 13
0
class CloudHandler:
	'''




	'''




	def __init__(self):
		self.DBConfig = AppConfig()
		self.FH = FileHandler()
		self.googleConfig = 'configs/gdrive.yaml'

	def ssl_seed(self,size=24, chars=string.ascii_uppercase + string.digits):
		self.randomString = ''.join(random.choice(chars) for _ in range(size))
		return self


	def authenticategoogle(self):
		self.ga = GoogleAuth(self.googleConfig)
		try:
			self.ga.LoadClientConfig()
			self.ga.LoadCredentials()
			self.ga.Authorize()
		except:
			return self.ga.GetAuthUrl()
			#code = raw_input("code: ").strip()
		else:
			return True
			#auth loaded ok

	def googleauthorize(self,authCode):
		code = authCode.strip()
		self.ga.Auth(code)
		self.ga.SaveCredentials()
		return True

	def googleupload(self,filename):
		packageName = filename
		self.ga = GoogleAuth(self.googleConfig)
		self.ga.LoadClientConfig()
		self.ga.LoadCredentials()
		self.ga.Authorize()
		drive = GoogleDrive(self.ga)
		#flist = drive.ListFile({'q': "title contains '.crypt' and trashed = false"})
		folderlistquery = drive.ListFile({'q': "title = 'SeccuDB' and mimeType = 'application/vnd.google-apps.folder' and trashed = false"})
		

		cloudfolder = folderlistquery.GetList()
		if (len(cloudfolder) == 0):
			#create folder 
			folder = drive.CreateFile()
			folder['title'] = "SeccuDB"
			folder['mimeType'] = "application/vnd.google-apps.folder"
			folder['parents'] = "root"
			folder.Upload()
			cloudfolder = folderlistquery.GetList()
			if (len(cloudfolder) == 0):
				print "error"
				raise error('GooglePermissionsError')


		cloudfolderid = cloudfolder[0]['id']
		print cloudfolderid

		databaseListquery = drive.ListFile({'q': "'%s' in parents and trashed = false" % (cloudfolderid)})
		databaseList = databaseListquery.GetList()


		database_file = drive.CreateFile()
		database_file['title'] = packageName
		database_file['parents']=[{"kind": "drive#fileLink" ,'id': str(cloudfolderid) }]
		#check if already exists, if so, get id and update
		databasenamelist = []
		for databaseAvaliable in databaseList:
			databasenamelist.append(databaseAvaliable['title'])
		if packageName in databasenamelist:
			cloudPackageQuery = drive.ListFile({'q': "title = '%s' and trashed = false" % (packageName)})
			cloudPackage = cloudPackageQuery.GetList()

			if(len(cloudPackage) > 1): # if theres more than one, go for the most recent
				packdates = []
				for everypack in cloudPackage:
					packdates.append((everypack['modifiedByMeDate'],everypack['id']))
				database_file['id'] = sorted(packdates,reverse=True)[0][1]

			else:
				database_file['id'] = cloudPackage[0]['id']

		database_file.Upload()
		return True


	def getgooglefileid(self,title):

		print os.getcwd()
		self.ga = GoogleAuth(self.DBConfig.googleyaml)
		self.ga.LocalWebserverAuth()
		drive = GoogleDrive(self.ga)
		flist = drive.ListFile({'q': "title = '%s' and trashed = false"%title})
		files = flist.GetList() 
		if len(files)==0:
			return False
		else:
			return files[0]['id']


	def simpleUploadGoogle(self,filename): #test_01_Files_Insert
		drive = GoogleDrive(self.ga)
		#f = drive.CreateFile({'fluidSecurity': parent_id})
		file1 = drive.CreateFile()
		file1.SetContentFile(filename) # Read local file
		file1.Upload() # Upload it
		
	

		return True
	##save file ID to config
	
	
	def simpleUpdateGoogle(self,filename,dbID):
		drive = GoogleDrive(self.ga)
	
		file1=drive.CreateFile({'id': dbID}) #overwrite by ID
		file1['title'] = filename
		file1.FetchContent()
		file1.SetContentFile(filename)
		file1.Upload() 
		return True
		
	
	def simpleDownloadGoogle(self,filename):
		DeleteOldFile(self.filename) #delete local version, not that safe
	
		drive = GoogleDrive(self.ga)
		file1 = drive.CreateFile()
		file1['title'] = filename
		file1.FetchContent()  # Force download and double check content
		return True
	
	
#	
#	
#	def ftpDown(filename,host,user,ftpass):
#		import ftplib
#		session = ftplib.FTP(host,user,ftpass)
#		file = open(filename, 'wb')  
#		session.retrbinary('RETR %s' % filename, file.write)
#		file.close()
#		session.quit()
#	


	


	def uploadftp(self,filename,host,user,password):	  

		# upload logic
		import ftplib
		session = ftplib.FTP(host,user,password)
		file = open(filename,'rb')				  # file to send
		session.storbinary('STOR ' +filename, file)	 # send the file
		file.close()									# close file and FTP
		session.quit()

		return True

	def authenticatedropbox(self):
		import dropbox

		# Get your app key and secret from the Dropbox developer website
		app_key = 'p2iu4n7f9yegl3u'
		app_secret = '0903whnau7p2zde'

		flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)

		authorize_url = flow.start()
		print "============= authenticate dropbox" + str(authorize_url)

		pickled  = pickle.dumps(flow)
		encodedPickle = base64.b64encode(pickled)
		self.DBConfig.putmap('cloudinfo','dropboxobject', str(encodedPickle) )

		return authorize_url



	def uploaddropbox(self,filename,authcode):
		import socket
		socket.RAND_add(self.ssl_seed().randomString, 75.0)
		import dropbox

		try:
			# Get your app key and secret from the Dropbox developer website
			# encodedPickle =self.DBConfig.mapget('cloudinfo')['dropboxobject']
			# decodedPickle = base64.b64decode(encodedPickle)
			# flow = pickle.loads(decodedPickle)

			app_key = 'p2iu4n7f9yegl3u'
			app_secret = '0903whnau7p2zde'

			flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)

			authorize_url = flow.start()
			print "============= authenticate dropbox" + str(authorize_url)


			print "loaded ok"
			print "------ authcode: " + str(authcode)
			access_token, user_id = flow.finish(authcode)

			print "finidhed oko"
			client = dropbox.client.DropboxClient(access_token)
			print "finidhed client"
			print 'linked account: ', client.account_info()

			#Uploading files
			f = open(filename, 'rb')
			response = client.put_file('/'+str(filename), f)
			print "uploaded:", response

		except Exception as e:
			print("Upload failed: " + str(e))
			return False
		return True

	def uploadgoogledrive(self,filename):
		googlefileid = self.getgooglefileid(filename)
		if googlefileid == False:
			self.simpleUploadGoogle(filename)
		else:
			self.simpleUpdateGoogle(filename,googlefileid)
		return True

	def uploadicloud(self,filename,email,password):

		return True

	def uploadskydrive(self,filename,email,password):	

		return True
Esempio n. 14
0
from pydrive.auth import GoogleAuth

gauth = GoogleAuth()
auth_url = gauth.GetAuthUrl()  # Create authentication url user needs to visit
code = AskUserToVisitLinkAndGiveCode(
    auth_url)  # Your customized authentication flow
gauth.Auth(code)  # Authorize and build service from the code
Esempio n. 15
0
class DriveHelper:
    def __init__(self):
        self.drive_auth_settings = constants.DRIVE_AUTH_SETTINGS
        self.drive_credentials_file = constants.DRIVE_CREDS_FILE
        self.auth = GoogleAuth(settings_file=self.drive_auth_settings)

    def get_authentication_url(self):
        return self.auth.GetAuthUrl()

    def set_authentication_code(self, code):
        is_auth = False
        try:
            self.auth.Auth(code)
            self.auth.SaveCredentialsFile(self.drive_credentials_file)
            is_auth = True
        except:
            print("Error occurred while trying to authenticate via given code: {0}".format(code))
        finally:
            return is_auth

    def google_auth(self):
        self.auth.LoadCredentialsFile(self.drive_credentials_file)
        if self.auth.credentials is None:
            # Authenticate if credentials.json not there
            # auth.CommandLineAuth()
            # auth.LocalWebserverAuth()
            # custom_authentication_flow()
            print('Authenticate via this url: {0}'.format(self.auth.GetAuthUrl()))
            return None
        elif self.auth.access_token_expired:
            # Refresh them if expired
            self.auth.Refresh()
        else:
            # Initialize the saved creds
            self.auth.Authorize()
        return self.auth

    def upload_file(self, folder_id, file_name, file):
        is_uploaded = False
        if self.google_auth() is not None:
            try:
                drive = GoogleDrive(self.auth)
                mime = dict(title=file_name, parents=[{"kind": "drive#fileLink", "id": folder_id}])
                _file = drive.CreateFile(mime)  # Create GoogleDriveFile instance with title 'Hello.txt'.
                _file.SetContentFile(file)
                _file.Upload()
                is_uploaded = True
            except:
                print("Something ugly happened.. Couldn't upload file")
            finally:
                return is_uploaded

        print('Check to see if auth is none...')

        if self.google_auth() is not None:
            print("It's not..")
            drive = GoogleDrive(self.google_auth())
            mime = dict(title="HelloWorld.txt",
                        parents=[{"kind": "drive#fileLink", "id": constants.DRIVE_RAWDOCS_FOLDER_ID}])
            _file = drive.CreateFile(mime)  # Create GoogleDriveFile instance with title 'Hello.txt'.
            _file.SetContentString('Hello World!')  # Set content of the file from given string.
            _file.Upload()
Esempio n. 16
0
def uploadData(oe):
    filename = oe.finaldataPath + '\\PWVout_%s.fits' % oe.night

    def ListFolder(parent):
        filelist = []
        file_list = drive.ListFile({
            'q':
            "'%s' in parents and trashed=false" % parent
        }).GetList()
        for f in file_list:
            if f['mimeType'] == 'application/vnd.google-apps.folder':  # if folder
                filelist.append({
                    "id": f['id'],
                    "title": f['title'],
                    "list": ListFolder(f['id'])
                })
            else:
                filelist.append({
                    "title": f['title'],
                    "title1": f['alternateLink']
                })
        return filelist

    if filename:  # whi was there an indent here?
        gauth = GoogleAuth()
        auth_url = gauth.GetAuthUrl(
        )  # Create authentication url user needs to visit
        gauth.LocalWebserverAuth(
        )  #will this require me to click a button every time?????
        #http://pythonhosted.org/PyDrive/oauth.html#customizing-authentication-with-settings-yaml
        drive = GoogleDrive(gauth)

        # Check if folder in CAMAL_data for night
        out_root = ListFolder('root')
        for ifold in range(len(out_root)):
            if out_root[ifold]['title'] == u'Data':
                camalid = out_root[ifold]['id']
        #camalid   = '0B18tnyqgrwlpbFV0aXA4ckxXUlE' # id of CAMAL data folder
        #file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % camalid}).GetList()
        file_list = ListFolder(camalid)
        folders = {}
        for f in file_list:
            folders[str(f['title'])] = str(f['id'])
        if oe.night in folders.keys():
            nightid = folders[oe.night]  # store night id
        else:
            # Create folder
            nightfolder = drive.CreateFile({
                'title':
                oe.night,
                "parents": [{
                    "id": camalid
                }],
                "mimeType":
                "application/vnd.google-apps.folder"
            })
            nightfolder.Upload()
            file_list = ListFolder(camalid)
            for f in file_list:
                folders[str(f['title'])] = str(f['id'])
            nightid = folders[oe.night]  # store night id

        files = glob.glob(oe.finaldataPath + '\\*')
        # Upload Files to night's folder
        for filepath in files:
            fname = filepath.split('\\')[-1]
            f = drive.CreateFile({
                'title':
                fname,
                "parents": [{
                    "kind": "drive#fileLink",
                    "id": nightid
                }]
            })
            f.SetContentFile(filepath)
            f.Upload()
Esempio n. 17
0
import os, urllib, wget, subprocess, time, pydrive, glob
from flask import Flask, render_template, url_for, flash, redirect
from forms import InformationForm
from auth import AuthForm
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

app = Flask(__name__)

app.config['SECRET_KEY'] = 'asdf'
uploaded = []
gauth = GoogleAuth()
url = gauth.GetAuthUrl()
auth_url = url.replace("http%3A%2F%2Flocalhost%3A8080%2F", "http://*****:*****@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html')

Esempio n. 18
0
def get_authorize_url():
    gauth = GoogleAuth()
    return gauth.GetAuthUrl()
Esempio n. 19
0
                        '--download',
                        help='download [file ID] / [folder ID]')
    parser.add_argument('-u', '--upload', help='upload [file] / [folder]')
    parser.add_argument('-r',
                        '--recursive',
                        help='download / upload recursively for folders',
                        action='store_true')
    parser.add_argument(
        '-dest',
        '--destination',
        help='download: destination folder; upload: destination folder ID')
    args = parser.parse_args()

    #Login to Google Drive and create drive object
    g_auth = GoogleAuth()
    auth_url = g_auth.GetAuthUrl()
    print(auth_url)
    code = input("Enter code: ")
    g_auth.Auth(code)
    g_drive = GoogleDrive(g_auth)

    if args.recursive:
        if args.download != None:
            download_folder(g_drive, args.destination, args.download)
            pass
        if args.upload != None:
            upload_folder(g_drive, args.destination, args.upload)
            pass
        pass
    else:
        if args.download != None:
        #gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication
        # authCode = driveConfig.get("auth-code", "")
        # if authCode is None or authCode == "":
        #   url = gauth.GetAuthUrl()
        #   print "This application have not access to your Google Drive. Yo need an access code from:"
        #   print url
        #   print "then copy and paste the code in \"auth-code\" in the outputs/google-drive section in your config.py file"
        #   sys.exit(0)

        try:
            #gauth.Auth(authCode)
            drive = GoogleDrive(gauth)
        except Exception as e:
            print "Exception: " + str(e)
            print "If you have problems with the application permissions try to use this url:"
            print gauth.GetAuthUrl()
            print "then copy and paste the code in the outputs/google-drive/auth-code section in your config.py file"
            sys.exit(-1)

        fileName = driveConfig.get("file-name", "cumulustv.json")
        jsonContent = json.dumps(cumulustv, ensure_ascii=True)

        try:
            cumulusTVFile = drive.CreateFile({
                'title': fileName,
                'mimeType': 'application/json'
            })  # Create GoogleDriveFile instance with title 'Hello.txt'
            cumulusTVFile.SetContentString(
                jsonContent)  # Set content of the file from given string
            cumulusTVFile.Upload()
            print "Uploaded to drive: " + fileName
Esempio n. 21
0
def to_google():
    gauth = GoogleAuth()
    gauth.GetFlow()
    gauth.flow.redirect_uri = "http://localhost:8000/launch/"
    auth_url = gauth.GetAuthUrl()
    hug.redirect.to(auth_url)
Esempio n. 22
0
    def test_01_LocalWebserverAuthWithClientConfigFromFile(self):

        # Test if authentication works with config read from file
        packageName = "test.z.crypt"
        foldername = "SeccuDB"
        ga = GoogleAuth('settings/test1.yaml')
        #ga.getAuthURL()
        try:
            ga.LoadClientConfig()
            ga.LoadCredentials()
            ga.Authorize()
        except:

            print ga.GetAuthUrl()
            code = raw_input("code: ").strip()

            ga.Auth(code)
            ga.SaveCredentials()

        print "complete Auth"
        drive = GoogleDrive(ga)
        #flist = drive.ListFile({'q': "title contains '.crypt' and trashed = false"})
        folderlistquery = drive.ListFile({
            'q':
            "title = 'SeccuDB' and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
        })

        cloudfolder = folderlistquery.GetList()
        if (len(cloudfolder) == 0):
            #create folder

            folder = drive.CreateFile()
            folder['title'] = "SeccuDB"
            folder['mimeType'] = "application/vnd.google-apps.folder"
            folder['parents'] = "root"
            folder.Upload()
            cloudfolder = folderlistquery.GetList()
            if (len(cloudfolder) == 0):
                print "error"
                raise error('GooglePermissionsError')

        cloudfolderid = cloudfolder[0]['id']
        print cloudfolderid

        databaseListquery = drive.ListFile(
            {'q': "'%s' in parents and trashed = false" % (cloudfolderid)})
        databaseList = databaseListquery.GetList()

        database_file = drive.CreateFile()
        database_file['title'] = packageName
        database_file['parents'] = [{
            "kind": "drive#fileLink",
            'id': str(cloudfolderid)
        }]
        #check if already exists, if so, get id and update
        databasenamelist = []
        for databaseAvaliable in databaseList:
            databasenamelist.append(databaseAvaliable['title'])
        if packageName in databasenamelist:
            cloudPackageQuery = drive.ListFile(
                {'q': "title = '%s' and trashed = false" % (packageName)})
            cloudPackage = cloudPackageQuery.GetList()

            if (len(cloudPackage) >
                    1):  # if theres more than one, go for the most recent
                packdates = []
                for everypack in cloudPackage:
                    packdates.append(
                        (everypack['modifiedByMeDate'], everypack['id']))
                database_file['id'] = sorted(packdates, reverse=True)[0][1]

            else:
                database_file['id'] = cloudPackage[0]['id']

        database_file.Upload()
Esempio n. 23
0
class RHDrive:
    """
	A drive class for wrapping the necessary functions from pydrive
	"""
    def __init__(self):
        """
		Initialize RHDrive
		"""
        self.gauth = GoogleAuth()  #initiate authenticator for OAuth2
        self.drive = None
        self.data_id = None

    def get_data_id(self):
        """
		populate data_id with id of folder called 'Data'
		"""
        filelist = self.get_files()
        for file in filelist:
            if file['title'] == 'Data':
                self.data_id = file['id']
                return

    def get_auth_link(self):
        """
		Returns the auth link required for authentication
		"""
        link = self.gauth.GetAuthUrl()
        return link

    def write_auth_link(self, local_filename):
        """
		Write authentication link to local_filename for someone to read
		"""
        link = self.get_auth_link()
        with open(local_filename, 'w') as f:
            f.write(link)

    def authorize(self):
        """
		Authenticate, try to get loaded credentials, if not possible then try CommandLineAuth
		"""
        self.gauth.LoadCredentialsFile("rhcred.txt")  #load saved credentials
        if self.gauth.credentials is None:
            self.gauth.CommandLineAuth()
        elif self.gauth.access_token_expired:
            self.gauth.Refresh()
        else:
            self.gauth.Authorize()
        self.gauth.SaveCredentialsFile(
            "rhcred.txt")  #save credentials after authentication
        self.drive = GoogleDrive(self.gauth)

    def check_login_email(self):
        """
		Check if we're logged into [email protected] (We don't want to log into any other account)
		This is a very hack-ish way to do this
		But the Drive REST API doesn't provide any better methods
		"""
        #check if there is a file called 'emailcheck.txt' containing the string 'this is [email protected]\n'
        filelist = self.get_files()
        emailcheck = None
        for file in filelist:
            if file['title'] == 'emailcheck.txt':
                toget = file
                break
        if toget is not None:
            #print toget.GetContentString()
            if toget.GetContentString(
            ) == 'this is [email protected]\n':
                return True
        return False

    def get_files(self, parent='root'):
        """
		Get iterable list of files in root folder of GoogleDrive
		"""
        query = '"' + parent + '" in parents and trashed = false'
        files = self.drive.ListFile({'q': query}).GetList()
        return files

    def write_filelist(self, local_filename):
        """
		write the names of the files in GoogleDrive to local_filename
		"""
        filelist = self.get_files(self.data_id)
        f = open(local_filename, 'w')
        for file in filelist:
            f.write(file['title'] + '\n')
        f.close()

    def update_file(self, server_filename, local_filename):
        """
		Update the file called server_filename with the contents of local_filename
		"""
        filelist = self.get_files(self.data_id)
        toupdate = None
        for file in filelist:
            if file['title'] == server_filename:
                toupdate = file
                break
        if toupdate is not None:
            toupdate.SetContentFile(local_filename)
            toupdate.Upload()
        return toupdate

    def upload_file(self, server_filename, local_filename):
        """
		Upload a new file by name and content of filename, may cause naming conflict, should be unique
		"""
        newfile = self.drive.CreateFile({
            'title':
            server_filename,
            'parents': [{
                "kind": "drive#fileLink",
                "id": self.data_id
            }]
        })
        newfile.SetContentFile(local_filename)
        newfile.Upload()

    def write_key(self, localfile):
        """
		get the 'key.txt' file from the top level directory
		"""
        filelist = self.get_files()
        for file in filelist:
            if file['title'] == 'key.txt':
                file.GetContentFile(localfile)
                return file
        return None

    def retrieve_file(self, server_filename, local_filename):
        """
		Get file called server_filename from GoogleDrive and save as local_filename
		"""
        filelist = self.get_files(self.data_id)
        toget = None
        for file in filelist:
            if file['title'] == server_filename:
                toget = file
                break
        if toget is not None:
            toget.GetContentFile(local_filename)
        return toget