From 69a81e482fc59d9ce5ea2828b477250fdabd001b Mon Sep 17 00:00:00 2001 From: rdbsolutions Date: Tue, 23 Aug 2022 15:06:55 +0100 Subject: [PATCH] migrate auth db to sql server --- .env.local | 19 ++-- actions/index.js | 12 +-- i18n.js | 1 + package.json | 4 +- pages/account/register.js | 30 ++++--- pages/api/auth/[...nextauth].js | 8 +- pages/error.js | 2 +- pages/index.js | 15 +++- pages/newappeal/index.js | 12 ++- .../migration.sql | 88 ++++++++++--------- ...tion_lock.toml => old_migration_lock.toml} | 0 prisma/mysql_schema.prisma | 61 +++++++++++++ prisma/schema.prisma | 33 ++++--- 13 files changed, 194 insertions(+), 91 deletions(-) rename prisma/migrations/{migration_lock.toml => old_migration_lock.toml} (100%) create mode 100644 prisma/mysql_schema.prisma diff --git a/.env.local b/.env.local index b24eb907..c4b68891 100644 --- a/.env.local +++ b/.env.local @@ -77,15 +77,24 @@ GOOGLE_MAP_API_KEY = AIzaSyCzeVrHt544bp_72YCFkw21eDsmI2JEsQo //Next Auth vars -EMAIL_SERVER_HOST=smtp.sendgrid.net +//EMAIL_SERVER_HOST=smtp.sendgrid.net +//EMAIL_SERVER_PORT=465 +//EMAIL_SERVER_USER=apikey +//EMAIL_SERVER_PASSWORD=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 +//EMAIL_FROM=rob@rdbsolutions.co.uk + + +EMAIL_SERVER_HOST=rdbdigital.com EMAIL_SERVER_PORT=465 -EMAIL_SERVER_USER=apikey -EMAIL_SERVER_PASSWORD=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 -EMAIL_FROM=rob@rdbsolutions.co.uk +EMAIL_SERVER_USER=rob@rdbdigital.com +EMAIL_SERVER_PASSWORD=!Sky9fish2020 +EMAIL_FROM=no-reply@rdbdigital.com NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_URL_INTERNAL=http://localhost:3000 -DATABASE_URL=mysql://nextAuthAdmin:!Sky9fish1972@77.68.17.157:3306/nextauthDB?synchronise=true +//DATABASE_URL=mysql://nextAuthAdmin:!Sky9fish1972@77.68.17.157:3306/nextauthDB?synchronise=true +DATABASE_URL = sqlserver://pedw-dev-test-sql-svr.database.windows.net:1433;database=PEDWDev;user=RobBondSQL;password=GhWKr62F5sQ69dZx;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;authentication=ActiveDirectoryPassword + SECRET=SuperSecret diff --git a/actions/index.js b/actions/index.js index 337c698d..9d3f525f 100644 --- a/actions/index.js +++ b/actions/index.js @@ -26,7 +26,7 @@ const WEBAPI_URL = export const consoleLogger = (err) => { var errStr = - "///////\nServer Error " + + "\n\n/////////////////////////////////////////////////\nServer Error " + "\n" + err.response.status + " : " + @@ -35,7 +35,7 @@ export const consoleLogger = (err) => { err.response.config.url + "\nRequest Time: " + err.response.headers.date + - "\n///////"; + "\n/////////////////////////////////////////////////\n\n"; return errStr; }; @@ -602,7 +602,7 @@ export const getAppealID = ( // getFormCollection(updateFormCollection) // ) - let formCollectionName = getFormCollection(updateFormCollection); + //let formCollectionName = getFormCollection(updateFormCollection); //console.log(formCollectionName); return axios .get( @@ -617,12 +617,12 @@ export const getAppealID = ( const result = Object.entries(res.data.value[0]).filter( ([key]) => !key.startsWith("_") )[0][1]; - + console.log("result:", res.data); var appealID = result; return appealID; }) .catch((error) => { - //console.log("API call error", error); + console.log("API call error", error); }); }; @@ -915,7 +915,7 @@ export const updateCase = async ( var config = { method: "post", url: queryUrl, - data: data, + data: updateBody, }; //console.log(data); diff --git a/i18n.js b/i18n.js index c548e141..864fa98b 100644 --- a/i18n.js +++ b/i18n.js @@ -11,6 +11,7 @@ module.exports = { "pages": { "*": ["common", "newappeal", "search"], "/": ["common", "home"], + "/error": ["common", "home", "myportal"], "/myportal": ["myportal", "common", "home"], "/myportal/viewall": ["search"], "/myportal/advancedsearch": ["search", "myportal"], diff --git a/package.json b/package.json index 24b2ab45..74511df6 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "@azure/storage-blob": "^12.10.0", "@googlemaps/react-wrapper": "^1.1.24", "@magic-sdk/admin": "^1.4.0", - "@next-auth/prisma-adapter": "^1.0.3", + "@next-auth/prisma-adapter": "^1.0.4", "@prisma/client": "^3.12.0", "@webdeb/next-styles": "^1.1.1", "applicationinsights": "^2.2.0", @@ -86,4 +86,4 @@ "prettier": "2.5.1", "prisma": "^3.12.0" } -} +} \ No newline at end of file diff --git a/pages/account/register.js b/pages/account/register.js index b2e64851..644f71de 100644 --- a/pages/account/register.js +++ b/pages/account/register.js @@ -18,6 +18,7 @@ import { reduxForm, formValueSelector } from "redux-form"; import RegisterForm from "../../components/account/registerform"; import { dehashString, hashAPIPath } from "../../actions"; +import { getSession, useSession, signIn, signOut } from "next-auth/react"; const Home = (props) => { const { footerLinks, formData, loggedInUserEmail } = props; @@ -156,22 +157,23 @@ const Home = (props) => { }; export const getServerSideProps = wrapper.getServerSideProps( - (store) => - async ({ query, req, res }) => { - let hasRegistrationEmail = typeof query.id != "undefined"; - let loginEmailStr = ""; + (store) => async (ctx) => { + const { query, req, res } = ctx; - if (hasRegistrationEmail == true) { - loginEmailStr = dehashString(query.id); + let thisSession = await getSession(ctx); - console.log(loginEmailStr); - } - return { - props: { - loggedInUserEmail: loginEmailStr, - }, - }; - } + console.log( + "auth sess for register :", + thisSession, + thisSession.user.email + ); + + return { + props: { + loggedInUserEmail: thisSession.user.email, + }, + }; + } ); const mapStateToProps = (state) => { diff --git a/pages/api/auth/[...nextauth].js b/pages/api/auth/[...nextauth].js index fab3f813..068c3b30 100644 --- a/pages/api/auth/[...nextauth].js +++ b/pages/api/auth/[...nextauth].js @@ -125,6 +125,12 @@ export default NextAuth({ //signOut: "/auth/signout", error: "/auth/error", // Error code passed in query string as ?error= verifyRequest: "/auth/verify-request", // (used for check email message) - // newUser: "/auth/new-user", // New users will be directed here on first sign in (leave the property out if not of interest) + newUser: "/account/register", // New users will be directed here on first sign in (leave the property out if not of interest) + }, + callbacks: { + session: async (session, user) => { + console.log(user); + return Promise.resolve(session); + }, }, }); diff --git a/pages/error.js b/pages/error.js index 4a378e1d..39bb90f0 100644 --- a/pages/error.js +++ b/pages/error.js @@ -15,7 +15,7 @@ function Error({ statusCode }, props) {
- {t("case:page-title")} - {t("common:service-name")} + {t("common:error-page-title")} - {t("common:service-name")}
diff --git a/pages/index.js b/pages/index.js index a65625c8..12914ed9 100644 --- a/pages/index.js +++ b/pages/index.js @@ -44,7 +44,13 @@ const Home = (props) => { expDate.setDate(now.getDate() + 1); //console.log("hashed email str", loginEmailStr); - hasLoginCode != false + + //const { data: session } = useSession(); + + //console.log("has session:", session); + //console.log("has LoginCode", hasLoginCode); + + hasLoginCode == false ? console.log("no session") : _.has(loggedInUserId, "value") ? _.isEmpty(loggedInUserId.value) @@ -163,6 +169,8 @@ export const getServerSideProps = wrapper.getServerSideProps( let thisSession = await getSession(ctx); + console.log(ctx); + var relayToken = await getToken(); relayToken = relayToken.access_token; @@ -171,7 +179,9 @@ export const getServerSideProps = wrapper.getServerSideProps( const showLoginCheck = process.env.SHOWLOGIN || false; const showMapCheck = process.env.SHOWMAPS || false; - const hasLoginCode = thisSession != null; + let hasLoginCode = thisSession != null; + + console.log("server side has session:", thisSession != null); // let providerConfig = await getProviderConfig(); let ggLocale = @@ -227,6 +237,7 @@ export const getServerSideProps = wrapper.getServerSideProps( hasSession: hasLoginCode, loggedInUserId: portalUserObj, loggedInUserEmail: loginEmailStr, + hasLoginCode: hasLoginCode, }, }; } diff --git a/pages/newappeal/index.js b/pages/newappeal/index.js index c710748a..227bdc36 100644 --- a/pages/newappeal/index.js +++ b/pages/newappeal/index.js @@ -1,5 +1,7 @@ import useTranslation from "next-translate/useTranslation"; import Head from "next/head"; +import { getSession, useSession } from "next-auth/react"; + import { useRouter } from "next/router"; import { connect } from "react-redux"; import { @@ -24,7 +26,7 @@ import { getGovGatewayConfig } from "../../store/govgateway/action"; import { getProviderConfig } from "../../actions/govgateway"; const Home = (props) => { - const { footerLinks, pages, formData } = props; + const { footerLinks, pages, formData, loggedInUserIdent } = props; let { t, lang } = useTranslation(); const router = useRouter(); @@ -118,6 +120,7 @@ const Home = (props) => { appealType={props.setAppealType} loggedInUser={props.accountDetails.loggedinUserId} whichForm={props.form} + loggedInUserIdent={loggedInUserIdent} />
@@ -135,7 +138,10 @@ export const getServerSideProps = wrapper.getServerSideProps( const { cookies } = req; console.log("/newappeal - cookies ", cookies); + let thisSession = await getSession(ctx); + console.log("nextAuth Session:", thisSession); + let loggedInUserIdent = thisSession.user.id; let loggedInUser = cookies.pinsUser; console.log("has loggedInUser", loggedInUser); @@ -157,6 +163,10 @@ export const getServerSideProps = wrapper.getServerSideProps( store.dispatch(setLPA(lpaData)); store.dispatch(setLoggedInUserId(loggedInUser)); store.dispatch(setAccountDetails(accountDetails)); + + return { + props: { loggedInUserIdent: loggedInUserIdent }, + }; } ); diff --git a/prisma/migrations/20220419063544_nextauthmigration/migration.sql b/prisma/migrations/20220419063544_nextauthmigration/migration.sql index b59e5472..db95ab9b 100644 --- a/prisma/migrations/20220419063544_nextauthmigration/migration.sql +++ b/prisma/migrations/20220419063544_nextauthmigration/migration.sql @@ -1,57 +1,61 @@ -- CreateTable -CREATE TABLE `accounts` ( - `id` VARCHAR(191) NOT NULL, - `user_id` VARCHAR(191) NOT NULL, - `type` VARCHAR(191) NOT NULL, - `provider` VARCHAR(191) NOT NULL, - `provider_account_id` VARCHAR(191) NOT NULL, - `refresh_token` TEXT NULL, - `access_token` TEXT NULL, - `expires_at` INTEGER NULL, - `token_type` VARCHAR(191) NULL, - `scope` VARCHAR(191) NULL, - `id_token` TEXT NULL, - `session_state` VARCHAR(191) NULL, +-- SQLINES LICENSE FOR EVALUATION USE ONLY +CREATE TABLE accounts ( + id VARCHAR(191) NOT NULL, + user_id VARCHAR(191) NOT NULL, + type VARCHAR(191) NOT NULL, + provider VARCHAR(191) NOT NULL, + provider_account_id VARCHAR(191) NOT NULL, + refresh_token VARCHAR(max) NULL, + access_token VARCHAR(max) NULL, + expires_at INTEGER NULL, + token_type VARCHAR(191) NULL, + scope VARCHAR(191) NULL, + id_token VARCHAR(max) NULL, + session_state VARCHAR(191) NULL, - UNIQUE INDEX `accounts_provider_provider_account_id_key`(`provider`, `provider_account_id`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + CONSTRAINT accounts_provider_provider_account_id_key UNIQUE (provider, provider_account_id), + PRIMARY KEY (id) +) -- CreateTable -CREATE TABLE `sessions` ( - `id` VARCHAR(191) NOT NULL, - `session_token` VARCHAR(191) NOT NULL, - `user_id` VARCHAR(191) NOT NULL, - `expires` DATETIME(3) NOT NULL, +-- SQLINES LICENSE FOR EVALUATION USE ONLY +CREATE TABLE sessions ( + id VARCHAR(191) NOT NULL, + session_token VARCHAR(191) NOT NULL, + user_id VARCHAR(191) NOT NULL, + expires DATETIME2(3) NOT NULL, - UNIQUE INDEX `sessions_session_token_key`(`session_token`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + CONSTRAINT sessions_session_token_key UNIQUE (session_token), + PRIMARY KEY (id) +) -- CreateTable -CREATE TABLE `users` ( - `id` VARCHAR(191) NOT NULL, - `name` VARCHAR(191) NULL, - `email` VARCHAR(191) NULL, - `email_verified` DATETIME(3) NULL, - `image` VARCHAR(191) NULL, +-- SQLINES LICENSE FOR EVALUATION USE ONLY +CREATE TABLE users ( + id VARCHAR(191) NOT NULL, + name VARCHAR(191) NULL, + email VARCHAR(191) NULL, + email_verified DATETIME2(3) NULL, + image VARCHAR(191) NULL, - UNIQUE INDEX `users_email_key`(`email`), - PRIMARY KEY (`id`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + CONSTRAINT users_email_key UNIQUE (email), + PRIMARY KEY (id) +) -- CreateTable -CREATE TABLE `verificationtokens` ( - `identifier` VARCHAR(191) NOT NULL, - `token` VARCHAR(191) NOT NULL, - `expires` DATETIME(3) NOT NULL, +-- SQLINES LICENSE FOR EVALUATION USE ONLY +CREATE TABLE verificationtokens ( + identifier VARCHAR(191) NOT NULL, + token VARCHAR(191) NOT NULL, + expires DATETIME2(3) NOT NULL, - UNIQUE INDEX `verificationtokens_token_key`(`token`), - UNIQUE INDEX `verificationtokens_identifier_token_key`(`identifier`, `token`) -) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + CONSTRAINT verificationtokens_token_key UNIQUE (token), + CONSTRAINT verificationtokens_identifier_token_key UNIQUE (identifier, token) +) -- AddForeignKey -ALTER TABLE `accounts` ADD CONSTRAINT `accounts_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE accounts ADD CONSTRAINT accounts_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE; -- AddForeignKey -ALTER TABLE `sessions` ADD CONSTRAINT `sessions_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE sessions ADD CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/old_migration_lock.toml similarity index 100% rename from prisma/migrations/migration_lock.toml rename to prisma/migrations/old_migration_lock.toml diff --git a/prisma/mysql_schema.prisma b/prisma/mysql_schema.prisma new file mode 100644 index 00000000..e260260d --- /dev/null +++ b/prisma/mysql_schema.prisma @@ -0,0 +1,61 @@ +datasource db { + provider = "mysql" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + + + +model Account { + id String @id @default(cuid()) + userId String @map("user_id") + type String + provider String + providerAccountId String @map("provider_account_id") + refresh_token String? @db.Text + access_token String? @db.Text + expires_at Int? + token_type String? + scope String? + id_token String? @db.Text + session_state String? + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([provider, providerAccountId]) + @@map("accounts") +} + +model Session { + id String @id @default(cuid()) + sessionToken String @unique @map("session_token") + userId String @map("user_id") + expires DateTime + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@map("sessions") +} + +model User { + id String @id @default(cuid()) + name String? + email String? @unique + emailVerified DateTime? @map("email_verified") + image String? + accounts Account[] + sessions Session[] + + @@map("users") +} + +model VerificationToken { + identifier String + token String @unique + expires DateTime + + @@unique([identifier, token]) + @@map("verificationtokens") +} diff --git a/prisma/schema.prisma b/prisma/schema.prisma index e260260d..5dbf11a5 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -1,27 +1,26 @@ datasource db { - provider = "mysql" - url = env("DATABASE_URL") + provider = "sqlserver" + url = env("DATABASE_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") } generator client { - provider = "prisma-client-js" + provider = "prisma-client-js" } - - model Account { - id String @id @default(cuid()) - userId String @map("user_id") - type String - provider String - providerAccountId String @map("provider_account_id") - refresh_token String? @db.Text - access_token String? @db.Text - expires_at Int? - token_type String? - scope String? - id_token String? @db.Text - session_state String? + id String @id @default(cuid()) + userId String @map("user_id") + type String + provider String + providerAccountId String + refresh_token String? @db.Text + access_token String? @db.Text + expires_at Int? + token_type String? + scope String? + id_token String? @db.Text + session_state String? user User @relation(fields: [userId], references: [id], onDelete: Cascade)