aboutsummaryrefslogtreecommitdiff
path: root/src/server
diff options
context:
space:
mode:
Diffstat (limited to 'src/server')
-rw-r--r--src/server/apis/google/GoogleApiServerUtils.ts27
-rw-r--r--src/server/database.ts32
-rw-r--r--src/server/index.ts6
3 files changed, 38 insertions, 27 deletions
diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts
index 665dcf862..f2ce51395 100644
--- a/src/server/apis/google/GoogleApiServerUtils.ts
+++ b/src/server/apis/google/GoogleApiServerUtils.ts
@@ -103,21 +103,21 @@ export namespace GoogleApiServerUtils {
*/
export function authorize(credentials: any, userId: string): Promise<TokenResult> {
const { client_secret, client_id, redirect_uris } = credentials.installed;
- const oAuth2Client = new google.auth.OAuth2(
- client_id, client_secret, redirect_uris[0]);
-
+ const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
return new Promise<TokenResult>((resolve, reject) => {
+ // Attempting to authorize user (${userId})
Database.Auxiliary.GoogleAuthenticationToken.Fetch(userId).then(token => {
- // Check if we have previously stored a token for this userId.
if (!token) {
+ // No token registered, so awaiting input from user
return getNewToken(oAuth2Client, userId).then(resolve, reject);
}
- let parsed: Credentials = parseBuffer(token);
- if (parsed.expiry_date! < new Date().getTime()) {
- return refreshToken(parsed, client_id, client_secret, oAuth2Client, userId).then(resolve, reject);
+ if (token.expiry_date < new Date().getTime()) {
+ // Token has expired, so submitting a request for a refreshed access token
+ return refreshToken(token, client_id, client_secret, oAuth2Client, userId).then(resolve, reject);
}
- oAuth2Client.setCredentials(parsed);
- resolve({ token: parsed, client: oAuth2Client });
+ // Authentication successful!
+ oAuth2Client.setCredentials(token);
+ resolve({ token, client: oAuth2Client });
});
});
}
@@ -134,11 +134,12 @@ export namespace GoogleApiServerUtils {
};
let url = `${refreshEndpoint}?${qs.stringify(queryParameters)}`;
request.post(url, headerParameters).then(async response => {
- let parsed = JSON.parse(response);
- credentials.access_token = parsed.access_token;
- credentials.expiry_date = new Date().getTime() + (parsed.expires_in * 1000);
+ let { access_token, expires_in } = JSON.parse(response);
+ const expiry_date = new Date().getTime() + (expires_in * 1000);
+ await Database.Auxiliary.GoogleAuthenticationToken.Update(userId, access_token, expiry_date);
+ credentials.access_token = access_token;
+ credentials.expiry_date = expiry_date;
oAuth2Client.setCredentials(credentials);
- await Database.Auxiliary.GoogleAuthenticationToken.Write(userId, credentials);
resolve({ token: credentials, client: oAuth2Client });
});
});
diff --git a/src/server/database.ts b/src/server/database.ts
index 890ac6b32..bc9a9ab23 100644
--- a/src/server/database.ts
+++ b/src/server/database.ts
@@ -1,7 +1,7 @@
import * as mongodb from 'mongodb';
import { Transferable } from './Message';
import { Opt } from '../new_fields/Doc';
-import { Utils } from '../Utils';
+import { Utils, emptyFunction } from '../Utils';
import { DashUploadUtils } from './DashUploadUtils';
export namespace Database {
@@ -21,7 +21,7 @@ export namespace Database {
});
}
- public update(id: string, value: any, callback: (err: mongodb.MongoError, res: mongodb.UpdateWriteOpResult) => void, upsert = true, collectionName = Database.DocumentsCollection) {
+ public async update(id: string, value: any, callback: (err: mongodb.MongoError, res: mongodb.UpdateWriteOpResult) => void, upsert = true, collectionName = Database.DocumentsCollection) {
if (this.db) {
let collection = this.db.collection(collectionName);
const prom = this.currentWrites[id];
@@ -40,6 +40,7 @@ export namespace Database {
};
newProm = prom ? prom.then(run) : run();
this.currentWrites[id] = newProm;
+ return newProm;
} else {
this.onConnect.push(() => this.update(id, value, callback, upsert, collectionName));
}
@@ -226,23 +227,22 @@ export namespace Database {
export namespace Auxiliary {
export enum AuxiliaryCollections {
- GooglePhotosUploadHistory = "UploadedFromGooglePhotos"
+ GooglePhotosUploadHistory = "uploadedFromGooglePhotos"
}
- const GoogleAuthentication = "GoogleAuthentication";
- const SanitizedCappedQuery = async (query: { [key: string]: any }, collection: string, cap: number) => {
+ const SanitizedCappedQuery = async (query: { [key: string]: any }, collection: string, cap: number, removeId = true) => {
const cursor = await Instance.query(query, undefined, collection);
const results = await cursor.toArray();
const slice = results.slice(0, Math.min(cap, results.length));
- return slice.map(result => {
+ return removeId ? slice.map(result => {
delete result._id;
return result;
- });
+ }) : slice;
};
- const SanitizedSingletonQuery = async (query: { [key: string]: any }, collection: string) => {
- const results = await SanitizedCappedQuery(query, collection, 1);
+ const SanitizedSingletonQuery = async (query: { [key: string]: any }, collection: string, removeId = true) => {
+ const results = await SanitizedCappedQuery(query, collection, 1, removeId);
return results.length ? results[0] : undefined;
};
@@ -252,14 +252,24 @@ export namespace Database {
export namespace GoogleAuthenticationToken {
- export const Fetch = async (userId: string) => {
- return SanitizedSingletonQuery({ userId }, GoogleAuthentication);
+ const GoogleAuthentication = "googleAuthentication";
+
+ export const Fetch = async (userId: string, removeId = true) => {
+ return SanitizedSingletonQuery({ userId }, GoogleAuthentication, removeId);
};
export const Write = async (userId: string, token: any) => {
return Instance.insert({ userId, ...token }, GoogleAuthentication);
};
+ export const Update = async (userId: string, access_token: string, expiry_date: number) => {
+ const entry = await Fetch(userId, false);
+ if (entry) {
+ const parameters = { $set: { access_token, expiry_date } };
+ return Instance.update(entry._id, parameters, emptyFunction, true, GoogleAuthentication);
+ }
+ };
+
}
export const LogUpload = async (information: DashUploadUtils.UploadInformation) => {
diff --git a/src/server/index.ts b/src/server/index.ts
index 2ff63ab78..33d098e2c 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -824,7 +824,7 @@ app.post(RouteStore.googleDocs + "/:sector/:action", (req, res) => {
});
});
-app.get(RouteStore.googlePhotosAccessToken, (req, res) => GoogleApiServerUtils.RetrieveAccessToken({ credentialsPath, userId: req.headers.userId as string }).then(token => res.send(token)));
+app.get(RouteStore.googlePhotosAccessToken, (req, res) => GoogleApiServerUtils.RetrieveAccessToken({ credentialsPath, userId: req.header("userId")! }).then(token => res.send(token)));
const tokenError = "Unable to successfully upload bytes for all images!";
const mediaError = "Unable to convert all uploaded bytes to media items!";
@@ -839,9 +839,9 @@ export interface NewMediaItem {
app.post(RouteStore.googlePhotosMediaUpload, async (req, res) => {
const { media } = req.body;
- const { userId } = req.headers;
+ const userId = req.header("userId");
- if (!userId || Array.isArray(userId)) {
+ if (!userId) {
return _error(res, userIdError);
}