这是indexloc提供的服务,不要输入任何密码
Skip to content

Issue/392 require tanam user role to access the cms #410

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions functions/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Compiled JavaScript files
lib
lib/**/*.js
lib/**/*.js.map

Expand Down
2 changes: 1 addition & 1 deletion functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"lint:fix": "npm run lint --fix",
"logs": "firebase functions:log",
"prettier:fix": "prettier --write .",
"serve": "npm run build && firebase emulators:start --only functions",
"serve": "npm run build && firebase emulators:start --only auth,functions,firestore",
"shell": "npm run build && firebase functions:shell"
},
"name": "functions",
Expand Down
2 changes: 1 addition & 1 deletion functions/src/triggers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const tanamNewUserInit = onDocumentCreated("tanam-users/{docId}", async (

// Function to enforce role management on document update
// This function will apply changes to custom claims when the role field is updated
export const onRoleChange = onDocumentUpdated("tanam-users/{docId}", async (event) => {
export const onTanamUserRoleChange = onDocumentUpdated("tanam-users/{docId}", async (event) => {
const uid = event.params.docId;
const beforeData = event?.data?.before.data();
const afterData = event?.data?.after.data();
Expand Down
25 changes: 25 additions & 0 deletions hosting/src/app/(protected)/error/insufficient-role/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"use client";
import Loader from "@/components/common/Loader";
import Notification from "@/components/common/Notification";
import PageHeader from "@/components/common/PageHeader";
import {useAuthentication} from "@/hooks/useAuthentication";
import {useTanamUser} from "@/hooks/useTanamUser";
import {Suspense} from "react";

export default function ErrorInsufficientRolePage() {
const {authUser} = useAuthentication();
const {error: userError} = useTanamUser(authUser?.uid);

return (
<>
<Suspense fallback={<Loader />}>
<PageHeader pageName="Insufficient role" />
<Notification
type="error"
title={userError?.title || "Something wrong"}
message={userError?.message || "Unknown error"}
/>
</Suspense>
</>
);
}
16 changes: 16 additions & 0 deletions hosting/src/app/(protected)/error/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"use client";
import Loader from "@/components/common/Loader";
import Notification from "@/components/common/Notification";
import PageHeader from "@/components/common/PageHeader";
import {Suspense} from "react";

export default function ErrorPage() {
return (
<>
<Suspense fallback={<Loader />}>
<PageHeader pageName="Error" />
<Notification type="error" title="Something wrong" message="Unknown error" />
</Suspense>
</>
);
}
3 changes: 1 addition & 2 deletions hosting/src/app/(protected)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"use client";

import CmsLayout from "@/components/Layouts/CmsLayout";
import React from "react";
import {useAuthentication} from "@/hooks/useAuthentication";
import {redirect} from "next/navigation";
import React from "react";

interface ProtectedLayoutProps {
children: React.ReactNode;
Expand Down
9 changes: 2 additions & 7 deletions hosting/src/components/Header/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import DarkModeSwitcher from "@/components/Header/DarkModeSwitcher";
import DropdownUser from "@/components/Header/DropdownUser";
import {useAuthentication} from "@/hooks/useAuthentication";
import {useTanamUser} from "@/hooks/useTanamUser";
import Image from "next/image";
import Link from "next/link";
import {useEffect} from "react";
import {useTanamUser} from "../../hooks/useTanamUser";

const Header = (props: {sidebarOpen: string | boolean | undefined; setSidebarOpen: (arg0: boolean) => void}) => {
const {authUser} = useAuthentication();
const {data: tanamUser, error: userError} = useTanamUser(authUser?.uid);

useEffect(() => {
console.log("userError", userError);
}, [userError]);
const {data: tanamUser} = useTanamUser(authUser?.uid);

return (
<header className="sticky top-0 z-999 flex w-full bg-white drop-shadow-1 dark:bg-boxdark dark:drop-shadow-none">
Expand Down
22 changes: 22 additions & 0 deletions hosting/src/hooks/useAuthentication.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
"use client";
import {firebaseAuth} from "@/plugins/firebase";
import {TanamRole} from "@functions/models/TanamUser";
import {User} from "firebase/auth";
import {redirect, usePathname} from "next/navigation";
import {useEffect, useState} from "react";

export function useAuthentication() {
const pathname = usePathname();

const [error, setError] = useState<Error | null>(null);
const [authUser, setUser] = useState<User | null>(null);
const [userRole, setUserRole] = useState<TanamRole | null>(null);
const [isSignedIn, setIsSignedIn] = useState<boolean | null>(null);

useEffect(() => {
const unsubscribe = firebaseAuth.onAuthStateChanged((user) => {
console.log("[onAuthStateChanged]", {user});
setUser(user);
setIsSignedIn(!!user);
fetchUserRole();
});

return () => unsubscribe();
}, []);

async function fetchUserRole() {
try {
const idTokenResult = await firebaseAuth.currentUser?.getIdTokenResult();

setUserRole((idTokenResult?.claims as {tanamRole: TanamRole}).tanamRole);

// Redirect when user doesnt have claims
if (pathname !== "/error/insufficient-role" && (userRole === null || !userRole)) {
redirect("/error/insufficient-role");
}
} catch (error) {
setError(error as Error);
}
}

async function signout() {
console.log("[signout]");
try {
Expand All @@ -30,6 +51,7 @@ export function useAuthentication() {
return {
isSignedIn,
authUser,
userRole,
error,
signout,
setError,
Expand Down
6 changes: 5 additions & 1 deletion hosting/src/hooks/useFirebaseUi.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";
import {firebaseAuth} from "@/plugins/firebase";
import {AuthCredential, EmailAuthProvider, GoogleAuthProvider} from "firebase/auth";
import {auth as firebaseAuthUi} from "firebaseui";
import {AuthCredential, GoogleAuthProvider} from "firebase/auth";
import "firebaseui/dist/firebaseui.css";
import {useEffect, useState} from "react";

Expand Down Expand Up @@ -31,6 +31,10 @@ export function useFirebaseUi() {
tosUrl: "https://github.com/oddbit/tanam/blob/main/docs/tos.md",
privacyPolicyUrl: "https://github.com/oddbit/tanam/blob/main/docs/privacy-policy.md",
signInOptions: [
{
provider: EmailAuthProvider.PROVIDER_ID,
fullLabel: isSignUp ? "Sign up with email" : "Sign in with email",
},
Comment on lines +34 to +37
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding email sign in is not part of the scope

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just a change in indentation when doing yarn codecheck

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, it seems there was a mistake from me because I forgot to delete the testing code. I thought it was just because of the indentation problem and I forgot to add it. I also forgot if we don't have a login with email button.
I'll delete it in the next update

{
provider: GoogleAuthProvider.PROVIDER_ID,
fullLabel: isSignUp ? "Sign up with Google" : "Sign in with Google",
Expand Down
4 changes: 4 additions & 0 deletions hosting/src/hooks/useTanamUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export function useTanamUser(uid?: string): UseTanamDocumentsResult {
const unsubscribe = onSnapshot(
docRef,
(snapshot) => {
if (!snapshot.exists()) {
setError(new UserNotification("error", "Access Denied", "Sorry you cant access the page"));
}

const tanamUser = TanamUserClient.fromFirestore(snapshot);
setData(tanamUser);
},
Expand Down
Loading