This commit is contained in:
Benjamin Toby
2025-07-10 12:13:03 +01:00
parent 5ab079f687
commit f9725a1d6f
22 changed files with 262 additions and 177 deletions
+1 -1
View File
@@ -145,7 +145,7 @@ export default async function loginUser<
const cookieNames = getAuthCookieNames({
database,
userId: apiUserID,
userId: apiUserID || process.env.DSQL_API_USER_ID,
});
if (httpResponse.csrf && !skipWriteAuthFile) {
@@ -1,36 +1,21 @@
import http from "http";
import encrypt from "../../../functions/dsql/encrypt";
import grabHostNames from "../../../utils/grab-host-names";
import apiGoogleLogin from "../../../functions/api/users/social/api-google-login";
import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names";
import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files";
import { APILoginFunctionReturn } from "../../../types";
import {
APIGoogleLoginFunctionParams,
APIResponseObject,
GoogleAuthParams,
} from "../../../types";
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
type Param = {
key?: string;
token: string;
database?: string;
response?: http.ServerResponse;
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
additionalData?: { [s: string]: string | number };
apiUserID?: string | number;
debug?: boolean;
secureCookie?: boolean;
loginOnly?: boolean;
/**
* Login without calling external API
*/
forceLocal?: boolean;
};
import queryDSQLAPI from "../../../functions/api/query-dsql-api";
import grabUserDSQLAPIPath from "../../../utils/backend/users/grab-api-path";
/**
* # SERVER FUNCTION: Login with google Function
*/
export default async function googleAuth({
key,
apiKey,
token,
database,
response,
@@ -42,12 +27,9 @@ export default async function googleAuth({
debug,
secureCookie,
loginOnly,
forceLocal,
}: Param): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames({
userId: apiUserID || process.env.DSQL_API_USER_ID,
});
const { host, port, scheme, user_id } = grabedHostNames;
useLocal,
apiVersion,
}: GoogleAuthParams): Promise<APIResponseObject> {
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
const finalEncryptionKey =
@@ -90,72 +72,37 @@ export default async function googleAuth({
* Initialize HTTP response variable
*/
let httpResponse: APILoginFunctionReturn = {
let httpResponse: APIResponseObject = {
success: false,
};
if (forceLocal) {
const googleAuthParams: APIGoogleLoginFunctionParams = {
token,
additionalFields,
additionalData,
debug,
loginOnly,
database,
apiUserId: apiUserID || process.env.DSQL_API_USER_ID,
};
if (useLocal) {
if (debug) {
console.log(`Google login with Local Paradigm ...`);
}
httpResponse = await apiGoogleLogin({
token,
additionalFields,
additionalData,
debug,
loginOnly,
});
httpResponse = await apiGoogleLogin(googleAuthParams);
} else {
httpResponse = await new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
token,
httpResponse = await queryDSQLAPI({
path: grabUserDSQLAPIPath({
paradigm: "auth",
action: "google-login",
database,
additionalFields,
additionalData,
});
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/user/${
apiUserID || grabedHostNames.user_id
}/google-login`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
resolve(JSON.parse(str));
});
response.on("error", (err) => {
reject(err);
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.end();
apiVersion,
}),
apiKey,
body: googleAuthParams,
method: "POST",
});
}
@@ -173,7 +120,7 @@ export default async function googleAuth({
const cookieNames = getAuthCookieNames({
database,
userId: user_id,
userId: apiUserID || process.env.DSQL_API_USER_ID,
});
if (httpResponse.csrf) {
@@ -0,0 +1,52 @@
import http from "http";
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
import parseCookies from "../../utils/backend/parseCookies";
import decrypt from "../../functions/dsql/decrypt";
import EJSON from "../../utils/ejson";
import { SendOneTimeCodeEmailResponse } from "../../types";
type Param = {
request?: http.IncomingMessage & { [s: string]: any };
cookieString?: string;
email?: string;
code?: string;
};
/**
* # Verify the temp email code sent to the user's email address
*/
export default async function validateTempEmailCode({
request,
email,
cookieString,
code,
}: Param): Promise<SendOneTimeCodeEmailResponse | null> {
try {
const keyNames = getAuthCookieNames();
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
const cookies = parseCookies({ request, cookieString });
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
const encryptedPayload = decrypt({
encryptedString: encryptedOneTimeCode,
});
const payload = EJSON.parse(encryptedPayload) as
| SendOneTimeCodeEmailResponse
| undefined;
if (payload?.email && !email) {
return payload;
}
if (payload?.email && payload.email === email) {
return payload;
}
return null;
} catch (error: any) {
console.log("validateTempEmailCode error:", error.message);
return null;
}
}
+7
View File
@@ -4,12 +4,14 @@ import loginUser from "../../actions/users/login-user";
import logoutUser from "../../actions/users/logout-user";
import resetPassword from "../../actions/users/reset-password";
import sendEmailCode from "../../actions/users/send-email-code";
import googleAuth from "../../actions/users/social/google-auth";
import updateUser from "../../actions/users/update-user";
import userAuth from "../../actions/users/user-auth";
import {
AddUserParams,
GetUserParams,
GoogleAuthParams,
LoginUserParam,
ResetPasswordParams,
SendEmailCodeParams,
@@ -53,6 +55,11 @@ export default function user(params?: Params) {
return await resetPassword({ ..._, useLocal: true });
}
: resetPassword,
googleLogin: params?.local
? async (_: GoogleAuthParams) => {
return await googleAuth({ ..._, useLocal: true });
}
: googleAuth,
logout: logoutUser,
auth: userAuth,
},
@@ -11,6 +11,7 @@ import {
HandleSocialDbFunctionParams,
} from "../../../types";
import grabDirNames from "../../../utils/backend/names/grab-dir-names";
import grabDbFullName from "../../../utils/grab-db-full-name";
/**
* # Handle Social DB
@@ -25,9 +26,13 @@ export default async function handleSocialDb({
additionalFields,
debug,
loginOnly,
apiUserId,
}: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn> {
try {
const finalDbName = database ? database : "datasquirel";
const finalDbName = grabDbFullName({
dbName: database,
userId: apiUserId,
});
const existingSocialUserQUery = `SELECT * FROM users WHERE email = ? AND social_login='1' AND social_platform = ? `;
const existingSocialUserValues = [email, social_platform];
@@ -17,6 +17,7 @@ export default async function apiGoogleLogin({
additionalData,
debug,
loginOnly,
apiUserId,
}: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn> {
try {
const gUser: GoogleOauth2User | undefined = await new Promise(
@@ -78,6 +79,7 @@ export default async function apiGoogleLogin({
additionalFields,
debug,
loginOnly,
apiUserId,
});
////////////////////////////////////////
@@ -85,7 +87,7 @@ export default async function apiGoogleLogin({
////////////////////////////////////////
return { ...loggedInGoogleUser };
} catch (/** @type {any} */ error: any) {
} catch (error: any) {
console.log(`api-google-login.ts ERROR: ${error.message}`);
return {
+23
View File
@@ -1167,6 +1167,7 @@ export type APIGoogleLoginFunctionParams = {
additionalData?: { [key: string]: string | number };
debug?: boolean;
loginOnly?: boolean;
apiUserId?: string | number;
};
export type APIGoogleLoginFunction = (
@@ -1187,6 +1188,7 @@ export type HandleSocialDbFunctionParams = {
debug?: boolean;
loginOnly?: boolean;
social_id?: string | number;
apiUserId?: string | number;
};
export type HandleSocialDbFunctionReturn = {
@@ -2348,6 +2350,7 @@ export const UserAPIAuthActions = [
"delete",
"send-email-code",
"reset-password",
"google-login",
] as const;
export type GrabUserAPIPathParams = {
@@ -2451,3 +2454,23 @@ export type ApiUpdateUserParams<
dbSchema?: DSQL_DatabaseSchemaType;
dbUserId?: string | number;
};
export type GoogleAuthParams = {
apiKey?: string;
token: string;
database?: string;
response?: ServerResponse;
encryptionKey?: string;
encryptionSalt?: string;
additionalFields?: string[];
additionalData?: { [s: string]: string | number };
apiUserID?: string | number;
debug?: boolean;
secureCookie?: boolean;
loginOnly?: boolean;
/**
* Login without calling external API
*/
useLocal?: boolean;
apiVersion?: string;
};