diff --git a/README.md b/README.md index 3e296b68..ca1468bc 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,16 @@ Once the program is finished: - Please, for Eric's sake, make sure you didn't break anything *Note: This program was primarily made with the intention of making "coding" and "haystack"-type problems.* -*If you make mutation problems, the finished problem directory will be placed correctly, **but will be missing the mutation.py files*** +*If you make mutation problems, the finished problem directory will be placed correctly,* **but will be missing the mutation.py files** + + +### Create New Users + +- To create new users, ensure you have a service role key in your .env as `SUPABASE_SERVICE_ROLE_KEY` + - This can be found right under the Anon key, see "Run Locally" above **THE VALUE IS SECRET, DO NOT SHARE** +- Run `node scripts/create-users.mjs ` +- The script will print out the new users login credentials +*Note: As the app no longer uses emails, resetting a password would need to be done manually in SQL.* **Please ask users to be careful and not lose their creds** ### Modify Contract diff --git a/scripts/create-users.ts b/scripts/create-users.ts new file mode 100644 index 00000000..0a051db3 --- /dev/null +++ b/scripts/create-users.ts @@ -0,0 +1,104 @@ +import { createClient } from "@supabase/supabase-js"; +import { readFileSync } from "fs"; +import { config } from "dotenv";import { createRequire } from "module"; +import { fileURLToPath } from "url"; +import { dirname, join } from "path"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +config({ path: join(__dirname, "../.env.local") }); + +const SUPABASE_URL = process.env.REACT_APP_SUPABASE_URL; +const SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY; +// not a real domain, just to comply with Supabase email field +const EMAIL_DOMAIN = "coding-cat.internal"; + +if (!SUPABASE_URL || !SERVICE_ROLE_KEY) { + console.error("Missing REACT_APP_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env"); + process.exit(1); +} + +const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, { + auth: { autoRefreshToken: false, persistSession: false } +}); + +const usernameParts = JSON.parse(readFileSync(join(__dirname, "./username-words.json"), "utf-8")); +const usedUsernames: string[] = []; + +function generateAdjAnimalCombo() { + const adjective = usernameParts.adjectives[ + Math.floor(Math.random() * usernameParts.adjectives.length) + ]; + const animal = usernameParts.animals[ + Math.floor(Math.random() * usernameParts.animals.length) + ]; + + return `${adjective}${animal}`; +} + +function generateUniqueUsername() { + let username; + + do{ + username = generateAdjAnimalCombo() + Math.floor(Math.random() * 1000); + }while(usedUsernames.includes(username)); + usedUsernames.push(username); + + return username; +} + +async function createUser(username: string, password: string) { + const email = `${username}@${EMAIL_DOMAIN}`; + + const { data, error } = await supabase.auth.admin.createUser({ + email, + password, + email_confirm: true, + }); + + if (error) { + console.error(`Auth error for "${username}": ${error.message}`); + return false; + } + + const { error: profileError } = await supabase + .from("profiles") + .upsert({ + profile_id: data.user.id, + username: username, + created_at: data.user.created_at, + }, { onConflict: "profile_id" }); + + if (profileError) { + console.error(`Profile error for "${username}": ${profileError.message}`); + return false; + } + + return true; +} + +async function main() { + const count = parseInt(process.argv[2]); + if (!count || isNaN(count) || count < 1) { + console.error("Usage: node create-users.mjs "); + console.error("Example: node create-users.mjs 10"); + process.exit(1); + } + + console.log(`\nCreating ${count} users...\n`); + + let successCount = 0; + + for (let i = 0; i < count; i++) { + const username = generateUniqueUsername(); + const password = generateAdjAnimalCombo(); + const ok = await createUser(username, password); + if (ok) { + console.log(`User: ${username}\nPass: ${password}\n`); + successCount++; + } + } + console.log(`Done. ${successCount}/${count} users created successfully.`); + console.log("Note: usernames are not case-sensitive, passwords are") +} + +main(); diff --git a/scripts/username-words.json b/scripts/username-words.json new file mode 100644 index 00000000..ffca7061 --- /dev/null +++ b/scripts/username-words.json @@ -0,0 +1,226 @@ +{ + "adjectives": [ + "Agile", + "Amber", + "Ancient", + "Arctic", + "Ashen", + "Astral", + "Autumn", + "Azure", + "Bamboo", + "Blazing", + "Bold", + "Brave", + "Breezy", + "Bright", + "Bronze", + "Calm", + "Candid", + "Celestial", + "Clever", + "Cloudy", + "Cobalt", + "Coding", + "Cosmic", + "Crimson", + "Crystal", + "Curious", + "Dancing", + "Daring", + "Dawn", + "Desert", + "Distant", + "Divine", + "Dreamy", + "Dusky", + "Dynamic", + "Echoing", + "Electric", + "Elegant", + "Emerald", + "Epic", + "Fabled", + "Feral", + "Fiery", + "Flying", + "Forest", + "Frozen", + "Gentle", + "Ghostly", + "Glacial", + "Golden", + "Grand", + "Hidden", + "Hollow", + "Icy", + "Iron", + "Ivory", + "Jade", + "Jolly", + "Jovial", + "Lively", + "Lunar", + "Majestic", + "Mellow", + "Midnight", + "Mighty", + "Misty", + "Moonlit", + "Mystic", + "Nimble", + "Noble", + "Nova", + "Obsidian", + "Ocean", + "Phantom", + "Plucky", + "Polar", + "Prairie", + "Primal", + "Quick", + "Quiet", + "Radiant", + "Rapid", + "Ravenous", + "Regal", + "River", + "Roaming", + "Royal", + "Rustic", + "Savage", + "Scarlet", + "Shadow", + "Shimmering", + "Silent", + "Silver", + "Skybound", + "Solar", + "Stormy", + "Swift", + "Thunder", + "Timber", + "Twilight", + "Velvet", + "Verdant", + "Vibrant", + "Violet", + "Wandering", + "Whispering", + "Wild", + "Winter", + "Wise", + "Zealous" + ], + "animals": [ + "Aardvark", + "Albatross", + "Alligator", + "Alpaca", + "Antelope", + "Armadillo", + "Badger", + "Barracuda", + "Bat", + "Bear", + "Beaver", + "Bison", + "Boar", + "Buffalo", + "Butterfly", + "Camel", + "Capybara", + "Caribou", + "Cassowary", + "Cat", + "Cheetah", + "Cobra", + "Condor", + "Cougar", + "Coyote", + "Crab", + "Crane", + "Crocodile", + "Crow", + "Deer", + "Dingo", + "Dolphin", + "Dragonfly", + "Duck", + "Eagle", + "Echidna", + "Falcon", + "Ferret", + "Firefly", + "Fox", + "Frog", + "Gazelle", + "Gecko", + "Giraffe", + "Goose", + "Gorilla", + "Hawk", + "Hedgehog", + "Heron", + "Hippo", + "Horse", + "Hummingbird", + "Hyena", + "Ibex", + "Iguana", + "Jackal", + "Jaguar", + "Jellyfish", + "Kangaroo", + "Kingfisher", + "Koala", + "Kraken", + "Lemur", + "Leopard", + "Lion", + "Llama", + "Lobster", + "Lynx", + "Mammoth", + "Manatee", + "Meerkat", + "Moose", + "Narwhal", + "Newt", + "Octopus", + "Opossum", + "Orca", + "Otter", + "Owl", + "Panther", + "Parrot", + "Peacock", + "Penguin", + "Phoenix", + "Puma", + "Python", + "Rabbit", + "Raccoon", + "Raven", + "Rhino", + "Salamander", + "Scorpion", + "Seahorse", + "Seal", + "Shark", + "Sloth", + "Sparrow", + "Spider", + "Squid", + "Swan", + "Tabby", + "Tiger", + "Toucan", + "Turtle", + "Viper", + "Walrus", + "Wolf", + "Yak", + "Zebra" + ] +} \ No newline at end of file diff --git a/src/components/layout/UpperNavBar.tsx b/src/components/layout/UpperNavBar.tsx index bf3522c9..45645719 100644 --- a/src/components/layout/UpperNavBar.tsx +++ b/src/components/layout/UpperNavBar.tsx @@ -104,9 +104,6 @@ export default function UpperNavBar({ - - - )} diff --git a/src/components/profile/UserInfo.tsx b/src/components/profile/UserInfo.tsx index 0dd89ef6..1e00d832 100644 --- a/src/components/profile/UserInfo.tsx +++ b/src/components/profile/UserInfo.tsx @@ -1,9 +1,10 @@ import { Session } from "@supabase/supabase-js"; import { FormEvent, useEffect, useState } from "react"; import { supabase } from "../../supabaseClient"; -import { Button, FormLabel, Input, Stack, Typography } from "@mui/joy"; +import { Button, Stack, Typography } from "@mui/joy"; import { useOutletContext } from "react-router-dom"; import ProfileAvatar from "./ProfileAvatar"; +import { UserData } from "../../types"; // TODO: maybe get these dynamically? export const ALL_PFPS = [ @@ -14,10 +15,8 @@ export const ALL_PFPS = [ "thumbs-up-pfp.png" ] -export default function UserInfo({ refetchProfile }: { refetchProfile: Function }) { +export default function UserInfo({ userData, refetchProfile }: { userData: UserData | null, refetchProfile: Function }) { const [isUpdating, setIsUpdating] = useState(false); - const [name, setName] = useState(""); - const [id, setId] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [success, setSuccess] = useState(""); @@ -41,17 +40,15 @@ export default function UserInfo({ refetchProfile }: { refetchProfile: Function const { data, error } = await supabase .from('profiles') - .select('username, student_id, pfp_id') + .select('username, pfp_id') .eq('profile_id', user.id) .single(); if (!ignore) { if (error) { - alert(error.message); + setError(error.message); console.warn(error); } else if (data) { - setName(data.username ?? "Unnamed User"); - setId(data.student_id ?? ""); setPfpFileName(ALL_PFPS[data.pfp_id] ?? 0); setPfpArrPos(data.pfp_id ?? 0); } @@ -79,8 +76,6 @@ export default function UserInfo({ refetchProfile }: { refetchProfile: Function const updates = { profile_id: user.id, - username: name, - student_id: id, updated_at: new Date(), pfp_id: pfpArrPos }; @@ -115,32 +110,25 @@ export default function UserInfo({ refetchProfile }: { refetchProfile: Function isUpdating ?
- Edit Profile - Profile Picture - - - - + + + + - Name - setName(e.target.value)} - /> - Student ID - setId(e.target.value)} - /> - + {success} } diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts index a8a9ddf4..67b34908 100644 --- a/src/hooks/useAuth.ts +++ b/src/hooks/useAuth.ts @@ -1,11 +1,7 @@ import { useState, useEffect, useCallback } from 'react'; import { supabase } from '../supabaseClient'; import { type Session } from '@supabase/supabase-js'; - -interface UserData { - name: string; - pfp_id: number; -} +import { UserData } from '../types'; interface UseAuthReturn { session: Session | null; diff --git a/src/index.css b/src/index.css index 1914d4fa..f0aa919d 100644 --- a/src/index.css +++ b/src/index.css @@ -225,6 +225,7 @@ textarea{ padding: 20px; margin: 10px 40px 30px; flex-direction: row; + align-self: center; border-radius: 10px; } diff --git a/src/index.tsx b/src/index.tsx index d17c07ee..33015e4e 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -13,15 +13,12 @@ import ErrorPage from './error'; import { theme } from './theme'; import Login from './routes/Login'; -import Register from './routes/Register'; import AccountWrapper from './routes/AccountWrapper'; import MainTutorial from './components/MainTutorial'; import PreSessionForm from './components/PreSessionForm'; import PostSessionForm from './components/PostSessionForm'; import AdminWrapper, { adminLoader } from './routes/AdminWrapper'; import AdminPage from './routes/AdminPage'; -import ChangePassword from './routes/ChangePassword'; -import ReqPasswordChange from './routes/ReqPasswordChange'; import AuthCallback from './routes/AuthCallback'; import Auth from './routes/Auth'; import BlogPostView, { blogPostLoader } from './routes/BlogPostView'; @@ -67,14 +64,6 @@ const router = createHashRouter([ path: "signin", element: }, - { - path: "change-password-req", - element: - }, - { - path: "register", - element: - }, { path: "profile", element: @@ -99,10 +88,6 @@ const router = createHashRouter([ { path: "callback", element: - }, - { - path: "change-password", - element: } ] } diff --git a/src/routes/Account.tsx b/src/routes/Account.tsx index dc00c663..f6d00ce8 100644 --- a/src/routes/Account.tsx +++ b/src/routes/Account.tsx @@ -11,6 +11,7 @@ import OtherStats from "../components/profile/progress/other-stats/OtherStats"; import { useOutletContext } from "react-router-dom"; import SessionReflections from "../components/profile/sessions/SessionReflections"; import useActivityTracker from "../hooks/useActivityTracker"; +import { UserData } from "../types"; /** * The `Account` component handles everything related to the profile page. @@ -18,6 +19,7 @@ import useActivityTracker from "../hooks/useActivityTracker"; */ export default function Account({ session }: { session: Session }) { const { refetchProfile } = useOutletContext<{ refetchProfile: () => Promise }>(); + const { userData } = useOutletContext<{ userData: UserData | null }>(); // Change "reflections" into something else const [view, setView] = useState<"reflections" | "activity" | "sessions">("reflections"); @@ -36,19 +38,28 @@ export default function Account({ session }: { session: Session }) { } = useActivityTracker(user); return ( - + - - + + + + Contract + - diff --git a/src/routes/ChangePassword.tsx b/src/routes/ChangePassword.tsx deleted file mode 100644 index 408234d9..00000000 --- a/src/routes/ChangePassword.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { FormEvent, useState } from 'react' -import { supabase } from '../supabaseClient' -import { Box, Button, FormLabel, Input, Stack, Typography } from '@mui/joy'; -import { Navigate } from 'react-router-dom'; - -/** - * Change Password page for the app. - */ -export default function ChangePassword() { - const [done, setDone] = useState(false); - const [loading, setLoading] = useState(false); - const [newPassword, setNewPassword] = useState(""); - const [error, setError] = useState(""); - - const handleSubmit = async (event: FormEvent) => { - event.preventDefault(); - setError(""); - setLoading(true); - - const { error } = await supabase.auth.updateUser({ password: newPassword }); - - if (error) { - setError(error.message); - } else { - await supabase.auth.signOut(); - setDone(true); - } - setLoading(false); - } - - if (done) return ; - - return ( - - Change Password -
- - New Password - setNewPassword(e.target.value)} - /> - - -
- {!!error && {error}} -
- ) -} diff --git a/src/routes/Login.tsx b/src/routes/Login.tsx index 1a63f25d..e9db84f9 100644 --- a/src/routes/Login.tsx +++ b/src/routes/Login.tsx @@ -1,7 +1,7 @@ import { FormEvent, useEffect, useState } from 'react' import { supabase } from '../supabaseClient' import { Box, Button, FormLabel, Input, Stack, Typography } from '@mui/joy'; -import { Link, Navigate, useOutletContext } from 'react-router-dom'; +import { Navigate, useOutletContext } from 'react-router-dom'; import { Session } from '@supabase/supabase-js'; /** @@ -9,9 +9,8 @@ import { Session } from '@supabase/supabase-js'; */ export default function Login() { const [loading, setLoading] = useState(false); - const [email, setEmail] = useState(""); + const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); - const [error, setError] = useState(""); const [success, setSuccess] = useState(""); const { session } = useOutletContext<{ session: Session | null }>(); @@ -19,7 +18,7 @@ export default function Login() { // Clear data on unmount so it doesn't stay in memory useEffect(() => { return () => { - setEmail(""); + setUsername(""); setPassword(""); }; }, []); @@ -34,10 +33,15 @@ export default function Login() { setSuccess(""); setLoading(true); - const { error } = await supabase.auth.signInWithPassword({ - email: email, - password: password - }); + const { error } = username.includes("@") + ? await supabase.auth.signInWithPassword({ + email: username, + password: password + }) + : await supabase.auth.signInWithPassword({ + email: `${username}@coding-cat.internal`, + password: password + }); if (error) { setError(error.message); @@ -56,11 +60,11 @@ export default function Login() { Email setEmail(e.target.value)} + onChange={(e) => setUsername(e.target.value)} /> Password Loading : Login} - - - { !!error && {error} } { !!success && {success} }
diff --git a/src/routes/Register.tsx b/src/routes/Register.tsx deleted file mode 100644 index 9ef02e2a..00000000 --- a/src/routes/Register.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { FormEvent, useEffect, useState } from 'react' -import { supabase } from '../supabaseClient' -import { Box, Button, FormLabel, Input, Stack, Typography } from '@mui/joy'; -import { Navigate, useOutletContext } from 'react-router-dom'; -import { Session } from '@supabase/supabase-js'; - -/** - * Register page for the app. - */ -export default function Register() { - // TODO: on register the user should be able to write their contract - const [loading, setLoading] = useState(false); - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - - const [error, setError] = useState(""); - const [success, setSuccess] = useState(""); - const { session } = useOutletContext<{ session: Session | null }>(); - - // Clear data on unmount so it doesn't stay in memory - useEffect(() => { - return () => { - setEmail(""); - setPassword(""); - }; - }, []); - - if (session) { - return - } - - const handleRegister = async (event: FormEvent) => { - event.preventDefault(); - setError(""); - setSuccess(""); - setLoading(true); - - const { data: signUpData, error: signUpError } = await supabase.auth.signUp({ - email: email, - password: password, - options: { - // !! if this is edited, it needs to match with the Supabase redirect URLs !! - // check 'Authentication/URL Configuration' - // ${window.location.origin} sets it dynamically to localhost or coding-cat.club - emailRedirectTo: `${window.location.origin}/#/auth/callback`, - }, - }); - - if(signUpError){ - setError(signUpError.message); - } - - if(signUpData.user){ - const { error: createProfileError } = await supabase - .from('profiles') - .insert({ - created_at: signUpData.user.created_at, - profile_id: signUpData.user.id - }); - if(createProfileError){ - setError(createProfileError.message); - }else{ - setSuccess('User Registered!'); - } - }else{ - setError("Something went wrong registering..."); - } - - setLoading(false); - } - - return ( - - Register -
- - Email - setEmail(e.target.value)} - /> - Password - setPassword(e.target.value)} - /> - - -
- { !!error && {error} } - { !!success && {success} } -
- ) -} diff --git a/src/routes/ReqPasswordChange.tsx b/src/routes/ReqPasswordChange.tsx deleted file mode 100644 index 85013da8..00000000 --- a/src/routes/ReqPasswordChange.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { FormEvent, useState } from 'react' -import { supabase } from '../supabaseClient' -import { Box, Button, FormLabel, Input, Stack, Typography } from '@mui/joy'; - -/** - * Request Password Change page for the app. - */ -export default function ReqPasswordChange() { - const [loading, setLoading] = useState(false); - const [email, setEmail] = useState(""); - const [error, setError] = useState(""); - const [success, setSuccess] = useState(""); - - const handleSubmit = async (event: FormEvent) => { - event.preventDefault(); - setError(""); - setSuccess(""); - setLoading(true); - - const { error } = await supabase.auth.resetPasswordForEmail(email, { - // !! if this is edited, it needs to match with the Supabase redirect URLs !! - // check 'Authentication/URL Configuration - // ${window.location.origin} sets it dynamically to localhost or coding-cat.club - redirectTo: `${window.location.origin}/` - }); - - if(error){ - setError(error.message) - }else { - setSuccess("Check your email for a password reset link!") - } - - setLoading(false); - } - - return ( - - Reset Password -
- - Email - setEmail(e.target.value)} - /> - - -
- { !!error && {error} } - { !!success && {success} } -
- ) -} diff --git a/src/routes/root.tsx b/src/routes/root.tsx index b2108036..7d96aff0 100644 --- a/src/routes/root.tsx +++ b/src/routes/root.tsx @@ -371,7 +371,7 @@ export default function App() { setActiveProblem, session, isAdmin, refetchProgress: fetchProgress, refetchProfile: fetchProfile, activeSession, sessionId, sessionRemainingSeconds, sessionDuration, plannedExerciseCount, problemSessionStats, setProblemSessionStats, - progress, sessionTimerRunning, + progress, sessionTimerRunning, userData }} /> diff --git a/src/types.ts b/src/types.ts index 5bf7751d..0164fbe0 100644 --- a/src/types.ts +++ b/src/types.ts @@ -229,4 +229,9 @@ export interface SessionReflectionRecord { exercise_goals: number; pre_session_reflection: FormAnswers | null; post_session_reflection: FormAnswers | null; +} + +export interface UserData { + name: string; + pfp_id: number; } \ No newline at end of file