Skip to content

Added check for authenticated users access to public pages#185

Merged
sumagnadas merged 5 commits intoOpenLake:mainfrom
HarK-github:pr-public-route
Feb 23, 2026
Merged

Added check for authenticated users access to public pages#185
sumagnadas merged 5 commits intoOpenLake:mainfrom
HarK-github:pr-public-route

Conversation

@HarK-github
Copy link
Copy Markdown
Member

@HarK-github HarK-github commented Jan 24, 2026

Description

Prevents authenticated users from accessing public routes like
/login and /register by introducing a PublicRoute wrapper.

Changes

  • Added PublicRoute component
  • Tracked authentication state in AuthContext
  • Wrapped login & register routes
  • Added redirect handling in Login page

Type of Change

  • Bug fix

Checklist

  • Code follows project style
  • Tested locally
  • No new warnings

Summary by CodeRabbit

  • New Features
    • Authenticated users are now automatically redirected from login and registration pages to the home page.
    • Added a loading state that displays a full-page indicator during authentication checks for smoother transitions.
    • Improved login flow with automatic navigation after successful sign-in, including support for Google sign-in.
    • Apps consuming authentication status can now reliably detect whether a user is signed in for more consistent behavior across pages.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 24, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d3a25d1 and bcd9c02.

📒 Files selected for processing (1)
  • app/src/App.jsx

Walkthrough

The changes introduce a new PublicRoute component that protects public pages by redirecting authenticated users to the home page. AuthContext is updated to expose isAuthenticated and loading states. The Login component adds redirect logic when already authenticated. The App.jsx routing wraps public routes with the new guard component.

Changes

Cohort / File(s) Summary
Auth Context & State Management
app/src/Context/AuthContext.jsx
Added loading state and isAuthenticated derived property. Introduced useEffect to synchronize user state from authTokens and expose both values through context provider.
Public Route Protection
app/src/Context/PublicRoute.jsx
New component that prevents authenticated users from accessing public routes by checking auth status, rendering loading indicator during loading state, and redirecting to home when authenticated.
Route Configuration
app/src/App.jsx
Updated routing to wrap /register and /login routes with PublicRoute component for authentication checks.
Login Page Enhancement
app/src/components/Login.jsx
Added useEffect to redirect to home when authenticated. Expanded auth state consumption to include isAuthenticated and loading. Added full-page loading indicator and Google authentication handler.

Sequence Diagram

sequenceDiagram
    actor User
    participant App as App Router
    participant PublicRoute as PublicRoute Guard
    participant AuthContext as Auth Context
    participant Login as Login Component
    
    User->>App: Navigate to /login
    App->>PublicRoute: Render PublicRoute wrapper
    PublicRoute->>AuthContext: useAuth() for isAuthenticated & loading
    
    alt User is loading
        PublicRoute->>User: Show "Loading..." indicator
    else User is authenticated
        PublicRoute->>App: Navigate to "/"
        App->>User: Redirect to home
    else User is not authenticated
        PublicRoute->>Login: Render children (Login component)
        Login->>AuthContext: useAuth() for auth state
        User->>Login: Submit login/Google auth
        Login->>AuthContext: Update authentication tokens
        Login->>User: Redirect to home after successful auth
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A guard hop-hops to check who's here,
Authenticated friends get redirected clear!
Loading signs dance while we wait,
Public pages now secured—how great!
No sneaky logins, just clean code flow. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Added check for authenticated users access to public pages' directly summarizes the main change: preventing authenticated users from accessing public routes via a PublicRoute wrapper.
Description check ✅ Passed The description covers key sections including purpose, changes, and type of change with completed checklist items, though Related Issue(s) and Screenshots sections are missing.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@app/src/components/Heatmap.jsx`:
- Around line 11-21: The useEffect that calls fetchGitHubContributions() or
generateMockData() is missing the contributions prop in its dependency array,
causing stale mock heatmap data when contributions changes; update the effect
dependencies from [platform, username] to include contributions (i.e.,
[platform, username, contributions]) so the effect reruns when contributions
updates, ensuring generateMockData() and fetchGitHubContributions() produce
fresh data (refer to the useEffect block and the generateMockData and
fetchGitHubContributions functions).

In `@app/src/components/HomePage.jsx`:
- Around line 27-104: The code dereferences potentially null objects (userNames
and the prop passed into Cards), causing runtime errors; fix by guarding these
accesses: update the Cards signature to accept a safe default (e.g., function
Cards({ usernames } = { usernames: {} }) or destructure with usernames = {}),
and replace direct accesses like usernames.github?.contributions and
usernames.codeforces?.username with optional chaining and sensible defaults;
likewise, in HomePage replace direct userNames.username uses with
userNames?.username (or conditionally render the UI only when userNames is
non-null) so every dereference is null-safe and Heatmap/contribution props fall
back to 0 or empty string when absent.

In `@app/src/components/Login.jsx`:
- Around line 48-52: handleGoogleAuth currently calls SignInWithGoogle() without
inspecting its result and always calls navigate("/"); update handleGoogleAuth to
await and capture the return value from SignInWithGoogle(), verify the response
indicates a successful auth (e.g., truthy user object or success flag returned
by SignInWithGoogle), and only call navigate("/") when that check passes; keep
proper try/catch around the call to SignInWithGoogle() and in the error/failure
branch avoid navigation and surface an error state or message to the user.

In `@app/src/Context/AuthContext.jsx`:
- Around line 33-48: The effect that sets user and isAuthenticated runs only on
mount, so isAuthenticated gets stale; update the useEffect in AuthContext (the
useEffect that calls setUser, setIsAuthenticated, setLoading) to depend on
authTokens (add authTokens to the dependency array) or alternatively remove the
separate isAuthenticated state and derive it from authTokens (e.g., compute
isAuthenticated = Boolean(authTokens) or from authTokens.access) and remove
setIsAuthenticated usage; ensure the effect still calls
setUser(jwtDecode(authTokens.access)) when authTokens is present and clears
user/setIsAuthenticated when null.
🧹 Nitpick comments (1)
app/src/components/Heatmap.jsx (1)

23-46: Consider checking response.ok before parsing.

This makes failure modes clearer and avoids treating non‑200 responses as valid data.

🔧 Suggested tweak
-      const response = await fetch(`https://github-contributions-api.deno.dev/${username}.json`);
-      const data = await response.json();
+      const response = await fetch(`https://github-contributions-api.deno.dev/${username}.json`);
+      if (!response.ok) {
+        throw new Error(`GitHub contributions fetch failed: ${response.status}`);
+      }
+      const data = await response.json();

