-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: safe sessions handling in server with communication to central …
…command
- Loading branch information
Showing
13 changed files
with
278 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
"use client" | ||
|
||
import {useContext, useEffect} from "react"; | ||
import {logout} from "../../../lib/auth/authorization"; | ||
import {redirect} from "next/navigation"; | ||
import {AuthorizerContext} from "../../../context/authorizerContext"; | ||
|
||
const LogoutPage = () => { | ||
|
||
const {revalidateAuth} = useContext(AuthorizerContext); | ||
|
||
useEffect(() => { | ||
logout().then(_ => { | ||
revalidateAuth(); | ||
redirect("/"); | ||
} | ||
); | ||
}, []); | ||
} | ||
|
||
export default LogoutPage; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
'use server' | ||
|
||
import {LoginResponse} from "../../types/authTypes"; | ||
import {SignJWT, jwtVerify} from "jose"; | ||
import {cookies} from "next/headers"; | ||
import {isLoginResponse, parseError} from "../errors"; | ||
import {setSessionCookie} from "./session"; | ||
|
||
const secretKeyText = `${process.env.SECRET}`; | ||
const secretKey = new TextEncoder().encode(secretKeyText); | ||
|
||
|
||
export const encryptAuthContext = async (payload: LoginResponse) => { | ||
return await new SignJWT(payload as any) | ||
.setProtectedHeader({alg: "HS256"}) | ||
.setIssuedAt() | ||
.setExpirationTime("one day from now") | ||
.sign(secretKey); | ||
} | ||
|
||
export const decryptAuthContext = async (token: string) => { | ||
const {payload} = await jwtVerify(token, secretKey, {algorithms: ["HS256"]}); | ||
|
||
if (isLoginResponse(payload)) { | ||
return payload; | ||
} else { | ||
throw new Error("Invalid token payload structure."); | ||
} | ||
} | ||
|
||
export const loginWithCredentials = async (email: string, password: string) => { | ||
const response = await fetch(`${process.env.CC_API_URL}/accounts/login-credentials`, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify({email, password}) | ||
}); | ||
|
||
const parsed = evaluateResponse(response); | ||
|
||
if (isLoginResponse(parsed)) { | ||
await setSessionCookie(parsed) | ||
} | ||
|
||
return parsed; | ||
} | ||
|
||
export const loginWithToken = async (token: string) => { | ||
const response = await fetch(`${process.env.CC_API_URL}/accounts/login-token`, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
credentials: "include", | ||
body: JSON.stringify({token}) | ||
}); | ||
|
||
const parsed = evaluateResponse(response); | ||
|
||
if (isLoginResponse(parsed)) { | ||
await setSessionCookie(parsed); | ||
} | ||
|
||
return parsed; | ||
} | ||
|
||
export const logout = async () => { | ||
cookies().set("session", "", {expires: new Date(0)}); | ||
} | ||
|
||
const evaluateResponse = async (response: Response) => { | ||
if (response.ok) { | ||
return await response.json() as LoginResponse; | ||
} else { | ||
const errorData = await response.json(); | ||
return parseError(errorData); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
"use server" | ||
|
||
import {cookies} from "next/headers"; | ||
import {LoginResponse} from "../../types/authTypes"; | ||
import {encryptAuthContext} from "./authorization"; | ||
|
||
export const tryGetSessionCookie = (): { success: boolean, value?: string } => { | ||
const sessionCooke = cookies().get("session")?.value; | ||
if (sessionCooke) { | ||
return { success: true, value: sessionCooke }; | ||
} | ||
|
||
return { success: false }; | ||
} | ||
|
||
export const setSessionCookie = async (payload: LoginResponse) => { | ||
cookies().set("session", await encryptAuthContext(payload), { | ||
httpOnly: true, | ||
expires: new Date(Date.now() + 1000 * 60 * 60 * 24) | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
"use client" | ||
|
||
import {useEffect, useState} from "react"; | ||
import {LoginResponse} from "../../types/authTypes"; | ||
import {FieldError, GeneralError, isLoginResponse} from "../errors"; | ||
import {decryptAuthContext, loginWithToken, logout} from "./authorization"; | ||
import {tryGetSessionCookie, setSessionCookie} from "./session"; | ||
|
||
|
||
export const useAuth = () => { | ||
const [isLoggedIn, setIsLoggedIn] = useState(false); | ||
const [authContext, setAuthContext] = useState<LoginResponse | undefined>(); | ||
const [error, setError] = useState<GeneralError | FieldError | undefined>(); | ||
|
||
const getLoggedInState = async (isMounted: boolean) => { | ||
const sessionCookie = tryGetSessionCookie(); | ||
if (!sessionCookie.success) { | ||
isMounted && setIsLoggedIn(false); | ||
return; | ||
} | ||
|
||
try { | ||
const decrypted = await decryptAuthContext(sessionCookie.value!); | ||
console.log("session cookie", sessionCookie); | ||
console.log("decrypted", decrypted); | ||
|
||
const response = await loginWithToken(decrypted.token); | ||
if (isLoginResponse(response)) { | ||
isMounted && setIsLoggedIn(true); | ||
isMounted && setAuthContext(response); | ||
await refreshAuthContext(isMounted); | ||
} else { | ||
isMounted && setIsLoggedIn(false); | ||
isMounted && setError(response); | ||
await logout(); | ||
} | ||
} catch (e) { | ||
isMounted && setIsLoggedIn(false); | ||
isMounted && setError({error: 'Unexpected error occurred', status: 500}); | ||
await logout(); | ||
} | ||
}; | ||
|
||
const refreshAuthContext = async (isMounted: boolean) => { | ||
if (!isMounted) { | ||
return; | ||
} | ||
|
||
const sessionCookie = tryGetSessionCookie(); | ||
if (!sessionCookie.success) { | ||
return; | ||
} | ||
|
||
const decrypted = await decryptAuthContext(sessionCookie.value!); | ||
if (!isLoginResponse(decrypted)) { | ||
return; | ||
} | ||
|
||
const response = await loginWithToken(decrypted.token); | ||
if (!isLoginResponse(response)) { | ||
return; | ||
} | ||
|
||
await setSessionCookie(response); | ||
}; | ||
|
||
useEffect(() => { | ||
let isMounted = true; | ||
|
||
getLoggedInState(isMounted); | ||
|
||
return () => { | ||
isMounted = false; | ||
}; | ||
}, []); | ||
|
||
return {isLoggedIn, authContext, error}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import {LoginResponse} from "../types/authTypes"; | ||
|
||
interface ErrorBase { | ||
status: number; | ||
} | ||
|
||
export interface GeneralError extends ErrorBase{ | ||
error: string; | ||
} | ||
|
||
export interface FieldError extends ErrorBase { | ||
error: { | ||
[field: string]: string[]; | ||
}; | ||
} | ||
|
||
export const isLoginResponse = (response: any): response is LoginResponse => | ||
response && response.account && typeof response.token === 'string'; | ||
|
||
export const isGeneralError = (error: any): error is GeneralError => | ||
typeof error.error === 'string'; | ||
|
||
export const isFieldError = (error: any): error is FieldError => | ||
typeof error.error === 'object' && !Array.isArray(error.error) && error.error !== null | ||
|
||
export const parseError = (error: any) => { | ||
if (isGeneralError(error)) { | ||
return error as GeneralError; | ||
} else if (isFieldError(error)) { | ||
return error as FieldError; | ||
} else { | ||
return { | ||
status: 500, | ||
error: 'Unknown error structure' | ||
} as GeneralError; | ||
} | ||
}; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters