Skip to content

Commit

Permalink
Use single method to update session (#16)
Browse files Browse the repository at this point in the history
* Use single method to update session

* Remove unused cookie lib
  • Loading branch information
polldo authored May 21, 2023
1 parent c2ee1cb commit 7654dc5
Show file tree
Hide file tree
Showing 7 changed files with 22 additions and 62 deletions.
7 changes: 2 additions & 5 deletions core/auth/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,11 @@ func HandleOauthCallback(db *sqlx.DB, session *scs.SessionManager, provs map[str

func HandleLogout(session *scs.SessionManager) web.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
session.Remove(ctx, userKey)
session.Remove(ctx, roleKey)

if err := session.RenewToken(ctx); err != nil {
if err := session.Destroy(ctx); err != nil {
return err
}

return nil
return web.Respond(ctx, w, nil, http.StatusNoContent)
}
}

Expand Down
25 changes: 0 additions & 25 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@
},
"dependencies": {
"@next/font": "13.1.6",
"@types/js-cookie": "^3.0.3",
"@types/node": "18.11.18",
"@types/react": "18.0.27",
"@types/react-dom": "18.0.10",
"buffer": "^6.0.3",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"js-cookie": "^3.0.5",
"next": "13.1.6",
"react": "18.2.0",
"react-dom": "18.2.0",
Expand Down
15 changes: 9 additions & 6 deletions frontend/pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@ import { useSession } from '@/session/context'
import { useFetch } from '@/services/fetch'

export default function Login() {
const router = useRouter()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')

const { isLoggedIn, isLoading, login } = useSession()
const { isLoggedIn, isLoading, updateSession } = useSession()
const router = useRouter()
const fetch = useFetch()

if (isLoading) {
return null
}

if (isLoggedIn) {
router.push('activate')
router.push('dashboard')
return null
}

const handleSubmit = async (e: React.FormEvent) => {
Expand All @@ -41,8 +45,7 @@ export default function Login() {
if (!res.ok) {
throw new Error('Something went wrong')
}

login()
updateSession()
} catch (err) {
if (err instanceof Error) {
setError(err.message)
Expand Down
2 changes: 1 addition & 1 deletion frontend/pages/signup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { useState } from 'react'
import { useRouter } from 'next/router'

export default function Signup() {
const router = useRouter()
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string>('')
const router = useRouter()

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
Expand Down
4 changes: 2 additions & 2 deletions frontend/services/fetch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useSession } from '@/session/context'
// - adds the 'credentials' header, to allow sending the session cookie to the backend.
// - calls the logout function when a 401 error is returned.
export function useFetch() {
const { logout } = useSession()
const { updateSession } = useSession()

async function customFetch(url: RequestInfo, options: RequestInit = {}): Promise<Response> {
if (options.method !== 'OPTIONS') {
Expand All @@ -13,7 +13,7 @@ export function useFetch() {

const response = await fetch(url, options)
if (response.status === 401) {
logout()
updateSession()
}

return response
Expand Down
29 changes: 8 additions & 21 deletions frontend/session/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,17 @@ import { ReactNode } from 'react'
import { useEffect } from 'react'
import { createContext } from 'react'
import { useContext } from 'react'
import Cookies from 'js-cookie'

type Session = {
isLoggedIn: boolean
isLoading: boolean
login: () => void
logout: () => void
updateSession: () => void
}

export const SessionContext = createContext<Session>({
isLoggedIn: false,
isLoading: true,
login: () => {},
logout: () => {},
updateSession: () => {},
})

export function useSession() {
Expand All @@ -27,36 +24,26 @@ export function SessionProvider(props: { children: ReactNode }) {
const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false)
const [isLoading, setIsLoading] = useState<boolean>(true)

// When the user wants to logout or the session expires, this function must be called.
function logout() {
Cookies.remove('session')
setIsLoggedIn(false)
}

// Upon login, the state is automatically added in cookies,
// so we only need to set the session state to true.
function login() {
setIsLoggedIn(true)
}

useEffect(() => {
function sync() {
const user = async () => {
const response = await fetch('http://mylocal.com:8000/users/current', { credentials: 'include' })
setIsLoggedIn(response.ok)
setIsLoading(false)
}

user().catch(() => {
setIsLoggedIn(false)
setIsLoading(false)
})
}

useEffect(() => {
sync()
}, [])

const session: Session = {
isLoggedIn: isLoggedIn,
isLoading: isLoading,
login: login,
logout: logout,
updateSession: sync,
}

return <SessionContext.Provider value={session}>{props.children}</SessionContext.Provider>
Expand Down

0 comments on commit 7654dc5

Please sign in to comment.