Skip to content

Commit

Permalink
Merge branch 'master' into features-gen25/agents-available-prod1
Browse files Browse the repository at this point in the history
# Conflicts:
#	models/faq_kb.js
  • Loading branch information
Giovanni Troisi committed Jan 23, 2025
2 parents d0b08a9 + bf3bf1c commit 586b967
Show file tree
Hide file tree
Showing 12 changed files with 1,487 additions and 652 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@
🚀 IN PRODUCTION 🚀
(https://www.npmjs.com/package/@tiledesk/tiledesk-server/v/2.3.77)

# 2.10.40
- bug fix: empty string for slug and index issue

# 2.10.39
- updated whatsapp-connector to 0.1.76
- updated tybot-connector to 0.2.139
- added chatbot slug in faq_kb model
- added /replace endpoint in request

# 2.10.38
- updated whatsapp-worker to 0.1.11
- added index to request model

# 2.10.36
- updated tybot-connector to 0.2.138

Expand Down
6 changes: 6 additions & 0 deletions errorCodes.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ const errorCodes = {
ACCESS_DENIED: 11003,
},
},
CHATBOT: {
BASE_CODE: 12000,
ERRORS: {
DUPLICATE_SLUG: 12001
}
}
// Aggiungi altre route
};

Expand Down
250 changes: 250 additions & 0 deletions middleware/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ if (process.env.GOOGLE_SIGNIN_ENABLED=="true" || process.env.GOOGLE_SIGNIN_ENABL
winston.info('Authentication Google Signin enabled : ' + enableGoogleSignin);



var enableOauth2Signin = false;
if (process.env.OAUTH2_SIGNIN_ENABLED=="true" || process.env.OAUTH2_SIGNIN_ENABLED == true) {
enableOauth2Signin = true;
}
winston.info('Authentication Oauth2 Signin enabled : ' + enableOauth2Signin);


var jwthistory = undefined;
try {
jwthistory = require('@tiledesk-ent/tiledesk-server-jwthistory');
Expand Down Expand Up @@ -573,6 +581,248 @@ if (enableGoogleSignin==true) {
}


if (enableOauth2Signin==true) {

const OAuth2Strategy = require('passport-oauth2');
OAuth2Strategy.prototype.userProfile = function(accessToken, done) {

winston.debug("accessToken " + accessToken)


/*
https://stackoverflow.com/questions/66452108/keycloak-get-users-returns-403-forbidden
The service account associated with your client needs to be allowed to view the realm users.
Go to http://localhost:8080/auth/admin/{realm_name}/console/#/realms/{realm_name}/clients
Select your client (which must be a confidential client)
In the settings tab, switch Service Account Enabled to ON
Click on save, the Service Account Roles tab will appear
In Client Roles, select realm_management
Scroll through available roles until you can select view_users
Click on Add selected
You should have something like this :
*/


// ATTENTION You have to add a client scope after as described here: https://keycloak.discourse.group/t/issue-on-userinfo-endpoint-at-keycloak-20/18461/4

// console.log("this._oauth2", this._oauth2)
this._oauth2._useAuthorizationHeaderForGET = true;
this._oauth2.get( process.env.OAUTH2_USER_INFO_URL, accessToken, (err, body) => {
if (err) {
return done(err);
}

try {
winston.debug("body", body);

const json = JSON.parse(body);
const userInfo = {
keycloakId: json.sub,
fullName: json.name,
firstName: json.given_name,
lastName: json.family_name,
username: json.preferred_username,
email: json.email,
// avatar: json.avatar,
// realm: this.options.realm,
};
winston.debug("userInfo", userInfo);

done(null, userInfo);
} catch (e) {
done(e);
}
});
};


passport.use(new OAuth2Strategy({
authorizationURL: process.env.OAUTH2_AUTH_URL,
tokenURL: process.env.OAUTH2_TOKEN_URL,
clientID: process.env.OAUTH2_CLIENT_ID,
clientSecret: process.env.OAUTH2_CLIENT_SECRET,
callbackURL: process.env.OAUTH2_CALLBACK_URL || "http://localhost:3000/auth/oauth2/callback"
},
function(accessToken, refreshToken, params, profile, cb) {
winston.debug("params", params);


const token = jwt.decode(accessToken); // user id lives in here
winston.debug("token", token);

const profileInfo = jwt.decode(params.id_token); // user email lives in here
winston.debug("profileInfo", profileInfo);

winston.debug("profile", profile);

winston.debug("accessToken", accessToken);

winston.debug("refreshToken", refreshToken);

var issuer = token.iss;
var email = profile.email;

var query = {providerId : issuer, subject: profile.keycloakId};
winston.debug("query", query)

Auth.findOne(query, function(err, cred){
winston.debug("cred", cred, err);
if (err) { return cb(err); }
if (!cred) {
// The oauth account has not logged in to this app before. Create a
// new user record and link it to the oauth account.
var password = uniqid()
// signup ( email, password, firstname, lastname, emailverified) {
userService.signup(email, password, profile.displayName, "", true)
.then(function (savedUser) {

winston.debug("savedUser", savedUser)

var auth = new Auth({
providerId: issuer,
email: email,
subject: profile.keycloakId,
});
auth.save(function (err, authSaved) {
if (err) { return cb(err); }
winston.debug("authSaved", authSaved);

return cb(null, savedUser);
});
}).catch(function(err) {
winston.error("Error signup oauth ", err);
return cb(err);
});
} else {
// The Oauth account has previously logged in to the app. Get the
// user record linked to the Oauth account and log the user in.

User.findOne({
email: email, status: 100
}, 'email firstname lastname emailverified id', function (err, user) {

winston.debug("user",user, err);
// winston.debug("usertoJSON()",user.toJSON());

if (err) {
winston.error("Error getting user",user, err);
return cb(err);
}

if (!user) {
winston.info("User not found",user, err);
return cb(null, false);
}

return cb(null, user);
});
}
});
}
));
}



// const KeycloakStrategy = require('@exlinc/keycloak-passport')


// // Register the strategy with passport
// passport.use(
// "keycloak",
// new KeycloakStrategy(
// {
// host: process.env.KEYCLOAK_HOST,
// realm: process.env.KEYCLOAK_REALM,
// clientID: process.env.KEYCLOAK_CLIENT_ID,
// clientSecret: process.env.KEYCLOAK_CLIENT_SECRET,
// callbackURL: `${process.env.AUTH_KEYCLOAK_CALLBACK}`,
// authorizationURL : `${process.env.KEYCLOAK_HOST}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/auth`,
// tokenURL : `${process.env.KEYCLOAK_HOST}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
// userInfoURL : `${process.env.KEYCLOAK_HOST}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/userinfo`
// // authorizationURL: '123',
// // tokenURL : '123',
// // userInfoURL: '123'
// },
// (accessToken, refreshToken, profile, done) => {


// const token = jwt.decode(accessToken); // user id lives in here
// console.log("token", token);

// console.log("profile", profile);

// console.log("accessToken", accessToken);

// console.log("refreshToken", refreshToken);

// var issuer = token.iss;
// var email = profile.email;

// var query = {providerId : issuer, subject: profile.keycloakId};
// winston.info("query", query)

// Auth.findOne(query, function(err, cred){
// winston.info("cred", cred, err);
// if (err) { return cb(err); }
// if (!cred) {
// // The oauth account has not logged in to this app before. Create a
// // new user record and link it to the oauth account.
// var password = uniqid()
// // signup ( email, password, firstname, lastname, emailverified) {
// userService.signup(email, password, profile.displayName, "", true)
// .then(function (savedUser) {

// winston.info("savedUser", savedUser)

// var auth = new Auth({
// providerId: issuer,
// email: email,
// subject: profile.keycloakId,
// });
// auth.save(function (err, authSaved) {
// if (err) { return cb(err); }
// winston.info("authSaved", authSaved);

// return cb(null, savedUser);
// });
// }).catch(function(err) {
// winston.error("Error signup oauth ", err);
// return cb(err);
// });
// } else {
// // The Oauth account has previously logged in to the app. Get the
// // user record linked to the Oauth account and log the user in.

// User.findOne({
// email: email, status: 100
// }, 'email firstname lastname emailverified id', function (err, user) {

// winston.info("user",user, err);
// winston.info("usertoJSON()",user.toJSON());

// if (err) {
// winston.error("Error getting user",user, err);
// return cb(err);
// }

// if (!user) {
// winston.info("User not found",user, err);
// return cb(null, false);
// }

// return done(null, user);
// });
// }
// });
// }
// ));







// var OidcStrategy = require('passport-openidconnect').Strategy;

Expand Down
12 changes: 6 additions & 6 deletions models/faq.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ const uuidv4 = require('uuid/v4');
var defaultFullTextLanguage = process.env.DEFAULT_FULLTEXT_INDEX_LANGUAGE || "none";

var FaqSchema = new Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
index: true,
required: true,
auto: true,
},
// _id: {
// type: mongoose.Schema.Types.ObjectId,
// index: true,
// required: true,
// auto: true,
// },
id_faq_kb: {
type: String,
index: true
Expand Down
50 changes: 46 additions & 4 deletions models/faq_kb.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,38 @@ var Faq_kbSchema = new Schema({
default: function () {
return this.isNew ? false : undefined;
},
},
slug: {
type: String,
required: false,
index: true
}
}, {
},{
timestamps: true
});


Faq_kbSchema.pre("save", async function (next) {
// Check if the document is new and if the slug has not been set manually
if (this.isNew && !this.slug) {
const baseSlug = generateSlug(this.name);
let uniqueSlug = baseSlug;

const existingCount = await mongoose.model("faq_kb").countDocuments({
id_project: this.id_project,
slug: { $regex: `^${baseSlug}(?:-\\d+)?$` }
});

if (existingCount > 0) {
uniqueSlug = `${baseSlug}-${existingCount}`;
}

this.slug = uniqueSlug;
}

next();
});

Faq_kbSchema.virtual('fullName').get(function () {
// winston.debug("faq_kb fullName virtual called");
return (this.name);
Expand All @@ -142,8 +168,14 @@ Faq_kbSchema.virtual('fullName').get(function () {
Faq_kbSchema.index({certified: 1, public: 1}); //suggested by atlas


Faq_kbSchema.index({name: 'text', description: 'text', "tags": 'text'},
{"name":"faqkb_fulltext","default_language": defaultFullTextLanguage,"language_override": "language"}); // schema level
Faq_kbSchema.index(
{name: 'text', description: 'text', "tags": 'text'},
{"name":"faqkb_fulltext","default_language": defaultFullTextLanguage,"language_override": "language"}); // schema level

Faq_kbSchema.index(
{ id_project: 1, slug: 1 },
{ unique: true, partialFilterExpression: { slug: { $exists: true } } }
);


var faq_kb = mongoose.model('faq_kb', Faq_kbSchema);
Expand All @@ -153,6 +185,16 @@ if (process.env.MONGOOSE_SYNCINDEX) {
winston.info("faq_kb syncIndexes")
}


function generateSlug(name) {
return name
.toLowerCase()
.trim()
.normalize("NFD") // Normalize characters with accents
.replace(/[\u0300-\u036f]/g, "") // Removes diacritics (e.g. à becomes a)
.replace(/[^a-z0-9\s-_]/g, "") // Remove special characters
.replace(/\s+/g, "-") // Replaces spaces with dashes
.replace(/_/g, "-")
.replace(/-+/g, "-"); // Removes consecutive hyphens
}

module.exports = faq_kb
1 change: 1 addition & 0 deletions models/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,7 @@ RequestSchema.index({ id_project: 1, preflight: 1, createdAt: 1 })
RequestSchema.index({ participants: 1, id_project: 1, createdAt: -1, status: 1 })
RequestSchema.index({ id_project: 1, "snapshot.lead.email": 1, createdAt: -1, status: 1 })
RequestSchema.index({ id_project: 1, createdAt: -1, status: 1 })
RequestSchema.index({ id_project: 1, preflight: 1, smartAssignment: 1, "snapshot.department.routing": 1, createdAt: 1, status: 1 })

// ERROR DURING DEPLOY OF 2.10.27
//RequestSchema.index({ id_project: 1, participants: 1, "snapshot.agents.id_user": 1, createdAt: -1, status: 1 })
Expand Down
Loading

0 comments on commit 586b967

Please sign in to comment.