Skip to content

Commit

Permalink
Refactor auth (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
mpapenbr authored and mpapenbr committed Apr 2, 2022
1 parent ca69219 commit 3d237e7
Show file tree
Hide file tree
Showing 10 changed files with 446 additions and 508 deletions.
2 changes: 1 addition & 1 deletion .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#REACT_APP_BASE_URL=http://localhost:8082/irsdk
REACT_APP_BASE_URL=http://host.docker.internal:8080
REACT_APP_AUTH_URL=https://auth-test.juelps.de/auth
REACT_APP_AUTH_REALM=iracing-tools
REACT_APP_AUTH_REALM=iracing-tools-test
REACT_APP_AUTH_CLIENT=login-web

#REACT_APP_MY_REDIRECT_URL=
Expand Down
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"antd": "^4.19.4",
"array-move": "^4.0.0",
"classnames": "^2.2.6",
"connected-react-router": "^6.8.0",
"copy-to-clipboard": "^3.3.1",
"history": "^5.3.0",
"immutability-helper": "^3.1.1",
Expand All @@ -22,9 +21,9 @@
"react-dnd-html5-backend": "^15.1.2",
"react-dom": "^17.0.2",
"react-highlight-words": "^0.17.0",
"react-redux": "^7.2.6",
"react-router": "^5.1.2",
"react-router-dom": "^5.2.0",
"react-redux": "^7.2.7",
"react-router": "^6.3.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.0",
"react-sortable-hoc": "^2.0.0",
"recoil": "^0.6.1",
Expand All @@ -51,7 +50,6 @@
"@types/react-dom": "^17.0.14",
"@types/react-highlight-words": "^0.16.1",
"@types/react-redux": "^7.1.23",
"@types/react-router-dom": "^5.1.5",
"@types/sprintf-js": "^1.1.2",
"@types/uuid": "^8.3.0",
"redux-saga-test-plan": "^4.0.4"
Expand Down
40 changes: 14 additions & 26 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { ReactKeycloakProvider } from "@react-keycloak/web";
import "antd/dist/antd.css";
import { ConnectedRouter } from "connected-react-router";
import { History } from "history";
import React from "react";
import { Provider } from "react-redux";
import { Store } from "redux";
import "./App.css";
import AppHeader from "./components/AppHeader";
import keycloak from "./keycloak";
import { AppRouter } from "./routes";
import { AuthProvider } from "./routes/auth";
import { ApplicationState } from "./stores";

interface AppProps {
Expand All @@ -17,33 +15,23 @@ interface AppProps {
}

const App: React.FC<AppProps> = ({ store, history }) => {
const eventLogger = (event: unknown, error: unknown) => {
console.log("onKeycloakEvent", event, error);
};

const tokenLogger = (tokens: unknown) => {
console.log("onKeycloakTokens", tokens);
};

return (
<ReactKeycloakProvider onEvent={eventLogger} onTokens={tokenLogger} authClient={keycloak}>
<Provider store={store}>
<ConnectedRouter history={history}>
<div className="App">
{/* <Login /> */}
{/* <DevContainer /> */}
<AppHeader />
{/* <TabContainer /> */}
{/* <Switch>
<Provider store={store}>
<div className="App">
{/* <Login /> */}
{/* <DevContainer /> */}
<AuthProvider>
<AppHeader />
{/* <TabContainer /> */}
{/* <Switch>
<Route path="/" exact={true} component={TabContainer} />
<Route path="/login" component={SocialLogin} />
</Switch> */}
<AppRouter />
{/* <RaceContainer /> */}
</div>
</ConnectedRouter>
</Provider>
</ReactKeycloakProvider>
<AppRouter />
</AuthProvider>
{/* <RaceContainer /> */}
</div>
</Provider>
);
};

Expand Down
27 changes: 25 additions & 2 deletions src/components/user/userInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { LogoutOutlined, UserOutlined } from "@ant-design/icons";
import { useKeycloak } from "@react-keycloak/web";
import { Button, Dropdown, Menu } from "antd";
import React, { useCallback } from "react";
import { useAuth } from "../../routes/auth";

interface IStateProps {}
interface IDispatchProps {}
Expand All @@ -12,7 +13,30 @@ interface MyTokenInfo {
name: string;
preferred_username: string;
}
const UserInfo: React.FC<MyProps> = (props: MyProps) => {

const UserInfo: React.FC<{}> = () => {
const { onLogin, onLogout, name } = useAuth();

if (name) {
const menu = (
<Menu>
<Menu.Item onClick={onLogout} key="1" icon={<LogoutOutlined />}>
Logout
</Menu.Item>
</Menu>
);

return (
<Dropdown.Button icon={<UserOutlined />} overlay={menu}>
{name}
</Dropdown.Button>
);
}
return <Button onClick={onLogin}>Login</Button>;
};
export default UserInfo;

const UserInfoOld: React.FC<MyProps> = (props: MyProps) => {
const { keycloak } = useKeycloak();
const login = useCallback(() => {
keycloak?.login();
Expand All @@ -38,4 +62,3 @@ const UserInfo: React.FC<MyProps> = (props: MyProps) => {
}
return <Button onClick={login}>Login</Button>;
};
export default UserInfo;
37 changes: 17 additions & 20 deletions src/configureStore.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
import {Store, createStore, applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga'


// If you use react-router, don't forget to pass in your history type.
import { History } from "history";
import { applyMiddleware, createStore, Store } from "redux";
// `react-router-redux` is deprecated, so we use `connected-react-router`.
// This provides a Redux middleware which connects to our `react-router` instance.
import { routerMiddleware } from 'connected-react-router'
// We'll be using Redux Devtools. We can use the `composeWithDevTools()`
// directive so we can pass our middleware along with it
import { composeWithDevTools } from 'redux-devtools-extension'
// If you use react-router, don't forget to pass in your history type.
import { History } from 'history'
import { ApplicationState, createRootReducer, rootSaga } from './stores'
import { composeWithDevTools } from "redux-devtools-extension";
import createSagaMiddleware from "redux-saga";
import { ApplicationState, createRootReducer, rootSaga } from "./stores";

export default function configureStore(history: History, initialState: ApplicationState) : Store<ApplicationState> {
// create the composing function for our middlewares
const composeEnhancers = composeWithDevTools({})
export default function configureStore(history: History, initialState: ApplicationState): Store<ApplicationState> {
// create the composing function for our middlewares
const composeEnhancers = composeWithDevTools({});
// create the redux-saga middleware
const sagaMiddleware = createSagaMiddleware()
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
createRootReducer(history),
initialState,
composeEnhancers(applyMiddleware(routerMiddleware(history), sagaMiddleware))
)
sagaMiddleware.run(rootSaga)
return store
}
createRootReducer(history),
initialState,
composeEnhancers(applyMiddleware(sagaMiddleware))
);
sagaMiddleware.run(rootSaga);
return store;
}
49 changes: 49 additions & 0 deletions src/routes/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { ReactKeycloakProvider } from "@react-keycloak/web";
import React, { useState } from "react";
import keycloak from "../keycloak";
export interface IAuthContext {
name?: string;
preferred_username?: string;
onLogin: () => void;
onLogout: () => void;
}

export const AuthContext = React.createContext(null);
export const useAuth = () => {
return React.useContext(AuthContext);
};

export const AuthProvider = ({ children }) => {
// const { keycloak } = useKeycloak();
const [name, setName] = useState();

const eventLogger = (event: unknown, error: unknown) => {
if (event === "onAuthSuccess") {
setName(keycloak.idTokenParsed.name);
}
};

const tokenLogger = (tokens: unknown) => {
console.log("onKeycloakTokens", tokens);
};

// const handleLogin = useCallback(() => {
// keycloak?.login();
// }, [keycloak]);
// const handleLogout = useCallback(() => keycloak?.logout(), [keycloak]);
const handleLogin = () => {
keycloak.login();
};
const handleLogout = () => keycloak.logout();
const value = {
onLogin: handleLogin,
onLogout: handleLogout,
name: name,
};

return (
<ReactKeycloakProvider onEvent={eventLogger} onTokens={tokenLogger} authClient={keycloak}>
<AuthContext.Provider value={value}>{children}</AuthContext.Provider>
</ReactKeycloakProvider>
);
};
46 changes: 36 additions & 10 deletions src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { useKeycloak } from "@react-keycloak/web";
import * as React from "react";
import { BrowserRouter as Router, Redirect, Route } from "react-router-dom";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import TabContainer from "../container/tabContainer";
import External from "../pages/External";
import LoginPage from "../pages/Login";
import { useAuth } from "./auth";
import { PrivateRoute } from "./utils";

const Home = () => {
const { name } = useAuth();
if (!name) return <p>Please use the login button.</p>;
return <TabContainer />;
};
const Unknown = () => {
return <p>NotMatched route</p>;
};

export const AppRouter = () => {
const { initialized } = useKeycloak();

Expand All @@ -14,12 +22,30 @@ export const AppRouter = () => {
}

return (
<Router>
<Redirect from="/" exact={true} to="/home" />
{/* <Route exact={true} path="/" to="/home" /> */}
<PrivateRoute path="/home" component={TabContainer} />
<Route path="/ext" component={External} />
<Route path="/login" component={LoginPage} />
</Router>
<BrowserRouter>
<Routes>
<Route path="" element={<Home />} />

<Route
path="home"
element={
<PrivateRoute>
<TabContainer />
</PrivateRoute>
}
/>
<Route path="*" element={<Unknown />} />
</Routes>
</BrowserRouter>
);

// return (
// <Router>
// <Redirect from="/" exact={true} to="/home" />
// {/* <Route exact={true} path="/" to="/home" /> */}
// <PrivateRoute path="/home" component={TabContainer} />
// <Route path="/ext" component={External} />
// <Route path="/login" component={LoginPage} />
// </Router>
// );
};
38 changes: 9 additions & 29 deletions src/routes/utils.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,12 @@
import { useKeycloak } from "@react-keycloak/web";
import * as React from "react";
import type { RouteProps } from "react-router-dom";
import { Redirect, Route, RouteComponentProps } from "react-router-dom";
import { Navigate } from "react-router";
import { useAuth } from "./auth";

interface PrivateRouteParams extends RouteProps {
component: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>;
}
export const PrivateRoute = ({ children }) => {
const { name } = useAuth();

export function PrivateRoute({ component: Component, ...rest }: PrivateRouteParams) {
// const { keycloak } = useKeycloak<KeycloakInstance>()
const { keycloak } = useKeycloak();
console.log("authenticated: " + keycloak?.authenticated);
console.log({ keycloak });
return (
<Route
{...rest}
render={(props) =>
keycloak?.authenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location },
}}
/>
)
}
/>
);
}
if (!name) {
return <Navigate to="/" replace />;
}
return children;
};
3 changes: 0 additions & 3 deletions src/stores/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { connectRouter, RouterState } from "connected-react-router";
import { History } from "history";
import { combineReducers } from "redux";
import { all, fork } from "redux-saga/effects";
Expand Down Expand Up @@ -27,7 +26,6 @@ export interface ApplicationState {
settings: ISettingsState;
ui: IUiState;
user: IUserState;
router: RouterState;
}

// export interface IMetaActions extends PayloadMetaAction<TypeConstant,IMeta> {}
Expand All @@ -41,7 +39,6 @@ export const createRootReducer = (history: History) =>
settings: settingsReducer,
ui: uiReducer,
user: userReducer,
router: connectRouter(history),
});

export function* rootSaga() {
Expand Down
Loading

0 comments on commit 3d237e7

Please sign in to comment.