Skip to content

Commit

Permalink
run lint --fix
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikmonsen committed Oct 16, 2024
1 parent 4ae9f29 commit 78bde99
Show file tree
Hide file tree
Showing 12 changed files with 293 additions and 293 deletions.
210 changes: 105 additions & 105 deletions src/app/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,119 +7,119 @@ import {User} from '@/models/UserToken';
import {refresh, signIn, signOut} from '@/services/auth.data';

interface IAuthContext {
authenticated: boolean;
user?: User;
logout?: () => void;
authenticated: boolean;
user?: User;
logout?: () => void;
}

const AuthContext = createContext<IAuthContext>({
authenticated: false,
logout: () => {}
authenticated: false,
logout: () => {}
});

export const AuthProvider = ({children}: { children: React.ReactNode }) => {
const router = useRouter();

const [authenticated, setAuthenticated] = useState<boolean>(false);
const [user, setUser] = useState<User>();
const [intervalId, setIntervalId] = useState<number>();

const handleNotAuthenticated = useCallback(() => {
setAuthenticated(false);
setUser(undefined);
if (intervalId) {
clearInterval(intervalId);
}
let currentUrl = window.location.href;
// The app dislikes being redirected to a sub-path, redirecting to root to avoid issues
currentUrl = currentUrl.replace(/\/hugin.*/, '/hugin');
currentUrl = encodeURIComponent(currentUrl);

window.location.assign(`${keycloakConfig.url}/realms/${keycloakConfig.realm}/protocol/openid-connect/auth` +
const router = useRouter();

const [authenticated, setAuthenticated] = useState<boolean>(false);
const [user, setUser] = useState<User>();
const [intervalId, setIntervalId] = useState<number>();

const handleNotAuthenticated = useCallback(() => {
setAuthenticated(false);
setUser(undefined);
if (intervalId) {
clearInterval(intervalId);
}
let currentUrl = window.location.href;
// The app dislikes being redirected to a sub-path, redirecting to root to avoid issues
currentUrl = currentUrl.replace(/\/hugin.*/, '/hugin');
currentUrl = encodeURIComponent(currentUrl);

window.location.assign(`${keycloakConfig.url}/realms/${keycloakConfig.realm}/protocol/openid-connect/auth` +
`?client_id=${keycloakConfig.clientId}&redirect_uri=${currentUrl}&response_type=code&scope=openid`);
}, [intervalId]);

useEffect(() => {
const codeInParams = new URLSearchParams(window.location.search).get('code');
if (codeInParams) {
const redirectUrl = new URLSearchParams({redirectUrl: trimRedirectUrl(window.location.href)}).toString();
void signIn(codeInParams, redirectUrl).then((token: User) => {
handleIsAuthenticated(token);
router.push('/');
}).catch((e: Error) => {
console.error('Failed to sign in: ', e.message);
handleNotAuthenticated();
});
} else if (user) {
if (user.expires && new Date(user.expires) > new Date()) {
handleIsAuthenticated(user);
}
} else {
}, [intervalId]);

useEffect(() => {
const codeInParams = new URLSearchParams(window.location.search).get('code');
if (codeInParams) {
const redirectUrl = new URLSearchParams({redirectUrl: trimRedirectUrl(window.location.href)}).toString();
void signIn(codeInParams, redirectUrl).then((token: User) => {
handleIsAuthenticated(token);
router.push('/');
}).catch((e: Error) => {
console.error('Failed to sign in: ', e.message);
handleNotAuthenticated();
});
} else if (user) {
if (user.expires && new Date(user.expires) > new Date()) {
handleIsAuthenticated(user);
}
} else {
handleNotAuthenticated();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const handleIsAuthenticated = (newUser: User) => {
if (newUser) {
setUser(newUser);
setAuthenticated(true);
}
};

const refreshToken = useCallback(async () => {
return refresh();
}, []);

const setIntervalToRefreshAccessToken = useCallback(async () => {
if (user?.expires && !intervalId) {
const expiryTime = new Date(user?.expires).getTime() - Date.now();
if (expiryTime < 1000 * 60 * 4.75) {
await refreshToken();
}
setIntervalId(window.setInterval(() => {
void refreshToken().then((newUser: User) => {
handleIsAuthenticated(newUser);
})
.catch((e: Error) => {
console.error('Failed to refresh token: ', e.message);
handleNotAuthenticated();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const handleIsAuthenticated = (newUser: User) => {
if (newUser) {
setUser(newUser);
setAuthenticated(true);
}
};

const refreshToken = useCallback(async () => {
return refresh();
}, []);

const setIntervalToRefreshAccessToken = useCallback(async () => {
if (user?.expires && !intervalId) {
const expiryTime = new Date(user?.expires).getTime() - Date.now();
if (expiryTime < 1000 * 60 * 4.75) {
await refreshToken();
}
setIntervalId(window.setInterval(() => {
void refreshToken().then((newUser: User) => {
handleIsAuthenticated(newUser);
})
.catch((e: Error) => {
console.error('Failed to refresh token: ', e.message);
handleNotAuthenticated();
});
}, (1000 * 60 * 4.75))); // Refresh every 4.75 minutes (fifteen seconds before expiry)
}
}, [handleNotAuthenticated, intervalId, refreshToken, user?.expires]);

useEffect(() => {
void setIntervalToRefreshAccessToken();
}, [setIntervalToRefreshAccessToken]);

const trimRedirectUrl= (returnUrl: string): string => {
returnUrl = returnUrl.split('?')[0];
if (returnUrl.at(-1) === '/') {
returnUrl = returnUrl.slice(0, -1);
}
return returnUrl;
};

const logout = async () => {
await signOut()
.then(() => {
handleNotAuthenticated();
});
};

return (
<AuthContext.Provider
value={{
authenticated,
user,
// eslint-disable-next-line @typescript-eslint/no-misused-promises
logout
}}
>
{children}
</AuthContext.Provider>
);
});
}, (1000 * 60 * 4.75))); // Refresh every 4.75 minutes (fifteen seconds before expiry)
}
}, [handleNotAuthenticated, intervalId, refreshToken, user?.expires]);

useEffect(() => {
void setIntervalToRefreshAccessToken();
}, [setIntervalToRefreshAccessToken]);

const trimRedirectUrl= (returnUrl: string): string => {
returnUrl = returnUrl.split('?')[0];
if (returnUrl.at(-1) === '/') {
returnUrl = returnUrl.slice(0, -1);
}
return returnUrl;
};

const logout = async () => {
await signOut()
.then(() => {
handleNotAuthenticated();
});
};

return (
<AuthContext.Provider
value={{
authenticated,
user,
// eslint-disable-next-line @typescript-eslint/no-misused-promises
logout
}}
>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => useContext<IAuthContext>(AuthContext);
36 changes: 18 additions & 18 deletions src/app/api/auth/refresh/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,27 @@ import {getRefreshToken, setUserCookie} from '@/utils/cookieUtils';

// POST api/auth/refresh
export async function POST(): Promise<NextResponse> {
const refreshToken = getRefreshToken();
if (!refreshToken) {
return NextResponse.json({error: 'No user token found'}, {status: 401});
}
const refreshToken = getRefreshToken();
if (!refreshToken) {
return NextResponse.json({error: 'No user token found'}, {status: 401});
}

const data = await fetch(`${process.env.AUTH_API_PATH}/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: refreshToken
});
const data = await fetch(`${process.env.AUTH_API_PATH}/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: refreshToken
});

const newToken = await data.json() as UserToken;
const newToken = await data.json() as UserToken;

if (!newToken || !newToken.name || !newToken.expires) {
return NextResponse.json({error: 'Failed to refresh token'}, {status: 500});
}
if (!newToken || !newToken.name || !newToken.expires) {
return NextResponse.json({error: 'Failed to refresh token'}, {status: 500});
}

setUserCookie(newToken);
setUserCookie(newToken);

const user: User = {name: newToken.name, expires: newToken.expires};
return NextResponse.json(user, {status: 200});
const user: User = {name: newToken.name, expires: newToken.expires};
return NextResponse.json(user, {status: 200});
}
54 changes: 27 additions & 27 deletions src/app/api/auth/signin/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,40 @@ import {ProblemDetail} from '@/models/ProblemDetail';
import {setUserCookie} from '@/utils/cookieUtils';

interface LoginRequest {
code: string;
redirectUrl: string;
code: string;
redirectUrl: string;
}

// POST api/auth/signin
export async function POST(req: NextRequest): Promise<NextResponse> {
const {code, redirectUrl} = await req.json() as LoginRequest;
const data = await fetch(`${process.env.AUTH_API_PATH}/login?${redirectUrl}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: code
})
.then(async response => {
if (!response.ok) {
const problemDetail = await response.json() as ProblemDetail;
return NextResponse.json({error: problemDetail.detail}, {status: problemDetail.status});
}
return response;
});
const {code, redirectUrl} = await req.json() as LoginRequest;
const data = await fetch(`${process.env.AUTH_API_PATH}/login?${redirectUrl}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: code
})
.then(async response => {
if (!response.ok) {
const problemDetail = await response.json() as ProblemDetail;
return NextResponse.json({error: problemDetail.detail}, {status: problemDetail.status});
}
return response;
});

if (data instanceof NextResponse) {
return data;
}
if (data instanceof NextResponse) {
return data;
}

const userToken = await data.json() as UserToken;
const userToken = await data.json() as UserToken;

if (!userToken || !userToken.name || !userToken.expires) {
return NextResponse.json({error: 'Failed to authenticate'}, {status: 500});
}
if (!userToken || !userToken.name || !userToken.expires) {
return NextResponse.json({error: 'Failed to authenticate'}, {status: 500});
}

setUserCookie(userToken);
setUserCookie(userToken);

const user: User = {name: userToken.name, expires: userToken.expires};
return NextResponse.json(user, {status: 200});
const user: User = {name: userToken.name, expires: userToken.expires};
return NextResponse.json(user, {status: 200});
}
38 changes: 19 additions & 19 deletions src/app/api/auth/signout/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@ import {deleteUserToken, getRefreshToken} from '@/utils/cookieUtils';

// POST api/auth/signout
export async function POST(): Promise<NextResponse> {
const refreshToken = getRefreshToken();
if (!refreshToken) {
return NextResponse.json({error: 'No user token found'}, {status: 401});
}
const refreshToken = getRefreshToken();
if (!refreshToken) {
return NextResponse.json({error: 'No user token found'}, {status: 401});
}

return await fetch(`${process.env.AUTH_API_PATH}/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: refreshToken
}).then(res => {
if (!res.ok) {
return NextResponse.json({error: 'Failed to logout'}, {status: res.status});
}
deleteUserToken();
return NextResponse.json({message: 'Logged out successfully'}, {status: 200});
}).catch((error: Error) => {
return NextResponse.json({error: `Failed to logout: ${error.message}`}, {status: 500});
});
return await fetch(`${process.env.AUTH_API_PATH}/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: refreshToken
}).then(res => {
if (!res.ok) {
return NextResponse.json({error: 'Failed to logout'}, {status: res.status});
}
deleteUserToken();
return NextResponse.json({message: 'Logged out successfully'}, {status: 200});
}).catch((error: Error) => {
return NextResponse.json({error: `Failed to logout: ${error.message}`}, {status: 500});
});
}
Loading

0 comments on commit 78bde99

Please sign in to comment.