Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

authentication #12

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions livekit-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@tailwindcss/forms": "^0.5.7",
"axios": "^1.6.5",
"gray-matter": "^4.0.3",
"jose": "^5.2.0",
"livekit-client": "^1.15.5",
"marked": "^11.1.0",
"next": "14.0.4",
Expand All @@ -26,6 +27,7 @@
"remark-gfm": "^4.0.0",
"sass": "^1.69.5",
"tinykeys": "^2.1.0",
"universal-cookie": "^7.0.1",
"usehooks-ts": "^2.9.1",
"zustand": "^4.4.7"
},
Expand Down
96 changes: 55 additions & 41 deletions livekit-frontend/src/app/accounts/signin/page.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"use client"
'use client';
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';

import './signin.module.css';

const SignIn = () => {
Expand All @@ -12,64 +14,79 @@ const SignIn = () => {
const activateButton = (event) => {
// Add any button activation logic here
};

const handleSubmit = (event) => {
const router = useRouter();
const handleSubmit = async (event) => {
event.preventDefault();

const username = document.getElementById('Username').value;
const password = document.getElementById('password').value;

const formData = {
username: username,
password: password,
};

fetch('/accounts/signin/', {
// const formData = {
// username: username,
// password: password,
// };
const formData = new FormData(event.target);
const res = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
// Handle successful response
alert('login success');
window.location.href = ''; // Replace with the desired URL
console.log(data);
})
.catch((error) => {
// Handle errors
console.error('There was a problem with the fetch operation:', error);
});
body: JSON.stringify({ username, password }),
});
const { success } = await res.json();
if (success) {
router.push('/protected');
router.refresh();
} else {
alert('Login failed');
}

// fetch('/accounts/signin/', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify(formData),
// })
// .then((response) => {
// if (!response.ok) {
// throw new Error('Network response was not ok');
// }
// return response.json();
// })
// .then((data) => {
// // Handle successful response
// alert('login success');
// window.location.href = ''; // Replace with the desired URL
// console.log(data);
// })
// .catch((error) => {
// // Handle errors
// console.error('There was a problem with the fetch operation:', error);
// });
};

return (
<div className="all">

<form method="post" id="signin-form" onSubmit={handleSubmit} className='form'>
<form method="post" id="signin-form" onSubmit={handleSubmit} className="form">
<div className="cent">
<p>Web3bridge Meet</p>
<p>
<a href="#login">login</a>
</p>
</div>

<label className='label' htmlFor="Username">Username</label>
<input className='input' type="text" id="Username" name="Username" required />
<label className="label" htmlFor="Username">
Username
</label>
<input className="input" type="text" id="Username" name="Username" required />

<label className='label' htmlFor="password">password:</label>
<input className='input' type="password" id="password" name="password" required />
<label className="label" htmlFor="password">
password:
</label>
<input className="input" type="password" id="password" name="password" required />

<div className="additional-options">
<label className="checkbox-container label">
Remember this device
<input className='' type="checkbox" name="remember-me" />
<input className="" type="checkbox" name="remember-me" />
<span className="checkmark"></span>
</label>
<a href="/accounts/reset_password/">Forgot Password?</a>
Expand All @@ -86,10 +103,7 @@ const SignIn = () => {
</div>

<a href="/github_login/" className="github-button" type="submit">
<img
src="/githublogo.png"
alt="GitHub Logo"
/>
<img src="/githublogo.png" alt="GitHub Logo" />
GitHub
</a>
</form>
Expand Down
40 changes: 40 additions & 0 deletions livekit-frontend/src/app/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { SignJWT } from 'jose';
import { NextResponse } from 'next/server';
import { getJwtSecretKey } from '@/lib/auth';
// import { IncomingRequest } from 'http';

interface Body {
username: string;
password: string;
}

export async function POST(request: {
json: () => Body | PromiseLike<Body>;
}): Promise<NextResponse> {
const body: Body = await request.json();

if (body.username === 'admin' && body.password === 'admin') {
const token = await new SignJWT({
username: body.username,
})
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('30s')
.sign(getJwtSecretKey());

const response = NextResponse.json(
{ success: true },
{ status: 200, headers: { 'content-type': 'application/json' } }
);

response.cookies.set({
name: 'token',
value: token,
path: '/',
});

return response;
}

return NextResponse.json({ success: false });
}
9 changes: 9 additions & 0 deletions livekit-frontend/src/app/protected/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { NextPage } from 'next';

const AuthyPage: NextPage = () => (
<div>
<h1>Hi, I am a protected page</h1>
</div>
);

export default AuthyPage;
19 changes: 19 additions & 0 deletions livekit-frontend/src/hooks/useAuth/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use client';
import React from 'react';
import Cookies from 'universal-cookie';
import { verifyJwtToken } from '@/lib/auth';

export function useAuth() {
const [auth, setAuth] = React.useState(null);

const getVerifiedtoken = async () => {
const cookies = new Cookies();
const token = cookies.get('token') ?? null;
const verifiedToken = await verifyJwtToken(token);
setAuth(verifiedToken);
};
React.useEffect(() => {
getVerifiedtoken();
}, []);
return auth;
}
20 changes: 20 additions & 0 deletions livekit-frontend/src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { jwtVerify, JWTVerifyResult } from 'jose';

export function getJwtSecretKey(): Uint8Array {
const secret = process.env.NEXT_PUBLIC_JWT_SECRET_KEY;

if (!secret) {
throw new Error('JWT Secret key is not matched');
}

return new TextEncoder().encode(secret);
}

export async function verifyJwtToken(token: string): Promise<any | null> {
try {
const { payload }: JWTVerifyResult = await jwtVerify(token, getJwtSecretKey());
return payload;
} catch (error) {
return null;
}
}
34 changes: 34 additions & 0 deletions livekit-frontend/src/middleware.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { verifyJwtToken } from '@/lib/auth';

const AUTH_PAGES = ['/login'];

const isAuthPages = (url: string) => AUTH_PAGES.some((page) => page.startsWith(url));

export async function middleware(request: { url: any; nextUrl: any; cookies: any }) {
const { url, nextUrl, cookies } = request;
const { value: token } = cookies.get('token') ?? { value: null };
const hasVerifiedToken = token && (await verifyJwtToken(token));
const isAuthPageRequested = isAuthPages(nextUrl.pathname);

if (isAuthPageRequested) {
if (!hasVerifiedToken) {
const response = NextResponse.next();
response.cookies.delete('token');
return response;
}
const response = NextResponse.redirect(new URL(`/`, url));
return response;
}

if (!hasVerifiedToken) {
const searchParams = new URLSearchParams(nextUrl.searchParams);
searchParams.set('next', nextUrl.pathname);
const response = NextResponse.redirect(new URL(`/login?${searchParams}`, url));
response.cookies.delete('token');
return response;
}

return NextResponse.next();
}
export const config = { matcher: ['/login', '/protected/:path*'] };
23 changes: 23 additions & 0 deletions livekit-frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,11 @@
dependencies:
"@types/estree" "*"

"@types/cookie@^0.6.0":
version "0.6.0"
resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.6.0.tgz#eac397f28bf1d6ae0ae081363eca2f425bedf0d5"
integrity sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==

"@types/debug@^4.0.0":
version "4.1.12"
resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.12.tgz#a155f21690871953410df4b6b6f53187f0500917"
Expand Down Expand Up @@ -890,6 +895,11 @@ concat-map@0.0.1:
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==

cookie@^0.6.0:
version "0.6.0"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.6.0.tgz#2798b04b071b0ecbff0dbb62a505a8efa4e19051"
integrity sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==

cross-spawn@^7.0.0, cross-spawn@^7.0.2:
version "7.0.3"
resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"
Expand Down Expand Up @@ -2099,6 +2109,11 @@ joi@^17.5.0:
"@sideway/formula" "^3.0.1"
"@sideway/pinpoint" "^2.0.0"

jose@^5.2.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/jose/-/jose-5.2.0.tgz#d0ffd7f7e31253f633eefb190a930cd14a916995"
integrity sha512-oW3PCnvyrcm1HMvGTzqjxxfnEs9EoFOFWi2HsEGhlFVOXxTE3K9GKWVMFoFw06yPUqwpvEWic1BmtUZBI/tIjw==

"js-tokens@^3.0.0 || ^4.0.0":
version "4.0.0"
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
Expand Down Expand Up @@ -4305,6 +4320,14 @@ unist-util-visit@^5.0.0:
unist-util-is "^6.0.0"
unist-util-visit-parents "^6.0.0"

universal-cookie@^7.0.1:
version "7.0.1"
resolved "https://registry.yarnpkg.com/universal-cookie/-/universal-cookie-7.0.1.tgz#14b7bc3d363836168f7102451ed4881bccd9e849"
integrity sha512-6OuX9xELF6dsVJeADJAYNDOxQf/NR3Na5bGCRd+hkysMDkSt79jJ4tdv5OBe+ZgAks3ExHBdCXkD2SjqLyK59w==
dependencies:
"@types/cookie" "^0.6.0"
cookie "^0.6.0"

update-browserslist-db@^1.0.13:
version "1.0.13"
resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz#3c5e4f5c083661bd38ef64b6328c26ed6c8248c4"
Expand Down