feat: add Oauth authentication
parent
4e417266c4
commit
3d149e0d1c
@ -1,3 +1,3 @@
|
||||
|
||||
BASE_URL=/
|
||||
DATABASE_PATH=db.local.json
|
||||
DATABASE_PATH=db.local.json
|
@ -0,0 +1,52 @@
|
||||
import { Router } from 'express';
|
||||
import { AuthorizationCode } from 'simple-oauth2'
|
||||
|
||||
export function setupOauth(r: Router) {
|
||||
const config = {
|
||||
client: {
|
||||
id: process.env.OAUTH_CLIENT_ID ?? '',
|
||||
secret: process.env.OAUTH_CLIENT_SECRET ?? '',
|
||||
},
|
||||
auth: {
|
||||
authorizePath: process.env.OAUTH_AUTH_URL ?? '',
|
||||
tokenHost: process.env.OAUTH_TOKEN_HOST ?? '',
|
||||
tokenPath: process.env.OAUTH_TOKEN_PATH ?? ''
|
||||
},
|
||||
};
|
||||
|
||||
const conf = {
|
||||
redirect_uri: process.env.OAUTH_REDIRECT_URL ?? '',
|
||||
scope: process.env.OAUTH_SCOPES ?? '',
|
||||
}
|
||||
|
||||
const client = new AuthorizationCode(config);
|
||||
|
||||
const authorizationUri = client.authorizeURL({
|
||||
redirect_uri: conf.redirect_uri,
|
||||
scope: conf.scope,
|
||||
state: ''
|
||||
});
|
||||
|
||||
r.get('/redirect', (req, res) => {
|
||||
res.redirect(authorizationUri);
|
||||
});
|
||||
|
||||
// Callback service parsing the authorization token and asking for the access token
|
||||
r.get('/callback', async (req, res) => {
|
||||
const code = req.query.code as string;
|
||||
|
||||
const options = {
|
||||
code,
|
||||
redirect_uri: conf.redirect_uri
|
||||
};
|
||||
|
||||
try {
|
||||
const accessToken = await client.getToken(options);
|
||||
|
||||
return res.status(200).json(accessToken.token);
|
||||
} catch (error) {
|
||||
console.error('Access Token Error', error.message);
|
||||
return res.status(500).redirect(`/error?message=${encodeURIComponent('Autenticazione fallita')}`);
|
||||
}
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue