Skip to content

Commit

Permalink
Added JWT on top of Firebase-Admin (#178)
Browse files Browse the repository at this point in the history
* Made error case for email in use display correctly in front end

* Made error case for email in use display correctly in front end (#158)

* Cleaned up useEffect function #159

* Added testing pipeline (#175)

* Create main.yml

* Update main.yml

* Update _layout.tsx

* Update main.yml

* Update socketio.test.ts

* Update socketio.test.ts

* Update _layout.tsx

* User Context and User Type created and wrapped chat screen (#131)

* added user context

* Added userID and displayName

* moved user and display name generation into UserProvider

* Improved UserContext implementation

Amongst these changes, the user type on the frontend has been edited in order
to prevent hidden functions that would pull information into the UserContext
from other contexts. The message type was also modified to keep a new author
section with a displayName attribute. An issue should be created for a socket
API endpoint for grabbing the displayName, and one to set it in a connectedUser
document in the databse.

* updated package lock

---------

Co-authored-by: h1divp <[email protected]>

* Set up Firebase-Admin in adminInit.ts (#155)

* new branch + function fix

* small bug fixes

* fixes pt2

* JWT WIP

* new branch + function fix

* small bug fixes

* fixes pt2

* JWT WIP

* new branch + function fix

* small bug fixes

* fixes pt2

* JWT WIP

* new branch + function fix

* small bug fixes

* added passport

* started auth + admin sdk

* removed passport

* added private key to gitignore

* Delete server/private_keys/private.json

---------

Co-authored-by: AlexanderWangY <[email protected]>

* Refactored most of the actions (#156)

* new branch + function fix

* small bug fixes

* fixes pt2

* JWT WIP

* new branch + function fix

* small bug fixes

* fixes pt2

* JWT WIP

* new branch + function fix

* small bug fixes

* fixes pt2

* JWT WIP

* new branch + function fix

* small bug fixes

* added passport

* started auth + admin sdk

* removed passport

* added private key to gitignore

* Delete server/private_keys/private.json

* initializing firestore in admin

* finished most of action refactoring

* Made error case for email in use display correctly in front end (#158)

* changed getConnectedUsers to admin

* migrated to firebase-admin

---------

Co-authored-by: AlexanderWangY <[email protected]>
Co-authored-by: Mohammed Ali <[email protected]>

* added middleware

---------

Co-authored-by: Phantom0110 <[email protected]>
Co-authored-by: Mohammed Ali <[email protected]>
Co-authored-by: AaronGibson2 <[email protected]>
Co-authored-by: h1divp <[email protected]>
Co-authored-by: AlexanderWangY <[email protected]>
  • Loading branch information
6 people authored Feb 25, 2024
1 parent 386b646 commit 9263c96
Show file tree
Hide file tree
Showing 14 changed files with 229 additions and 67 deletions.
65 changes: 65 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
name: Unit Tests

on: [pull_request]

jobs:
test:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [21.x]

steps:
- name: Checkout repository
uses: actions/checkout@v2

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}

- name: Install dependencies
run: npm ci
working-directory: server/

- name: Set up environment variables
env:
API_KEY: ${{ secrets.API_KEY }}
AUTH_DOMAIN: ${{ secrets.AUTH_DOMAIN }}
PROJECT_ID: ${{ secrets.PROJECT_ID }}
STORAGE_BUCKET: ${{ secrets.STORAGE_BUCKET }}
MESSAGING_SENDER_ID: ${{ secrets.MESSAGING_SENDER_ID }}
APP_ID: ${{ secrets.APP_ID }}
MESSAGE_OUTREACH_RADIUS: ${{ secrets.MESSAGE_OUTREACH_RADIUS }}
EXPRESS_PORT: ${{ secrets.EXPRESS_PORT }}
SOCKET_PORT: ${{ secrets.SOCKET_PORT }}
SOCKET_TEST_CLIENT_PORT: ${{ secrets.SOCKET_TEST_CLIENT_PORT }}
run: |
echo "API_KEY=${API_KEY}" >> .env
echo "AUTH_DOMAIN=${AUTH_DOMAIN}" >> .env
echo "PROJECT_ID=${PROJECT_ID}" >> .env
echo "STORAGE_BUCKET=${STORAGE_BUCKET}" >> .env
echo "MESSAGING_SENDER_ID=${MESSAGING_SENDER_ID}" >> .env
echo "APP_ID=${APP_ID}" >> .env
echo "message_outreach_radius=${MESSAGE_OUTREACH_RADIUS}" >> .env
echo "express_port=${EXPRESS_PORT}" >> .env
echo "socket_port=${SOCKET_PORT}" >> .env
echo "socket_test_client_port=${SOCKET_TEST_CLIENT_PORT}" >> .env
working-directory: server/

- name: Compile TypeScript files
run: npx tsc
working-directory: server/

- name: Start index.ts in background
run: npm start &
working-directory: server/

- name: Wait for server to start
run: sleep 5 # Adjust sleep time as needed to allow the server to start
timeout-minutes: 1

- name: Run tests
run: npm test
working-directory: server/
21 changes: 12 additions & 9 deletions client/src/app/(home)/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@ import { Stack } from "expo-router";
import { SettingsProvider } from "../../contexts/SettingsContext";
import { SocketProvider } from "../../contexts/SocketContext";
import { LocationProvider } from "../../contexts/LocationContext";
import { UserProvider } from "../../contexts/UserContext";

const AuthLayout = () => {
return (
<LocationProvider>
<SocketProvider>
<SettingsProvider>
<Stack
screenOptions={{
headerShown: false,
}}
>
<Stack.Screen name="chatchannel" options={{}} />
</Stack>
</SettingsProvider>
<UserProvider>
<SettingsProvider>
<Stack
screenOptions={{
headerShown: false,
}}
>
<Stack.Screen name="chatchannel" options={{}} />
</Stack>
</SettingsProvider>
</UserProvider>
</SocketProvider>
</LocationProvider>
);
Expand Down
14 changes: 9 additions & 5 deletions client/src/components/Chat/ChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import {
import { ChatInput } from "../Common/CustomInputs";
import { ChatSendButton } from "../Common/CustomButtons";
import MessageChannel from "../Common/MessageChannel";
import { LinearGradient } from "expo-linear-gradient";
import * as Crypto from "expo-crypto";
import { generateName } from "../../utils/scripts";
import { useSettings } from "../../contexts/SettingsContext";
import { SignOutButton } from "../Common/AuthButtons"
import { MessageType } from "../../types/Message";
import { LocationProvider } from "../../contexts/LocationContext";
import { useSocket } from "../../contexts/SocketContext";
import { useSettings } from "../../contexts/SettingsContext";
import { useLocation } from "../../contexts/LocationContext";
import { useUser } from "../../contexts/UserContext"; // imported for when it needs to be used
import { AuthStore } from "../../services/store";

const ChatScreen = () => {
Expand All @@ -32,8 +32,10 @@ const ChatScreen = () => {
const keyboardBehavior = Platform.OS === "ios" ? "padding" : undefined;
const socket = useSocket();
const location = useLocation();
const { user } = AuthStore.useState();

const user = useUser();
const userAuth = AuthStore.useState()
// Note: To prevent complexity, all user information is grabbed from different contexts and services. If we wanted most information inside of UserContext, we would have to import contexts within contexts and have state change as certain things mount, which could cause errors that are difficult to pinpoint.

// Message loading and sending logic
const [messages, setMessages] = React.useState<MessageType[]>([]);
const [messageContent, setMessageContent] = React.useState<string>("");
Expand All @@ -54,7 +56,9 @@ const ChatScreen = () => {
const onHandleSubmit = () => {
if (messageContent.trim() !== "") {
const newMessage: MessageType = {
uid: String(user?.uid),
author: {
uid: String(userAuth.userAuthInfo?.uid),
},
msgId: Crypto.randomUUID(),
msgContent: messageContent.trim(),
timeSent: Date.now(),
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Common/MessageChannel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const MessageChannel: React.FC<MessageChannelProps> = ({ messages }) => {
renderItem={({ item }) => (
<Message
messageContent={item.msgContent}
author={item.uid} // TODO: call server to get author name from UID. Or should this stored with MessageType?
author={item.author.uid}
time={item.timeSent}
/>
)}
Expand Down
3 changes: 3 additions & 0 deletions client/src/contexts/LocationContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ export const LocationProvider = ({
// Cleanup function to clear interval when component unmounts
return () => clearInterval(interval);
})();

return () => console.log("[LOG]: Cleaning up location useEffect");

}, []);

return (
Expand Down
3 changes: 0 additions & 3 deletions client/src/contexts/SettingsContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ export const SettingsProvider = ({
children: React.ReactNode;
}) => {
const [theme, setTheme] = useState("light");
const [displayName, setDisplayName] = useState("");
const [foregroundPfpImage, setForegroundPfpImage] = useState("");
const [backgroundPfpImage, setBackgroundPfpImage] = useState("");

// Initial settings load
useEffect(() => {
Expand Down
57 changes: 41 additions & 16 deletions client/src/contexts/SocketContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { createContext, useContext, useEffect, useState } from "react";
import { io, Socket } from "socket.io-client";
import { useLocation } from "./LocationContext";
import { EXPO_IP } from "@env";
import { AuthStore } from "../services/store";

const SocketContext = createContext<Socket | null>(null);

Expand All @@ -11,32 +12,56 @@ export const useSocket = () => {

export const SocketProvider = ({ children }: { children: React.ReactNode }) => {
const [socket, setSocket] = useState<Socket | null>(null);
const [mounted, setMounted] = useState(false);
const locationContext = useLocation();

useEffect(() => {
let isMounted = true;

const socketIo = io(`http://${ EXPO_IP }:8080`); // Hardcoded IP address
useEffect(() => {
const getToken = async () => {
const token = await AuthStore.getRawState().userAuthInfo?.getIdToken();
console.log("Token:", token);
return token;
}

const initializeSocket = async () => {
const token = await getToken();
const socketIo = io(`http://${EXPO_IP}:8080`, {
auth: {
token: token,
}
});

socketIo.on("connect", () => {
if (isMounted) {
setSocket(socketIo);
} else {
console.log("Socket not mounted");
}
});
setSocket(socketIo);
setMounted(true);
}

// socketIo.on("message", (data: MessageType, ack) => {
// console.log("Sending message to server:", data);
// if (ack) console.log("Server acknowledged message:", ack);
// });
if (!mounted) {
initializeSocket();
}

return () => {
isMounted = false;
socketIo.disconnect();
console.log("[LOG]: Cleaning up intializeSocket useEffect");
};
}, []);

// Listen to the socket state and run once the socket is set!
useEffect(() => {

if (!socket) return;

socket.on("connect", () => {
console.log("Connected to server");
}
);

return () => {
console.log("[LOG]: Cleaning up sockets and mounted state.");
socket.disconnect();
setSocket(null);
setMounted(false);
}
}, [socket]);

useEffect(() => {
// TODO: Refactor this useEffect into a different file (service?) outside of the context, as it is not part of the purpose of a context.
if (
Expand Down
25 changes: 25 additions & 0 deletions client/src/contexts/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React, { createContext, useContext } from 'react';
import { UserType } from '../types/User';
import { useState } from 'react';

const UserContext = createContext<UserType | null>(null);

export const useUser = () => {
return useContext(UserContext);
}

export const UserProvider = ({ children }: {children: React.ReactNode}) => {
const [user, setUser] = useState<UserType>({
displayName: "DefaultDisplayName",
userIcon: {
imagePath: "DefaultImagePath",
colorHex: "#fff"
},
});

return (
<UserContext.Provider value={user}>
{children}
</UserContext.Provider>
);
};
19 changes: 10 additions & 9 deletions client/src/services/store.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,37 @@
import { User, createUserWithEmailAndPassword, onAuthStateChanged, signInWithEmailAndPassword, signOut } from 'firebase/auth'
import { Store } from 'pullstate'
import { auth } from '../configs/firebaseConfig'
import { auth, app } from '../configs/firebaseConfig'



interface AuthStoreInterface {
isLoggedin: boolean,
initialized: boolean,
user: User | null,
userAuthInfo: User | null,
}

export const AuthStore = new Store<AuthStoreInterface>({
isLoggedin: false,
initialized: false,
user: null,
userAuthInfo: null,
})

const unsub = onAuthStateChanged(auth, (user) => {
console.log('onAuthStateChanged', user);
AuthStore.update((store) => {
store.initialized = true,
store.isLoggedin = user ? true : false,
store.user = user
store.userAuthInfo = user
})
});

export const appSignIn = async (email: string, password: string) => {
try {
const response = await signInWithEmailAndPassword(auth, email, password);
AuthStore.update((store) => {
store.user = response?.user;
store.userAuthInfo = response?.user;
store.isLoggedin = response?.user ? true : false;
});
console.log('appSignIn', await response.user.getIdToken()); // This is the token we need to send to the server
return { user: auth.currentUser };
} catch (e) {
return { error: e };
Expand All @@ -41,7 +42,7 @@ export const appSignOut = async () => {
try {
await signOut(auth);
AuthStore.update((store) => {
store.user = null;
store.userAuthInfo = null;
store.isLoggedin = false;
});
return { user: null}
Expand All @@ -55,11 +56,11 @@ export const appSignUp = async (email: string, password: string) => {
const response = await createUserWithEmailAndPassword(auth, email, password);

AuthStore.update((store) => {
store.user = response.user;
store.userAuthInfo = response.user;
store.isLoggedin = response.user ? true : false;
});
return { user: auth.currentUser}
} catch (e) {
return { error: e };
}
};
};
6 changes: 4 additions & 2 deletions client/src/types/Message.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
export interface MessageType {
uid: string
authorName?: string // To be only used for display purposes (i.e. do not send to server)
author: {
uid: string
displayName?: string // To be only used for display purposes (do not send to server)
}
msgId: string
msgContent: string
timeSent: number // Unix timestamp; Date.now() returns a Number.
Expand Down
7 changes: 7 additions & 0 deletions client/src/types/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface UserType {
displayName: string
userIcon?: {
imagePath: string
colorHex: string
}
}
11 changes: 11 additions & 0 deletions client/src/utils/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type MessageType = {
messageContent: string;
author: string;
msgID: string;
};

export type UserType = {
userID: string;
displayName: string;
pfp: string;
};
Loading

0 comments on commit 9263c96

Please sign in to comment.