Comment on lines +11 to +21
useEffect(() => {
const fetchData = async () => {
if (platform === 'github' && username) {
await fetchGitHubContributions();
} else {
generateMockData();
}
};

fetchData();
}, [platform, username]);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

git ls-files | grep -i heatmap

Repository: OpenLake/Leaderboard-Pro

Length of output: 98


🏁 Script executed:

find . -name "Heatmap.jsx" -o -name "Heatmap.js"

Repository: OpenLake/Leaderboard-Pro

Length of output: 100


🏁 Script executed:

wc -l app/src/components/Heatmap.jsx

Repository: OpenLake/Leaderboard-Pro

Length of output: 102


🏁 Script executed:

cat -n app/src/components/Heatmap.jsx

Repository: OpenLake/Leaderboard-Pro

Length of output: 10444


Include contributions in the effect dependency array.

The generateMockData function (lines 97-131) reads the contributions prop to determine mock data intensity levels. When the effect calls generateMockData() and contributions changes, the effect won't re-run without it in the dependency array, leaving the heatmap with stale data.

🔧 Suggested fix
-  }, [platform, username]);
+  }, [platform, username, contributions]);
🤖 Prompt for AI Agents
In `@app/src/components/Heatmap.jsx` around lines 11 - 21, The useEffect that
calls fetchGitHubContributions() or generateMockData() is missing the
contributions prop in its dependency array, causing stale mock heatmap data when
contributions changes; update the effect dependencies from [platform, username]
to include contributions (i.e., [platform, username, contributions]) so the
effect reruns when contributions updates, ensuring generateMockData() and
fetchGitHubContributions() produce fresh data (refer to the useEffect block and
the generateMockData and fetchGitHubContributions functions).

