Skip to content

Commit

Permalink
fix: changes due to keycloak new release
Browse files Browse the repository at this point in the history
  • Loading branch information
gioppoluca committed Jun 24, 2024
1 parent 6024f15 commit 1a0681f
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,19 @@ export class KeycloakIdentityTenantManagerController {
): Promise<any> {
//Preconditions
let data
console.log("in the getAdminToken")
console.log(realm)
console.log(process.env.WSO2_IDENTITY_ADMIN_USER)
console.log(process.env.MICADO_KC_REALM_ADMIN_PASSWORD)
switch (realm) {
case 'migrant':
console.log('migrant');

data= {
username: process.env.WSO2_IDENTITY_ADMIN_USER,
password: process.env.WSO2_IDENTITY_ADMIN_PWD,
client_id:'migrant-realm',
client_secret:process.env.MIGRANT_REALM_CLIENT_SECRET,
username: "migrant-admin",
password: process.env.MICADO_KC_REALM_ADMIN_PASSWORD,
client_id:'migrant_app',
client_secret: process.env.MIGRANT_REALM_CLIENT_SECRET,
grant_type:"password",
}
console.log(data)
Expand All @@ -42,21 +46,21 @@ export class KeycloakIdentityTenantManagerController {
console.log('pa');

data= {
username: process.env.WSO2_IDENTITY_ADMIN_USER,
password: process.env.WSO2_IDENTITY_ADMIN_PWD,
client_id:'pa-realm',
client_secret:process.env.PA_REALM_CLIENT_SECRET,
username: "mimgrant-admin",
password: process.env.MICADO_KC_REALM_ADMIN_PASSWORD,
client_id:'pa_app',
client_secret: process.env.PA_REALM_CLIENT_SECRET,
grant_type:"password",
}
break;
case 'ngo':
console.log('Ngo realm chosen');

data= {
username: process.env.WSO2_IDENTITY_ADMIN_USER,
password: process.env.WSO2_IDENTITY_ADMIN_PWD,
client_id:'ngo-realm',
client_secret:process.env.NGO_REALM_CLIENT_SECRET,
username: "ngo-admin",
password: process.env.MICADO_KC_REALM_ADMIN_PASSWORD,
client_id:'ngo_app',
client_secret: process.env.NGO_REALM_CLIENT_SECRET,
grant_type:"password",
}
break;
Expand All @@ -68,11 +72,13 @@ export class KeycloakIdentityTenantManagerController {
console.log(data)
let manager = await this.keycloakService.getManager(
hostname ,
realm,
querystring.stringify(data)
)
console.log(manager)
let token = JSON.parse(manager).access_token
console.log(token)
return token
return Promise.resolve(token)
}


Expand Down Expand Up @@ -365,6 +371,7 @@ export class KeycloakIdentityTenantManagerController {

}

// TODO here there is still old values
@post('/createGroup')
@authenticate('micado')
async createGroup(
Expand All @@ -381,6 +388,7 @@ export class KeycloakIdentityTenantManagerController {
console.log(data)
let manager = await this.keycloakService.getManager(
hostname ,
realm,
querystring.stringify(data)
)
let token = JSON.parse(manager).access_token
Expand Down Expand Up @@ -458,7 +466,9 @@ export class KeycloakIdentityTenantManagerController {
): Promise<any> {
//Preconditions
let token = await this.getAdminToken(realm)

console.log("updateUser:"+token)
console.log("updateUser:"+hostname)
console.log("updateUser:"+realm)
return this.keycloakService.updateUser(
userid,
firstName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,14 @@ export class SurveyController {
@param.query.string('userid') userid = '',
): Promise<any> {
let surveys = await this.surveyRepository.dataSource.execute('select * from survey where survey.active = true and survey.destination_app =' + destinationApp + ' and survey.expiry_date >= current_date')
console.log("the surveys:" + surveys)
if (surveys.length == 0) {
console.log("No surveys available")
return null
}
if (userid != '') {
let completed_survey = await this.surveyAnswersRepository.dataSource.execute('select * from survey_answers where EXISTS(SELECT * from survey_answers WHERE id_user =\'' + userid + '\')')
console.log(completed_survey)
console.log("the completed survey:" + completed_survey)
if (completed_survey.length > 0) {
console.log("This survey was already answered")
return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export class UserController {
@param.path.string('id') id: string,
@param.filter(User, {exclude: 'where'}) filter?: FilterExcludingWhere<User>
): Promise<User> {
console.log('id' + id)
return this.userRepository.findById(id, filter);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
{
"template": {
"method": "POST",
"url": "https://{baseurl}/auth/realms/master/protocol/openid-connect/token",
"url": "https://{baseurl}/realms/{realm}/protocol/openid-connect/token",
"headers": {
"accept": "*/*",
"content-type": "application/x-www-form-urlencoded"
Expand All @@ -25,6 +25,7 @@
"functions": {
"getManager": [
"baseurl",
"realm",
"payload"
]
}
Expand Down Expand Up @@ -152,7 +153,7 @@
{
"template": {
"method": "PUT",
"url": "https://{baseurl}/auth/admin/realms/{realm}/users/{userid}",
"url": "https://{baseurl}/admin/realms/{realm}/users/{userid}",
"headers": {
"accept": "*/*",
"content-type": "application/json",
Expand Down
19 changes: 13 additions & 6 deletions application/micado-backend/src/modules/micado-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,35 +32,42 @@ export class MicadoAuthenticationStrategy implements AuthenticationStrategy {

const tokenparts: any = request.headers.authorization?.split(' ')
let decoded: any = jwt_decode(tokenparts[1])

console.log(tokenparts)
console.log(tokenparts[1])

var iss = decoded.iss

var iss_array = iss.split("/");
var realm = iss_array[iss_array.length - 1]

console.log(realm)
console.log('prima di keycloak')
console.log('https://' + process.env.IDENTITY_HOSTNAME + '/realms/' + realm + '/protocol/openid-connect/userinfo')

const axios = require('axios').default;
return axios({
url: 'https://' + process.env.IDENTITY_HOSTNAME + '/auth/realms/' + realm + '/protocol/openid-connect/userinfo',
url: 'https://' + process.env.IDENTITY_HOSTNAME + '/realms/' + realm + '/protocol/openid-connect/userinfo',
method: "get",
headers: { 'Authorization': 'Bearer ' + tokenparts[1] },
httpsAgent: new https.Agent({ rejectUnauthorized: false })

}
).then(function (response: any) {
if (response.status != 200) {
return undefined
console.log('error in response')
console.log(response)
return Promise.reject(undefined)
//return undefined
}
else {
let uu = new AuthUser({ username: 'pippo' })
return uu;
return Promise.resolve(uu);
}
})
.catch(function (error: any) {
console.log('error in catch')
console.log(error);
return undefined
return Promise.reject(undefined)
//return undefined

})
}
Expand Down
89 changes: 48 additions & 41 deletions application/micado-backend/src/sequence.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// ---------- ADD IMPORTS -------------
import { AuthenticateFn, AuthenticationBindings, AUTHENTICATION_STRATEGY_NOT_FOUND, USER_PROFILE_NOT_FOUND} from '@loopback/authentication';
import { AuthenticateFn, AuthenticationBindings, AUTHENTICATION_STRATEGY_NOT_FOUND, USER_PROFILE_NOT_FOUND } from '@loopback/authentication';
//import {AuthenticateFn, AuthenticationBindings} from 'loopback4-authentication';
/*
import {
Expand All @@ -8,8 +8,8 @@ import {
AuthorizeFn,
} from 'loopback4-authorization';
*/
import {AuthUser} from './models';
import {inject} from '@loopback/context';
import { AuthUser } from './models';
import { inject } from '@loopback/context';
import {
FindRoute,
InvokeMethod,
Expand All @@ -28,62 +28,69 @@ const SequenceActions = RestBindings.SequenceActions;

export class MySequence implements SequenceHandler {
//-----snippet added to try to fix cors----------
@inject(SequenceActions.INVOKE_MIDDLEWARE, {optional: true}) protected invokeMiddleware: InvokeMiddleware = () => false;
//---------end snippet---------
@inject(SequenceActions.INVOKE_MIDDLEWARE, { optional: true }) protected invokeMiddleware: InvokeMiddleware = () => false;
//---------end snippet---------
constructor(
@inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
@inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
@inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
@inject(SequenceActions.SEND) public send: Send,
@inject(SequenceActions.REJECT) public reject: Reject,
@inject(AuthenticationBindings.AUTH_ACTION) protected authenticateRequest: AuthenticateFn,
) {}
) { }

async handle(context: RequestContext) {
try {
const {request, response} = context;
const { request, response } = context;
//response.header('Access-Control-Allow-Origin', '*');
// response.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, access-control-allow-origin');
console.log(request.method)
console.log(request.headers['user-agent'])
console.log(request.headers['content-type'])
// response.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, access-control-allow-origin');
console.log("\nMySequence-handle: - methed " + request.method)
console.log("MySequence-handle - user agent:" + request.headers['user-agent'])
console.log("MySequence-handle - content type:" + request.headers['content-type'])

if(request.headers['user-agent']?.includes('Apache-HttpClient') && !request.headers['content-type']){
console.log("call from e-translation ")
request.headers['content-type']='text/plain'
}
/*if (request.method == 'OPTIONS') {
console.log("I AM IN THE SEQUENCE FOR AN OPTION REQUEST")
response.status(200)
this.send(response, 'ok');
} else {*/
const finished = await this.invokeMiddleware(context);
if (finished) return;
const route = this.findRoute(request);
// ------ ADD SNIPPET ---------
//call authentication action
//console.log(request)
const authUser: any = await this.authenticateRequest(request);
//console.log(authUser)
// ------------- END OF SNIPPET -------------
/*
const authUser: AuthUser = await this.authenticateRequest(
request,
response,
);
*/
console.log('nella sequence')
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
//}
if (request.headers['user-agent']?.includes('Apache-HttpClient') && !request.headers['content-type']) {
console.log("call from e-translation ")
request.headers['content-type'] = 'text/plain'
}
/*if (request.method == 'OPTIONS') {
console.log("I AM IN THE SEQUENCE FOR AN OPTION REQUEST")
response.status(200)
this.send(response, 'ok');
} else {*/
const finished = await this.invokeMiddleware(context);
console.log('nella sequence - finished:'+ finished)
if (finished) return;
const route = this.findRoute(request);
console.log('nella sequence - route:'+ route)
// ------ ADD SNIPPET ---------
//call authentication action
//console.log(request)
const authUser: any = await this.authenticateRequest(request);
console.log('nella sequence - authUser:'+ authUser)
//console.log(authUser)
// ------------- END OF SNIPPET -------------
/*
const authUser: AuthUser = await this.authenticateRequest(
request,
response,
);
*/
console.log('nella sequence')
const args = await this.parseParams(request, route);
console.log("after parseParams")
const result = await this.invoke(route, args);
console.log("after invoke")
console.log('nella sequence - result:'+ result)
this.send(response, result);
//}
} catch (err) {
console.log('nella sequence - err:'+ err)
// ------ ADD SNIPPET ---------
if (
err.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
err.code === USER_PROFILE_NOT_FOUND
) {
Object.assign(err, {statusCode: 401 /* Unauthorized */});
Object.assign(err, { statusCode: 401 /* Unauthorized */ });
}
// ------------- END OF SNIPPET -------------
this.reject(context, err);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export interface KeycloakService {
createGroup(name: String, realm: String, token: String, baseurl:String): Promise<any>;
addToGroup(userId: String, groupId: String, realm: String, token: String, baseurl:String): Promise<any>;
getGroupId(baseurl: String, realm: String, token: String): Promise<any>;
getManager(baseurl: String,payload:any): Promise<any>;
getManager(baseurl: String, realm: String, payload:any): Promise<any>;
getGroupMembers(baseurl: String,realm: String, groupId:String, token:String): Promise<any>;
updateUser(userid:String, firstName: String, lastName:String, email: String, birthdate:String, nationality: String, gender: String, phone_number:String, realm: String, token: String, baseurl: String): Promise<any>;
updateUserPassword(userid:String, password:String, realm: String, token: String, baseurl: String): Promise<any>;
Expand Down

0 comments on commit 1a0681f

Please sign in to comment.