Commit a96754ca authored by Sébastien DA ROCHA's avatar Sébastien DA ROCHA
Browse files

OIDC Fix email for add/renew user resource & add error logs

parent ee20dcc6
Pipeline #14416 passed with stage
in 9 seconds
......@@ -268,7 +268,6 @@ export class LegacyController {
try {
let userServices;
if (token.authzKey == null) { // is OIDC token
const access_token = await this.tokenService.getAccessToken(token)
userServices = await this.legacyServiceOidc.getUserResources(token);
} else {
userServices = await this.legacyService.getUserResources(token);
......
......@@ -22,6 +22,7 @@ moment.tz.setDefault('Europe/Paris');
import { LegacyService } from './legacy.service'
import { TokenService } from './token.service';
@Injectable()
export class LegacyServiceOIDC extends LegacyService {
......@@ -41,7 +42,7 @@ export class LegacyServiceOIDC extends LegacyService {
this.logger.log(' [*] user', email);
if(email) {
var tokenInfos= await this.tokenService.getTokenInfos(email);
var tokenInfos = await this.tokenService.getTokenInfos(email);
let url=`${this.conf.legacyAuthOidcUrl}/add_user/`;
this.logger.log('url ', url);
......@@ -56,7 +57,7 @@ export class LegacyServiceOIDC extends LegacyService {
let token_data = jwt.decode(tokenInfos.access_token);
// Get the list of the accessible services by the user
this.logger.log(`OIDC user account validation for : ${token_data['http://wso2.org/claims/emailaddress']}`, `${LegacyServiceOIDC.name} - ${this.createAccount.name}`);
this.logger.log(`OIDC user account validation for : ${token_data[TokenService.EMAIL]}`, `${LegacyServiceOIDC.name} - ${this.createAccount.name}`);
let res = await request.post(options).catch((error) => {
this.logger.error(`Couldn\'t create user (socle answer): ${error}`, `${LegacyServiceOIDC.name} - ${this.createAccount.name}`);
......@@ -94,6 +95,7 @@ export class LegacyServiceOIDC extends LegacyService {
throw new BadRequestException('tokenNotFound');
}
} catch (err) {
this.logger.error(err, `${LegacyServiceOIDC.name} - ${this.createAccount.name}`);
handleError(err, new InternalServerErrorException('Something went wrong.'));
}
}
......@@ -135,6 +137,7 @@ export class LegacyServiceOIDC extends LegacyService {
throw new BadRequestException(res.message);
}
} catch (err) {
this.logger.error(err, `${LegacyServiceOIDC.name} - ${this.getUserResources.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -147,6 +150,7 @@ export class LegacyServiceOIDC extends LegacyService {
this.logger.log('Entering function', `${LegacyServiceOIDC.name} - ${this.addUserResource.name}`);
try {
let token_data = jwt.decode(access_token);
// Get the list of datasets
const datasets = await this.getRestrictedAccessDatasets();
// Get the list of services
......@@ -169,7 +173,7 @@ export class LegacyServiceOIDC extends LegacyService {
};
let res = await request(options).form(
{
username: token.email,
username: token_data[TokenService.USER_NAME],
service_id: accessRequest.id,
modes: accessRequest.servicesId.toString(),
},
......@@ -209,16 +213,16 @@ export class LegacyServiceOIDC extends LegacyService {
// Building email temaplates
const adminEmail = buildDataAccessRequestAdminEmail({
datetime,
firstName: token.firstName,
lastName: token.lastName,
username: token.username,
firstName: token_data[TokenService.FIRST_NAME],
lastName: token_data[TokenService.LAST_NAME],
username: token_data[TokenService.USER_NAME],
datasets: formatedDatasets,
imageHost: this.conf.imageHost,
});
const userEmail = buildDataAccessRequestUserEmail({
datetime,
firstName: token.firstName,
firstName: token_data[TokenService.FIRST_NAME],
datasets: formatedDatasets,
imageHost: this.conf.imageHost,
});
......@@ -232,13 +236,14 @@ export class LegacyServiceOIDC extends LegacyService {
}),
this.sendEmail({
html: userEmail,
to: [token.email],
to: [token_data[TokenService.EMAIL]],
subject: 'Demande d’accès aux données',
}),
]);
return { successfullyRequested: accessSuccessfullyRequested, unsuccessfullyRequested: accessUnsuccessfullyRequested };
} catch (err) {
this.logger.error(err, `${LegacyServiceOIDC.name} - ${this.addUserResource.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -252,6 +257,7 @@ export class LegacyServiceOIDC extends LegacyService {
try {
// Get the list of user access
const access_token = await this.tokenService.getAccessToken(token);
let token_data = jwt.decode(access_token);
const userAccess = await this.getUserResources(token);
// Get the list of datasets
const datasets = await this.getRestrictedAccessDatasets();
......@@ -301,16 +307,16 @@ export class LegacyServiceOIDC extends LegacyService {
// Building email templates
const adminEmail = buildRenewDataAccessRequestAdminEmail({
firstName: token.firstName,
lastName: token.lastName,
username: token.username,
firstName: token_data[TokenService.FIRST_NAME],
lastName: token_data[TokenService.LAST_NAME],
username: token_data[TokenService.USER_NAME],
datasets: formatedDatasets,
datetime: moment().format('DD/MM/YYYY à HH:mm'),
imageHost: this.conf.imageHost,
});
const userEmail = buildRenewDataAccessRequestUserEmail({
firstName: token.firstName,
firstName: token_data[TokenService.FIRST_NAME],
datasets: formatedDatasets,
datetime: moment().format('DD/MM/YYYY à HH:mm'),
imageHost: this.conf.imageHost,
......@@ -335,6 +341,7 @@ export class LegacyServiceOIDC extends LegacyService {
unsuccessfullyRenewalRequested: accessRenewalUnsuccessfullyRequested,
};
} catch (err) {
this.logger.error(err, `${LegacyServiceOIDC.name} - ${this.renewUserResource.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -428,6 +435,7 @@ export class LegacyServiceOIDC extends LegacyService {
return { successfullyDeleted: datasetsSuccessfullyDeleted, unsuccessfullyDeleted: datasetsUnsuccessfullyDeleted };
} catch (err) {
this.logger.error(err, `${LegacyServiceOIDC.name} - ${this.deleteUserResource.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......
......@@ -59,6 +59,7 @@ export class LegacyService {
throw new BadRequestException(res.message);
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.getUser.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -90,6 +91,7 @@ export class LegacyService {
throw new BadRequestException(res.message);
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.getUserInfo.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -143,6 +145,7 @@ export class LegacyService {
}
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.updateUserPassword.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -184,6 +187,7 @@ export class LegacyService {
return;
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.createUser.name}`);
handleError(err, new InternalServerErrorException('Something went wrong.'));
}
}
......@@ -264,6 +268,7 @@ export class LegacyService {
}
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.updateUserInfo.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -378,6 +383,7 @@ export class LegacyService {
throw new InternalServerErrorException('Couldn\'t get the different modes');
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.getServices.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -421,6 +427,7 @@ export class LegacyService {
throw new BadRequestException(res.message);
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.getUserResources.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -459,6 +466,7 @@ export class LegacyService {
throw new InternalServerErrorException('Couldn\'t get the different restricted services.');
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.getRestrictedAccessDatasets.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -561,6 +569,7 @@ export class LegacyService {
return { successfullyRequested: accessSuccessfullyRequested, unsuccessfullyRequested: accessUnsuccessfullyRequested };
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.addUserResource.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -665,6 +674,7 @@ export class LegacyService {
unsuccessfullyRenewalRequested: accessRenewalUnsuccessfullyRequested,
};
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.renewUserResource.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -766,6 +776,7 @@ export class LegacyService {
return { successfullyDeleted: datasetsSuccessfullyDeleted, unsuccessfullyDeleted: datasetsUnsuccessfullyDeleted };
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.deleteUserResource.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......@@ -804,6 +815,7 @@ export class LegacyService {
throw new BadRequestException(res.message);
}
} catch (err) {
this.logger.error(err, `${LegacyService.name} - ${this.deleteUserAccount.name}`);
if (err instanceof HttpException) {
throw new HttpException(err.message, err.getStatus());
} else {
......
......@@ -14,6 +14,11 @@ interface TokenInfos{
@Injectable()
export class TokenService {
public static EMAIL = 'http://wso2.org/claims/emailaddress';
public static USER_NAME = 'http://wso2.org/claims/emailaddress';
public static FIRST_NAME= 'http://wso2.org/claims/givenname';
public static LAST_NAME= 'http://wso2.org/claims/lastname';
conf: any = {};
private logger: Logger;
private redis:Redis;
......
from datetime import datetime
import json
import logging
import requests
from decouple import config
......@@ -17,6 +19,10 @@ def send_request(endpoint, method="GET", data=None):
# Store OIDC token in Redis
oidc_token = jwt.decode(TOKEN, options={"verify_signature": False}, algorithms=["RS256"])
exp = oidc_token["exp"]
logging.debug("Token expiration date: %s (%s)", datetime.fromtimestamp(exp), exp)
email = oidc_token["http://wso2.org/claims/emailaddress"]
tokens = json.dumps({"access_token": TOKEN})
......@@ -77,24 +83,25 @@ def test_user_resources():
resp_json = resp.json()
assert resp_json == [
{
'datasetId': 3,
'datasetName': 'Rdata',
'geonetUuid': None,
'datasetId': 54,
'datasetName': 'Rdata / État du trafic temps réel',
'geonetUuid': 'ea3d6ea9-0878-4ee3-a8cc-1601b919754b',
'serviceName': 'wms',
'status': 'opened',
'urlPattern': 'rdata',
'urlPattern': 'rdata/pvo_patrimoine_voirie.pvotrafic',
'validUntil': 'Tue Dec 31 2030 00:00:00 GMT+0000',
}
]
def test_user_addUserResource():
# Lancer le service mail avant
endpoint = "user/resources/add"
data_input = [
{
"id": 55,
"id": 54,
"servicesId": [
1,
2,
......@@ -110,17 +117,20 @@ def test_user_addUserResource():
resp_json = resp.json()
assert {
'successfullyRequested': ['Rdata / Confluence - Etat du trafic temps réel (wms,wfs,files)'],
'successfullyRequested': ['Rdata / État du trafic temps réel (wms,wfs,files)'],
'unsuccessfullyRequested': []
} == resp_json
# Vérifier l'envoie de mail
def test_user_renewUserResource():
# Lancer le service mail avant
endpoint = "user/resources/renew"
data_input = [
{
"id": 55,
"id": 54,
"servicesId": [
1,
2,
......@@ -135,4 +145,59 @@ def test_user_renewUserResource():
assert resp.status_code == 201
resp_json = resp.json()
assert {'successfullyRenewalRequested': [], 'unsuccessfullyRenewalRequested': ['Rdata / Confluence - Etat du trafic temps réel (wms,wfs,files)']} == resp_json
assert {
'successfullyRenewalRequested': ['Rdata / État du trafic temps réel (wms)'],
'unsuccessfullyRenewalRequested': ['Rdata / État du trafic temps réel (wfs,files)']
} == resp_json
# Vérifier l'envoie de mail
def test_services():
endpoint = "services"
resp = send_request(endpoint)
#resp.raise_for_status()
assert resp.status_code == 200
resp_json = resp.json()
assert resp_json == [
{'abstract': 'Service cartographique en mode image', 'id': 1, 'name': 'wms'},
{'abstract': 'service de téléchargement (test GBB)', 'id': 2, 'name': 'wfs'},
{'abstract': 'Accès aux web services JSON', 'id': 3, 'name': 'ws'},
{'abstract': 'Accès aux web services kml', 'id': 4, 'name': 'kml'},
{'abstract': 'Accès aux fichiers plats\r\n', 'id': 5, 'name': 'files'},
{'abstract': 'Services au standard SOS pour la publication de données issues de capteurs.', 'id': 6, 'name': 'sos'},
{'abstract': 'Service datalake en mode navigateur de données', 'id': 7, 'name': 'minio'},
{'abstract': 'Service datalake en mode XML brut', 'id': 8, 'name': 'buckets'},
{'abstract': 'Service de téléchargement sécurisé des données MAJIC', 'id': 9, 'name': 'majic'},
{'abstract': 'géocodage direct et inversé', 'id': 10, 'name': 'geocoding'},
{'abstract': 'Service de tuiles vectorielles au format Protobuff', 'id': 11, 'name': 'mvt'},
{'abstract': 'Accès aux statistiques du dataset', 'id': 12, 'name': 'statistiques'}
]
def test_restrictedAccessDatasets():
endpoint = "services"
resp = send_request(endpoint)
assert resp.status_code == 200
resp_json = resp.json()
print(resp_json)
assert resp_json == [
{'id': 1, 'abstract': 'Service cartographique en mode image', 'name': 'wms'},
{'id': 2, 'abstract': 'service de téléchargement (test GBB)', 'name': 'wfs'},
{'id': 3, 'abstract': 'Accès aux web services JSON', 'name': 'ws'},
{'id': 4, 'abstract': 'Accès aux web services kml', 'name': 'kml'},
{'id': 5, 'abstract': 'Accès aux fichiers plats\r\n', 'name': 'files'},
{'id': 6, 'abstract': 'Services au standard SOS pour la publication de données issues de capteurs.', 'name': 'sos'},
{'id': 7, 'abstract': 'Service datalake en mode navigateur de données', 'name': 'minio'},
{'id': 8, 'abstract': 'Service datalake en mode XML brut', 'name': 'buckets'},
{'id': 9, 'abstract': 'Service de téléchargement sécurisé des données MAJIC', 'name': 'majic'},
{'id': 10, 'abstract': 'géocodage direct et inversé', 'name': 'geocoding'},
{'id': 11, 'abstract': 'Service de tuiles vectorielles au format Protobuff', 'name': 'mvt'},
{'id': 12, 'abstract': 'Accès aux statistiques du dataset', 'name': 'statistiques'}
]
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment