Skip to content
This repository has been archived by the owner on Nov 21, 2021. It is now read-only.

Commit

Permalink
Nore : Recovery Commit, Haven't Merged with Uttkarsh's Branch
Browse files Browse the repository at this point in the history
- Trying to add Alternate Google Login

- Added Google Login Support for Electron [Styling Necessary, Will do that tommo]

- Added Dev Enviroment to Run-Script.tsx by default so that Developer wont need to Specify [-dev] argument

- To Logout Current Google Accout for Python Scripts, Just Delete 'token.pickle' present under 'assets/installation/.usp/' directory

- To Logout Current Google Accout for Electron App, Just edit 'line no ~15' of Appsettings.json present under 'assets/installation/.usp/' to

"cloudLoginStatus": {
    "googleDrive": null
}

Eg [assets/installation/.usp/Appsettings.json] [for Logout]-

Replace -
"cloudLoginStatus": {
    "googleDrive": {
      "user": {
        "kind": "drive#user",
        "displayName": "sahil shahane",
        "me": true,
        "permissionId": "14809511190742694856",
        "emailAddress": "[email protected]"
      },
      "storageQuota": {
        "limit": "16106127360",
        "usage": "2694603157",
        "usageInDrive": "2660517007",
        "usageInDriveTrash": "236860755"
      }
    }

To -
"cloudLoginStatus": {
    "googleDrive": null
}

- Renamed 'python-scripts' folder to 'pythonScripts' which is present under 'assets' directory

- Renamed 'authenticate.py' to 'GoogleDrive.py' which is present under 'assets/pythonScripts/DrivePart' directory

- While Working in Python Scripts, Google's Service Object must be Retrived from 'getGDriveService()' function

- Fixed Width issue in FolderArea component [i guess Uttkarsh's Branch has already Fixed this issue]

- some Changes in main.dev.ts by sahilbest999
  • Loading branch information
sahilshahane committed Jan 9, 2021
1 parent 2c71fde commit 3428599
Show file tree
Hide file tree
Showing 15 changed files with 634 additions and 74 deletions.
11 changes: 0 additions & 11 deletions Pipfile

This file was deleted.

1 change: 0 additions & 1 deletion Testing/fields.json

This file was deleted.

11 changes: 6 additions & 5 deletions assets/installation/.usp/credentials.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
{
"installed": {
"client_id": "910230223829-lna3l0uvhsgd0o7vtqq9rcut2d63knaq.apps.googleusercontent.com",
"project_id": "fvs-project-288209",
"web": {
"client_id": "591318303565-m4kmaoeta09dg7qt9dv5n76glp1vl67j.apps.googleusercontent.com",
"project_id": "fhs-majorproject-1609495439106",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "m2A6UBTxAJHf4NjfcZJ984wx",
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
"client_secret": "zKod4j9aMi91knurg7PNwLD3",
"redirect_uris": ["http://localhost:4959"],
"javascript_origins": ["http://localhost:4959"]
}
}
11 changes: 11 additions & 0 deletions assets/installation/.usp/credentials_utt.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"installed": {
"client_id": "910230223829-lna3l0uvhsgd0o7vtqq9rcut2d63knaq.apps.googleusercontent.com",
"project_id": "fvs-project-288209",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "m2A6UBTxAJHf4NjfcZJ984wx",
"redirect_uris": ["http://localhost", "urn:ietf:wg:oauth:2.0:oob"]
}
}
Binary file modified assets/installation/.usp/token.pickle
Binary file not shown.
16 changes: 0 additions & 16 deletions assets/pythonScripts/ZMQ-test.py

This file was deleted.

18 changes: 11 additions & 7 deletions assets/pythonScripts/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,19 @@ def __init__(self):
args_const.add_argument('-init',"--initialize", help='Initillizes the Current Working Directory', action="store_true")
args_const.add_argument('-u',"--update", help='Update the Repository App Data', action="store_true")
args_const.add_argument('-dev',"--development", help='Enable Development Environment', action="store_true")
args_const.add_argument('-clean',"--clean", help='Cleans repository data, must be used with Development Environment Only', action="store_true")
args_const.add_argument('-glogin',"--googleLogin", help='Log-in into Google Account', action="store_true")
args_const.add_argument('-guserinfo',"--googleUserInfo", help='Provides Account Information for Logged In Google Account', action="store_true")

args = args_const.parse_args()

if(args.development): self.Development()
if(args.development):
if(args.clean):
try:
shutil.rmtree(os.path.join('.',"Testing",'.usp'))
except Exception as e: pass

self.Development()
else:
# CHANGE THE CWD [CURRENT WORKING DIRECTORY] ARGUMENT, ALWAYS SPECIFY THIS ARGUMENT
if(args.change_directory): os.chdir(args.change_directory)
Expand All @@ -72,7 +79,6 @@ def __init__(self):
self.REPOSITORY_SETTINGS = self.LOAD_REPOSITORY_SETTINGS()
self.update()


def Production(self):
USER_HOME_PATH = pathlib.Path.home()

Expand All @@ -81,10 +87,6 @@ def Production(self):
def Development(self):
os.environ["APP_FOLDER_PATH"] = os.path.join(os.getcwd(),'assets','installation','.usp') # APP's Main Folder, Where we are going to store App related Files

try:
shutil.rmtree(os.path.join('.',"Testing",'.usp'))
except Exception as e: pass

os.chdir(os.path.join('.',"Testing"))

def LOAD_APP_INIT_DATA(self):
Expand Down Expand Up @@ -334,4 +336,6 @@ def getGoogleUserInfo(self):
output({"code":self.CCODES["GOOGLE_USER_INFO"],"msg":"Google User Data","data":userInfo})
return userInfo

App()
if __name__ == "__main__":
App()

2 changes: 0 additions & 2 deletions assets/pythonScripts/prerequisite.txt

This file was deleted.

15 changes: 0 additions & 15 deletions fields.json

This file was deleted.

93 changes: 93 additions & 0 deletions login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
const fs = require('fs');
const { google } = require('googleapis');
const http = require('http');
const querystring = require('querystring');
const openURLinBrowser = require('open');

const loadCredentials = () => {
return fs.promises
.readFile('assets\\installation\\.usp\\credentials.json')
.catch((err) => {
if (err) console.log('Error Reading Credentials.json', err);
});
};

// eslint-disable-next-line @typescript-eslint/naming-convention
const get_Gservice = async () => {
const credentials = JSON.parse(await loadCredentials());
// eslint-disable-next-line @typescript-eslint/naming-convention
const { client_secret, client_id, redirect_uris } = credentials.web;
return new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
};

const GenerateToken = (TOKEN_PATH, Gservice) => {
const HOST = 'localhost';
const PORT = 8080;

const SCOPES = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
];

const authUrl = Gservice.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
redirect_uri: `http://${HOST}:${PORT}`,
});

// openURLinBrowser(authUrl);
console.log(authUrl);
const server = http
.createServer((req, res) => {
const CODE = querystring.parse(req.url)['/?code'];
if (CODE) {
Gservice.getToken(CODE, (err, token) => {
if (err) {
return console.error(err);
}
// SETTING TOKEN
Gservice.setCredentials(token);

// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err_) => {
if (err_)
return console.error(
'Error Occured While Writing Token File',
err_
);
});

// CLOSE THE SERVER
server.close();
});
}
res.writeHead(200, 'OK', { 'content-type': 'text/plain' });
res.write('Authorization Complete, You may now close this window.');
res.end();
})
.listen(PORT, HOST, () => {
// console.log(`Login Server Started at http://${HOST}:${PORT}`);
});
};

const startLogin = async () => {
const Gservice = await get_Gservice();

const TOKEN_PATH = 'token.json';

fs.readFile(TOKEN_PATH, (err, tokenFile) => {
if (err) {
const token = GenerateToken(TOKEN_PATH, Gservice);

// Setting Token
Gservice.setCredentials(token);
} else {
const token = JSON.parse(tokenFile);

// Setting Token
Gservice.setCredentials(token);
}
});
};

startLogin();
98 changes: 98 additions & 0 deletions login_g.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('assets\\installation\\.usp\\credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), listFiles);
});

/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);

// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}

/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
redirect_uri: `http://localhost:8000`,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
console.log(code);
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}

/**
* Lists the names and IDs of up to 10 files.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
const drive = google.drive({ version: 'v3', auth });
drive.files.list(
{
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
},
(err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.map((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
}
);
}
Loading

0 comments on commit 3428599

Please sign in to comment.