Skip to content

Commit

Permalink
Merge branch 'NTGL-be-oidc' of github.com:csesoc/notangles into NTGL-…
Browse files Browse the repository at this point in the history
…be-oidc
  • Loading branch information
Rayahhhmed committed Nov 4, 2023
2 parents d47caf9 + ca9d38f commit cabba4a
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 40 deletions.
25 changes: 24 additions & 1 deletion client/src/components/navbar/Navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Description, Info, Security, Settings as SettingsIcon } from '@mui/icons-material';
import { AppBar, Toolbar, Typography, useMediaQuery, useTheme } from '@mui/material';
import { AppBar, Button, Toolbar, Typography, useMediaQuery, useTheme } from '@mui/material';
import { styled } from '@mui/system';
import React, { useContext, useState } from 'react';

Expand All @@ -12,6 +12,7 @@ import Changelog from './Changelog';
import CustomModal from './CustomModal';
import Privacy from './Privacy';
import Settings from './Settings';
import { User } from '../../interfaces/Users';

const LogoImg = styled('img')`
height: 46px;
Expand Down Expand Up @@ -51,9 +52,22 @@ const Weak = styled('span')`
const Navbar: React.FC = () => {
const [currLogo, setCurrLogo] = useState(notanglesLogo);
const { term, termName, year } = useContext(AppContext);
const userData: User = {};
const [user, setUser] = useState(userData);
const theme = useTheme<ThemeType>();
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

const login = () => {
window.location.replace('http://localhost:3001/api/auth/login');
};
const logout = () => {
window.location.replace('http://localhost:3001/api/auth/logout');
};
// https://stackoverflow.com/a/32108184/1098564
const isEmpty = (obj: Object) => {
return Object.keys(obj).length === 0 && obj.constructor === Object;
};

return (
<NavbarBox>
<StyledNavBar enableColorOnDark position="fixed">
Expand Down Expand Up @@ -82,6 +96,15 @@ const Navbar: React.FC = () => {
content={<Privacy />}
/>
<CustomModal title="Settings" showIcon={<SettingsIcon />} description={'Settings'} content={<Settings />} />
{isEmpty(user) ? (
<Button color="warning" onClick={login}>
Login
</Button>
) : (
<Button color="warning" onClick={logout}>
Logout
</Button>
)}
</Toolbar>
</StyledNavBar>
</NavbarBox>
Expand Down
22 changes: 11 additions & 11 deletions server/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
version: '3.7'
services:
server:
container_name: notangles-server
image: notangles-server
restart: always
build: .
depends_on:
- database.notangles-db
ports:
- '3001:3001'
links:
- database.notangles-db
# server:
# container_name: notangles-server
# image: notangles-server
# restart: always
# build: .
# depends_on:
# - database.notangles-db
# ports:
# - '3001:3001'
# links:
# - database.notangles-db

database.notangles-db:
container_name: notangles-database
Expand Down
1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"google-protobuf": "3.21.2",
"grpc-tools": "1.12.4",
"grpc_tools_node_protoc_ts": "5.3.3",
"http-proxy-middleware": "2.0.6",
"minimist": "1.2.8",
"openid-client": "5.6.1",
"passport": "0.6.0",
Expand Down
63 changes: 62 additions & 1 deletion server/pnpm-lock.yaml

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

56 changes: 33 additions & 23 deletions server/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Controller,
Get,
Logger,
Request,
Res,
UseGuards,
Expand All @@ -10,43 +11,52 @@ import { Response } from 'express';
import { LoginGuard } from './login.guard';
import { Issuer } from 'openid-client';
import { AuthDto } from './dtos';

@Controller()
const REDIRECT_LINK = 'http://localhost:5173/';
@Controller('auth')
export class AuthController {

@UseGuards(LoginGuard)
@Get('/login')
login() {}

@Get('/user')
user(@Request() req) {
return req.user

return req.user;
}

@UseGuards(LoginGuard)
@Get('/callback')
@Get('/callback/csesoc')
loginCallback(@Res() res: Response) {
res.redirect('/');
res.redirect(REDIRECT_LINK);
}

@Get('/logout')
async logout(@Request() req, @Res() res: Response) {
console.log("logout");
const id_token = req.user ? req.user.id_token : undefined;
req.logout();
req.session.destroy(async (error: any) => {
const TrustIssuer = await Issuer.discover(`${process.env.OAUTH2_CLIENT_PROVIDER_OIDC_ISSUER}/.well-known/openid-configuration`);
const end_session_endpoint = TrustIssuer.metadata.end_session_endpoint;
if (end_session_endpoint) {
res.redirect(end_session_endpoint +
'?post_logout_redirect_uri=' + process.env.OAUTH2_CLIENT_REGISTRATION_LOGIN_POST_LOGOUT_REDIRECT_URI +
(id_token ? '&id_token_hint=' + id_token : ''));
} else {
res.redirect('/')
req.logout((err) => {
if (err) {
console.log(err + "omahgod errors");
}
})
req.session.destroy(async (error: any) => {
const TrustIssuer = await Issuer.discover(
`${process.env.OAUTH2_CLIENT_PROVIDER_OIDC_ISSUER}/.well-known/openid-configuration`,
);
const end_session_endpoint = TrustIssuer.metadata.end_session_endpoint;
console.log(id_token);
if (end_session_endpoint) {
res.redirect(
end_session_endpoint +
'?post_logout_redirect_uri=' +
process.env
.OAUTH2_CLIENT_REGISTRATION_LOGIN_POST_LOGOUT_REDIRECT_URI +
(id_token ? '&id_token_hint=' + id_token : ''),
);
} else {
res.redirect(REDIRECT_LINK);
}
});
});

}
}




5 changes: 3 additions & 2 deletions server/src/auth/login.guard.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { ExecutionContext, Injectable, Logger } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LoginGuard extends AuthGuard('oidc') {
async canActivate(context: ExecutionContext) {

const result = (await super.canActivate(context)) as boolean;
const request = context.switchToHttp().getRequest();
await super.logIn(request);
return result;
}
}
}
3 changes: 2 additions & 1 deletion server/src/auth/oidc.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class OidcStrategy extends PassportStrategy(Strategy, 'oidc') {

async validate(tokenset: TokenSet): Promise<any> {
const userinfo: UserinfoResponse = await this.client.userinfo(tokenset);
console.log("test");

try {
const id_token = tokenset.id_token
const access_token = tokenset.access_token
Expand All @@ -43,6 +43,7 @@ export class OidcStrategy extends PassportStrategy(Strategy, 'oidc') {
refresh_token,
userinfo,
}
// console.log(user);
return user;
} catch (err) {
throw new UnauthorizedException();
Expand Down
3 changes: 2 additions & 1 deletion server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ async function bootstrap() {
rolling: true, // keep session alive
cookie: {
maxAge: 30 * 60 * 1000, // session expires in 1hr, refreshed by `rolling: true` option.
httpOnly: true, // so that cookie can't be accessed via client-side script
httpOnly: false, // so that cookie can't be accessed via client-side script
sameSite: true
}
}));
app.use(passport.initialize());
Expand Down

0 comments on commit cabba4a

Please sign in to comment.