log in as other user

This commit is contained in:
Dobromir Popov
2024-04-13 13:04:02 +03:00
parent 717cd8499d
commit 471cbc0a55
5 changed files with 65 additions and 16 deletions

View File

@ -10,26 +10,13 @@ NEXTAUTH_SECRET=1dd8a5457970d1dda50600be28e935ecc4513ff27c49c431849e6746f158d638
# ? do we need to duplicate this? already defined in the deoployment yml file
DATABASE=mysql://jwpwsofia_demo:dwxhns9p9vp248@mariadb:3306/jwpwsofia_demo
APPLE_ID=
APPLE_TEAM_ID=
APPLE_PRIVATE_KEY=
APPLE_KEY_ID=
AUTH0_ID=Aa9f3HJowauUrmBVY4iQzQJ7fYsaZDbK
AUTH0_SECRET=_c0O9GkyRXkoWMQW7jNExnl6UoXN6O4oD3mg7NZ_uHVeAinCUtcTAkeQmcKXpZ4x
AUTH0_ISSUER=https://dev-wkzi658ckibr1amv.us.auth0.com
FACEBOOK_ID=
FACEBOOK_SECRET=
GITHUB_ID=
GITHUB_SECRET=
# GOOGLE_ID=926212607479-d3m8hm8f8esp3rf1639prskn445sa01v.apps.googleusercontent.com
# GOOGLE_SECRET=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
TWITTER_ID=
TWITTER_SECRET=
MAILTRAP_HOST_BULK=bulk.smtp.mailtrap.io
MAILTRAP_HOST=live.smtp.mailtrap.io
MAILTRAP_USER=api

View File

@ -7,7 +7,7 @@ import DayOfWeek from "../DayOfWeek";
import TextEditor from "../TextEditor";
import FileUploadWithPreview from 'components/FileUploadWithPreview ';
import ProtectedRoute, { serverSideAuth } from "../..//components/protectedRoute";
import ProtectedRoute, { serverSideAuth } from "../../components/protectedRoute";
import { UserRole } from "@prisma/client";
const common = require('src/helpers/common');

View File

@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'
import toast from "react-hot-toast";
import axiosInstance from '../../src/axiosSecure';
import ProtectedRoute, { serverSideAuth } from "../../components/protectedRoute";
//add months to date. works with negative numbers and numbers > 12
export function addMonths(numOfMonths, date) {
@ -53,6 +54,23 @@ export default function PublisherCard({ publisher }) {
console.log(JSON.stringify(error));
}
};
const handleLoginAs = async (userId) => {
const response = await fetch('/api/auth/login-as', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId }),
});
if (response.ok) {
const data = await response.json();
// Assuming you have some context or state management to update the session
updateSession(data.session);
} else {
alert("Failed to impersonate user.");
}
};
return isCardVisible ? (
// className="block p-6 max-w-sm bg-white rounded-lg border border-gray-200 shadow-md hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700 mb-3"
@ -89,6 +107,10 @@ export default function PublisherCard({ publisher }) {
<path fillRule="evenodd" d="M4.293 4.293A1 1 0 015.707 3.707L10 8l4.293-4.293a1 1 0 111.414 1.414L11.414 9l4.293 4.293a1 1 0 01-1.414 1.414L10 10.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 9 4.293 4.707a1 1 0 010-1.414z" clipRule="evenodd" /> */}
</svg>
</button>
<ProtectedRoute>
<button onClick={() => handleLoginAs(publisher.id)}>Login as</button>
</ProtectedRoute>
</div>
<style jsx>{`
.cardFadeOut {

View File

@ -18,7 +18,7 @@ const common = require("../../../src/helpers/common");
import { isLoggedIn, setAuthTokens, clearAuthTokens, getAccessToken, getRefreshToken } from 'axios-jwt'
console.log("appleID:", process.env.APPLE_ID);
console.log("appleID:", process.env.APPLE_APP_ID);
// console.log(process.env.EMAIL_SERVER)
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
@ -43,7 +43,7 @@ export const authOptions: NextAuthOptions = {
}
}),
AppleProvider({
clientId: process.env.APPLE_ID,
clientId: process.env.APPLE_APP_ID,
clientSecret: process.env.APPLE_SECRET
}),
// AzureADProvider({

View File

@ -0,0 +1,40 @@
// pages/api/auth/login-as.js
import { getSession } from "next-auth/react";
import prisma from '../../../lib/prisma'; // Adjust the path as per your setup
export default async function handler(req, res) {
const session = await getSession({ req });
if (session && session.user.role === 'admin') {
const { userId } = req.body;
const userToImpersonate = await prisma.publisher.findUnique({
where: { id: userId }
});
if (userToImpersonate) {
// Create a custom session object for the impersonated user
const impersonatedSession = {
...session,
user: {
...session.user,
id: userToImpersonate.id,
email: userToImpersonate.email,
name: userToImpersonate.name,
role: userToImpersonate.role,
// add other necessary fields
},
impersonating: true, // flag to indicate impersonation
originalUser: session.user // save the original user for later
};
// Here you would typically use some method to create a session server-side
// For this example, we'll just send the impersonated session as a response
res.status(200).json({ session: impersonatedSession });
} else {
res.status(404).json({ error: 'User not found' });
}
} else {
res.status(403).json({ error: 'Unauthorized' });
}
}