186 lines
5.3 KiB
TypeScript
186 lines
5.3 KiB
TypeScript
import encrypt from "../../functions/dsql/encrypt";
|
|
import apiLoginUser from "../../functions/api/users/api-login";
|
|
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
|
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
|
|
import {
|
|
APILoginFunctionParams,
|
|
APIResponseObject,
|
|
DATASQUIREL_LoggedInUser,
|
|
LoginUserParam,
|
|
} from "../../types";
|
|
import debugLog from "../../utils/logging/debug-log";
|
|
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
|
|
import grabUserDSQLAPIPath from "../../utils/backend/users/grab-api-path";
|
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
|
|
|
function debugFn(log: any, label?: string) {
|
|
debugLog({ log, addTime: true, title: "loginUser", label });
|
|
}
|
|
|
|
/**
|
|
* # Login A user
|
|
*/
|
|
export default async function loginUser<
|
|
T extends DATASQUIREL_LoggedInUser = DATASQUIREL_LoggedInUser
|
|
>({
|
|
apiKey,
|
|
payload,
|
|
database,
|
|
additionalFields,
|
|
response,
|
|
encryptionKey,
|
|
encryptionSalt,
|
|
email_login,
|
|
email_login_code,
|
|
temp_code_field,
|
|
token,
|
|
skipPassword,
|
|
apiUserID,
|
|
skipWriteAuthFile,
|
|
dbUserId,
|
|
debug,
|
|
cleanupTokens,
|
|
secureCookie,
|
|
useLocal,
|
|
apiVersion = "v1",
|
|
}: LoginUserParam): Promise<APIResponseObject<T | null>> {
|
|
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
|
|
|
const defaultTempLoginFieldName = "temp_login_code";
|
|
const emailLoginTempCodeFieldName = email_login
|
|
? temp_code_field
|
|
? temp_code_field
|
|
: defaultTempLoginFieldName
|
|
: undefined;
|
|
|
|
const finalEncryptionKey =
|
|
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
|
const finalEncryptionSalt =
|
|
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
|
|
|
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
|
console.log("Encryption key is invalid");
|
|
return {
|
|
success: false,
|
|
payload: null,
|
|
msg: "Encryption key is invalid",
|
|
};
|
|
}
|
|
|
|
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
|
console.log("Encryption salt is invalid");
|
|
return {
|
|
success: false,
|
|
payload: null,
|
|
msg: "Encryption salt is invalid",
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Initialize HTTP response variable
|
|
*/
|
|
|
|
let httpResponse: APIResponseObject = {
|
|
success: false,
|
|
};
|
|
|
|
const apiLoginParams: APILoginFunctionParams = {
|
|
database,
|
|
email: payload.email,
|
|
username: payload.username,
|
|
password: payload.password,
|
|
skipPassword,
|
|
encryptionKey: finalEncryptionKey,
|
|
additionalFields,
|
|
email_login,
|
|
email_login_code,
|
|
email_login_field: emailLoginTempCodeFieldName,
|
|
token,
|
|
dbUserId,
|
|
debug,
|
|
};
|
|
|
|
/**
|
|
* Check for local DB settings
|
|
*
|
|
* @description Look for local db settings in `.env` file and by pass the http request if available
|
|
*/
|
|
if (useLocal) {
|
|
httpResponse = await apiLoginUser(apiLoginParams);
|
|
} else {
|
|
httpResponse = await queryDSQLAPI({
|
|
path: grabUserDSQLAPIPath({
|
|
paradigm: "auth",
|
|
action: "login",
|
|
database,
|
|
apiVersion,
|
|
}),
|
|
apiKey,
|
|
body: apiLoginParams,
|
|
method: "POST",
|
|
});
|
|
}
|
|
|
|
if (debug) {
|
|
debugFn(httpResponse, "httpResponse");
|
|
}
|
|
|
|
/**
|
|
* # Send Response
|
|
*/
|
|
|
|
if (httpResponse?.success) {
|
|
let encryptedPayload = encrypt({
|
|
data: JSON.stringify(httpResponse.payload),
|
|
encryptionKey: finalEncryptionKey,
|
|
encryptionSalt: finalEncryptionSalt,
|
|
});
|
|
|
|
try {
|
|
if (token && encryptedPayload)
|
|
httpResponse["token"] = encryptedPayload;
|
|
} catch (error: any) {
|
|
console.log("Login User HTTP Response Error:", error.message);
|
|
}
|
|
|
|
const cookieNames = getAuthCookieNames({
|
|
database,
|
|
});
|
|
|
|
if (httpResponse.csrf && !skipWriteAuthFile) {
|
|
writeAuthFile(
|
|
httpResponse.csrf,
|
|
JSON.stringify(httpResponse.payload),
|
|
cleanupTokens && httpResponse.payload?.id
|
|
? { userId: httpResponse.payload.id }
|
|
: undefined
|
|
);
|
|
}
|
|
|
|
httpResponse["cookieNames"] = cookieNames;
|
|
httpResponse["key"] = String(encryptedPayload);
|
|
|
|
const authKeyName = cookieNames.keyCookieName;
|
|
const csrfName = cookieNames.csrfCookieName;
|
|
|
|
if (debug) {
|
|
debugFn(authKeyName, "authKeyName");
|
|
debugFn(csrfName, "csrfName");
|
|
debugFn(encryptedPayload, "encryptedPayload");
|
|
}
|
|
|
|
response?.setHeader("Set-Cookie", [
|
|
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
|
secureCookie ? ";Secure=true" : ""
|
|
}`,
|
|
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
|
]);
|
|
|
|
if (debug) {
|
|
debugFn("Response Sent!");
|
|
}
|
|
}
|
|
|
|
return httpResponse;
|
|
}
|