Comment thread app/src/components/HomePage.jsx
Comment on lines 48 to +52
async function handleGoogleAuth(e) {
e.preventDefault();
await SignInWithGoogle();
navigate("/");
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cd /repo && find . -type f -name "Login.jsx" | head -20

Repository: OpenLake/Leaderboard-Pro

Length of output: 123


🏁 Script executed:

cd /repo && find . -type f -name "*.jsx" -o -name "*.js" | grep -i login | head -20

Repository: OpenLake/Leaderboard-Pro

Length of output: 123


🏁 Script executed:

cd /repo && rg "SignInWithGoogle" --type jsx --type js -A 3 -B 3 | head -100

Repository: OpenLake/Leaderboard-Pro

Length of output: 123


🏁 Script executed:

find . -type f -name "Login.jsx"

Repository: OpenLake/Leaderboard-Pro

Length of output: 98


🏁 Script executed:

find . -type f -name "*.jsx" -o -name "*.js" | grep -i login

Repository: OpenLake/Leaderboard-Pro

Length of output: 98


🏁 Script executed:

rg "SignInWithGoogle" -A 5 -B 2

Repository: OpenLake/Leaderboard-Pro

Length of output: 2739


🏁 Script executed:

cat -n ./app/src/components/Login.jsx | head -60

Repository: OpenLake/Leaderboard-Pro

Length of output: 2039


🏁 Script executed:

cat -n ./app/src/firebase/AuthContext.js | grep -A 10 "const SignInWithGoogle"

Repository: OpenLake/Leaderboard-Pro

Length of output: 402


🏁 Script executed:

cat -n ./app/src/Context/AuthContext.jsx | grep -A 30 "const SignInWithGoogle"

Repository: OpenLake/Leaderboard-Pro

Length of output: 1354


🏁 Script executed:

cat -n ./app/src/Context/AuthContext.jsx | sed -n '172,210p'

Repository: OpenLake/Leaderboard-Pro

Length of output: 1628


Gate navigation on successful Google sign‑in response.

The SignInWithGoogle() function returns a response object, but the current handler doesn't capture or check it before navigating. If authentication fails in the try-catch block, the response may be undefined or invalid, causing users to navigate to protected routes and bounce back. Capture the return value and navigate only on success.

🔧 Suggested fix
  async function handleGoogleAuth(e) {
    e.preventDefault();
-    await SignInWithGoogle();
-    navigate("/");
+    const response = await SignInWithGoogle();
+    if (response) {
+      navigate("/");
+    }
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function handleGoogleAuth(e) {
e.preventDefault();
await SignInWithGoogle();
navigate("/");
}
async function handleGoogleAuth(e) {
e.preventDefault();
const response = await SignInWithGoogle();
if (response) {
navigate("/");
}
}
🤖 Prompt for AI Agents
In `@app/src/components/Login.jsx` around lines 48 - 52, handleGoogleAuth
currently calls SignInWithGoogle() without inspecting its result and always
calls navigate("/"); update handleGoogleAuth to await and capture the return
value from SignInWithGoogle(), verify the response indicates a successful auth
(e.g., truthy user object or success flag returned by SignInWithGoogle), and
only call navigate("/") when that check passes; keep proper try/catch around the
call to SignInWithGoogle() and in the error/failure branch avoid navigation and
surface an error state or message to the user.

Comment thread app/src/Context/AuthContext.jsx Outdated
@github-actions

This comment has been minimized.

Refactor authentication state management by using a boolean derived from authTokens instead of a separate state variable.
@github-actions

This comment has been minimized.

@sumagnadas
Copy link
Copy Markdown
Collaborator

Can you separate the commits whicrh are to be merged after pulling the current main branch.

@github-actions

This comment has been minimized.

@sumagnadas sumagnadas merged commit 02c46c6 into OpenLake:main Feb 23, 2026
0 of 2 checks passed
@github-actions
Copy link
Copy Markdown

@check-spelling-bot Report

🔴 Please review

See the 📂 files view, the 📜action log, or 📝 job summary for details.

Unrecognized words (605)
actionlist
addfriend
addlink
aditya
adn
aec
alignof
amazonaws
amqp
antialiased
apexcharts
api
apk
APPS
args
argv
Arial
arrowright
asc
asgi
asm
atcoder
atcoderuser
atlaskit
atn
attr
atv
authtoken
autocomplete
autodiscover
axios
AZERBAIJANI
backend
barcode
bbb
bdsw
bebec
bitbucket
bitcoin
bitset
Bitstream
blang
blinenums
blockquote
blog
bradlc
breadcrumb
bsd
btc
btn
calendarbox
calendarin
calendarlink
calendarnav
Cantarell
ccc
CCPS
CCPSAPI
ccpsleetcoderanking
ccshowfriends
cdata
cdn
changelink
changelist
charset
checkbox
checkboxes
chmod
chooseall
cjs
classmethod
clearall
clickjacking
clockbox
clocklink
clojure
closelink
cls
clsx
cmdk
cnt
cny
codechef
codecheffriends
codeforces
codeforcesfriends
codeforcesuser
collectstatic
colspan
combobox
concat
config
Consolas
constexpr
contenttypes
coreapi
coredocs
cors
corsheaders
cpp
CRA
cred
crontab
csh
csrf
csrftoken
css
ctz
curated
curleft
curtop
cva
cxx
dabapps
dadce
dafb
darkmode
dartdoc
datetime
datetimeshortcuts
davegandy
dbaeumer
dblclick
dce
ddd
decltype
dedent
deletelink
deno
deps
describedby
dest
dfd
dirname
DIRS
discription
discussionpost
disscussion
django
djangoproject
Dmitriy
dnd
dnt
dockerfile
doctype
dotenv
downcode
Downcoder
draggable
drf
dribbble
DRILLDOWN
Droid
dropbox
dropdown
dropfriend
droppable
eaed
ececf
edecd
eee
efb
efcajlnqvdqjeoud
ele
elems
elif
elsif
enctype
endif
entrypoint
enum
EOL
eot
errexit
errorlist
errornote
esac
esbenp
eslint
eur
facebook
favicon
fbfbfc
FCalcutta
fdd
Fefer
fetchall
ffc
ffefef
fff
fieldset
fieldsetcollapser
filteredusers
findpos
Fira
flatpage
flickr
fontawesome
fontawesomeregular
foreach
formset
fromtimestamp
frontend
func
gamepad
gbp
getccfriends
getcffriends
getenv
getghfriends
getltfriends
gettext
ghshowfriends
github
githubfriends
githubusercontent
gittip
globals
glyphicons
gmail
gohri
google
GOOGLEDATA
gotop
graphql
grayscale
GSo
gtcvau
halflingsregular
hdd
heatmap
hexcolor
hiddenfields
hljs
Holovaty
hookform
horiz
howto
href
hsl
htm
html
http
Hyperlinked
ical
icnt
ico
iefix
ifdef
ifndef
iframe
img
inbox
INITDB
inlinechangelink
inlines
inlineviewlink
inp
inr
insertapi
Insitute
instagram
instanceof
INTV
isoformat
isready
Jannis
javadoc
javascript
javascriptreact
jpg
jpy
jsguide
json
jsx
jti
jumbotron
jumotron
JWK
jwt
keydown
keyframes
keyup
krw
kwargs
kwd
kwv
lbh
lccal
Lconf
leaderboard
leaderboardpro
leetcode
leetcodecontestrankings
leetcodefriends
leetcoderanking
leetcoderankingsccps
Leetocde
Leidel
len
Lexer
lify
lightgrey
linecap
linejoin
linenums
linkedin
linting
linux
linuxhint
localhost
lockfile
lodash
loglevel
logresponse
lsaquo
LTshowfriends
lucide
madueke
majodev
makemigrations
maxcdn
maxlength
medkit
meh
Memon
messagelist
metadata
Microsoft
middleware
mixin
mjs
mongodb
moz
mozilla
mql
multiline
mxml
namearr
namespace
navbar
ndx
Neue
ngettext
nginx
nocode
nodejs
nodesource
nonday
noopener
noreferrer
normarr
noscript
nowrap
npm
npx
nullptr
nums
offcanvas
ofhiuvw
OFL
oklch
onrender
openlake
opensource
opentype
opn
orderby
osx
outdent
pagelines
paginator
params
pathlib
perl
pgettext
Phalip
php
phpdoc
pinterest
pln
plugin
png
pnpm
Polovnyov
Polyfill
popup
postgre
postgresql
Powershell
PPK
pragma
prepopulate
prepopulated
prettyprint
progid
pyguide
pylint
pymongo
pypi
PYTHONPATH
qrcode
queryset
Quicklink
quirksmode
qyu
rabbitmq
radiolist
reactjs
readonly
redis
redislabs
regex
regexp
regresponse
reinit
renren
replypost
resizable
retweet
rgba
rmb
rmq
Roboto
robotstxt
rohit
rpdttenqphkdyvpuoeky
rsaquo
rsc
rss
rstrip
rtl
runserver
sbyte
scrollbars
scss
sdk
searchbar
searchfield
Segoe
selectfilter
selectfilterstacked
serializer
setattr
setcontestoptions
setdefault
setis
shadcn
showall
simplejwt
sitemap
sizeof
skype
solvedc
solvedl
sortoptions
sortpriority
sortremove
spsiphnqk
sqlite
src
stackalloc
stan
standalone
startproject
staticfiles
stderr
stdout
strftime
strictfp
strikethrough
stringify
strptime
stswe
styleguide
subdir
substr
sudo
Sumagna
sumagnadas
supabase
svg
svgr
svh
Swicegood
sys
tabbable
tabstyle
tailwindcss
tanstack
tbody
textarea
textfield
tfoot
thead
timedelta
timelist
timezone
timezonewarning
todisplayusers
TODO
toolbar
tooltag
tooltip
toplinks
trello
tripathi
truetype
tsx
ttext
ttf
TTFB
ttg
tumblr
typedef
typeid
typename
typeof
uage
ubuntu
uid
uint
ulk
ulong
uname
undef
unicode
unmounts
unsubscribe
upvotes
uri
url
URLCONF
urlencode
urlencoded
urlify
urllib
urlpatterns
usd
username
userphoto
userpic
usertasks
ushort
usr
utc
utf
utils
UUID
UXux
validator
venv
vercel
verdana
vhdl
VHOST
viewlink
viewsets
viewsitelink
vimeo
visualise
vitejs
vitest
vmin
vnd
vscode
vue
wantarray
webfont
webkit
webpack
website
weibo
whiteants
whitenoise
wiki
winutils
woff
WORKDIR
wsgi
www
xae
xaxis
xcode
XFrame
xfull
xhr
XHT
xhtml
XIcon
xing
xlink
xml
xmlns
xmp
XReg
xsl
xss
yaml
yapf
yaxis
youmightnotneedjquery
youtube
yuaoh
yzo
Some files were automatically ignored 🙈

These sample patterns would exclude them:

(?:^|/)__init__\.py$
(?:^|/)codechef\.svg$
(?:^|/)github\.svg$
(?:^|/)leetcode\.svg$
(?:^|/)pnpm-lock\.yaml$
/staticfiles_build/static/admin/img/gis/[^/]+$
[^/]\.eot$
[^/]\.ttf$
[^/]\.woff$
^\Q.cspell.json\E$
^\Qapi/staticfiles_build/static/rest_framework/docs/js/highlight.pack.js\E$
^\Qapi/staticfiles_build/static/rest_framework/js/coreapi-0.1.1.js\E$
^api/leaderboard/contest_data\.json$
^api/requirements\.txt$
^api/staticfiles_build/static/rest_framework/fonts/glyphicons-halflings-regular\.woff2$
^app/dump\.rdb$
^app/src/logo\.svg$

You should consider excluding directory paths (e.g. (?:^|/)vendor/), filenames (e.g. (?:^|/)yarn\.lock$), or file extensions (e.g. \.gz$)

You should consider adding them to:

.github/actions/spelling/excludes.txt

File matching is via Perl regular expressions.

To check these files, more of their words need to be in the dictionary than not. You can use patterns.txt to exclude portions, add items to the dictionary (e.g. by adding them to allow.txt), or fix typos.

To accept these unrecognized words as correct and update file exclusions, you could run the following commands

... in a clone of the git@github.com:HarK-github/Leaderboard-Pro.git repository
on the pr-public-route branch (ℹ️ how do I use this?):

curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/main/apply.pl' |
perl - 'https://github.com/OpenLake/Leaderboard-Pro/actions/runs/22309848367/attempts/1' &&
git commit -m 'Update check-spelling metadata'
Available 📚 dictionaries could cover words not in the 📘 dictionary
Dictionary Entries Covers Uniquely
cspell:django/dict/django.txt 393 62 18
cspell:software-terms/dict/softwareTerms.txt 1288 106 15
cspell:python/src/common/extra.txt 741 20 13
cspell:npm/dict/npm.txt 302 46 10
cspell:html/dict/html.txt 2060 46 7

Consider adding them (in .github/workflows/spelling.yml) in jobs:/spelling::

      with:
        extra_dictionaries: |
          cspell:django/dict/django.txt
          cspell:software-terms/dict/softwareTerms.txt
          cspell:python/src/common/extra.txt
          cspell:npm/dict/npm.txt
          cspell:html/dict/html.txt

To stop checking additional dictionaries, add (in .github/workflows/spelling.yml):

check_extra_dictionaries: ""
Warnings ⚠️ (4)

See the 📂 files view, the 📜action log, or 📝 job summary for details.

⚠️ Warnings Count
⚠️ binary-file 15
⚠️ minified-file 1
⚠️ noisy-file 5
⚠️ single-line-file 10

See ⚠️ Event descriptions for more information.

If you see a bunch of garbage

If it relates to a ...

well-formed pattern

See if there's a pattern that would match it.

If not, try writing one and adding it to the patterns.txt file.

Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

Note that patterns can't match multiline strings.

binary-ish string

Please add a file path to the excludes.txt file instead of just accepting the garbage.

File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants