Skip to content

Commit 688af68

Browse files
author
Sachin Maheshwari
committed
commiting auth0 related code here
1 parent 53e806a commit 688af68

File tree

5 files changed

+533
-0
lines changed

5 files changed

+533
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
function login(handleOrEmail, password, callback) {
2+
// This script should authenticate a user against the credentials stored in
3+
// your database.
4+
// It is executed when a user attempts to log in or immediately after signing
5+
// up (as a verification that the user was successfully signed up).
6+
//
7+
// Everything returned by this script will be set as part of the user profile
8+
// and will be visible by any of the tenant admins. Avoid adding attributes
9+
// with values such as passwords, keys, secrets, etc.
10+
//
11+
// The `password` parameter of this function is in plain text. It must be
12+
// hashed/salted to match whatever is stored in your database. For example:
13+
//
14+
// var bcrypt = require('bcrypt@0.8.5');
15+
// bcrypt.compare(password, dbPasswordHash, function(err, res)) { ... }
16+
//
17+
// There are three ways this script can finish:
18+
// 1. The user's credentials are valid. The returned user profile should be in
19+
// the following format: https://auth0.com/docs/users/normalized/auth0/normalized-user-profile-schema
20+
// var profile = {
21+
// user_id: ..., // user_id is mandatory
22+
// email: ...,
23+
// [...]
24+
// };
25+
// callback(null, profile);
26+
// 2. The user's credentials are invalid
27+
// callback(new WrongUsernameOrPasswordError(email, "my error message"));
28+
// 3. Something went wrong while trying to reach your database
29+
// callback(new Error("my error message"));
30+
//
31+
// A list of Node.js modules which can be referenced is available here:
32+
//
33+
// https://tehsis.github.io/webtaskio-canirequire/
34+
request.post({
35+
url: "https://api."+configuration.DOMAIN+"/v3/users/login",
36+
form: {
37+
handleOrEmail: handleOrEmail,
38+
password: password
39+
}
40+
//for more options check: https://github.com/mikeal/request#requestoptions-callback
41+
}, function (err, response, body) {
42+
console.log("response..............", err,response.statusCode);
43+
if (err) return callback(err);
44+
if (response.statusCode === 401) return callback();
45+
var user = JSON.parse(body);
46+
user.result.content.roles = user.result.content.roles.map(function(role) {
47+
return role.roleName;
48+
});
49+
50+
callback(null, {
51+
user_id: user.result.content.id,
52+
nickname: user.result.content.handle,
53+
email: user.result.content.email,
54+
handle:user.result.content.handle,
55+
roles: user.result.content.roles,
56+
email_verified: user.result.content.emailActive,
57+
});
58+
});
59+
}
60+
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
2+
function (user, context, callback) {
3+
if (context.clientID === configuration.CLIENT_ACCOUNTS_LOGIN) { //
4+
const _ = require('lodash');
5+
6+
// TODO: implement your rule
7+
// if (context.protocol === "redirect-callback") {
8+
// User was redirected to the /continue endpoint
9+
if (context.redirect) {
10+
return callback(null, user, context);
11+
// returnning from here no need to check further
12+
}
13+
// otherwise to nothing
14+
15+
console.log("Enter Rule: Custom-Claims");
16+
let handle = _.get(user, "handle", null);
17+
const provider = _.get(user, "identities[0].provider", null);
18+
if (!handle && provider === "auth0") {
19+
handle = _.get(user, "nickname", null);
20+
}
21+
console.log("Fetch roles for email/handle: ", user.email, handle, provider);
22+
23+
global.AUTH0_CLAIM_NAMESPACE = "https://" + configuration.DOMAIN + "/";
24+
try {
25+
request.post({
26+
url: 'https://api.' + configuration.DOMAIN + '/v3/users/roles',
27+
form: {
28+
email: user.email,
29+
handle: handle
30+
}
31+
}, function (err, response, body) {
32+
console.log("called topcoder api for role: response status - ", response.statusCode);
33+
if (err) return callback(err, user, context);
34+
if (response.statusCode !== 200) {
35+
return callback('Login Error: Whoops! Something went wrong. Looks like your registered email has discrepancy with Authentication. Please connect to our support <a href="mailto:support@topcoder.com">support@topcoder.com</a>. Back to application ', user, context);
36+
}
37+
38+
let res = JSON.parse(body);
39+
// TODO need to double sure about multiple result or no result
40+
let userId = res.result.content.id;
41+
let handle = res.result.content.handle;
42+
let roles = res.result.content.roles.map(function (role) {
43+
return role.roleName;
44+
});
45+
let userStatus = res.result.content.active; // true/false
46+
47+
// TEMP
48+
let tcsso = res.result.content.regSource || '';
49+
50+
context.idToken[global.AUTH0_CLAIM_NAMESPACE + 'roles'] = roles;
51+
context.idToken[global.AUTH0_CLAIM_NAMESPACE + 'userId'] = userId;
52+
context.idToken[global.AUTH0_CLAIM_NAMESPACE + 'handle'] = handle;
53+
context.idToken[global.AUTH0_CLAIM_NAMESPACE + 'user_id'] = user.identities[0].provider + "|" + userId;
54+
context.idToken[global.AUTH0_CLAIM_NAMESPACE + 'tcsso'] = tcsso;
55+
context.idToken[global.AUTH0_CLAIM_NAMESPACE + 'active'] = userStatus;
56+
context.idToken.nickname = handle;
57+
//console.log(user, context);
58+
if (!userStatus) {
59+
context.redirect = {
60+
url: `https://accounts-auth0.${configuration.DOMAIN}/check_email.html`
61+
};
62+
return callback(null, user, context);
63+
}
64+
if (!userStatus && context.login_counts > 1) {
65+
return callback('Login Alert: Please verify your email first! Please connect to our support <a href="mailto:support@topcoder.com">support@topcoder.com</a>. Back to application ', user, context);
66+
}
67+
return callback(null, user, context);
68+
}
69+
);
70+
} catch (e) {
71+
console.log("Error in calling user roles" + e);
72+
return callback("Something went worng!. Please retry.", user, context);
73+
}
74+
} else {
75+
// for other apps do nothing
76+
return callback(null, user, context);
77+
}
78+
}
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
2+
function (user, context, callback) {
3+
if (context.clientID === configuration.CLIENT_ACCOUNTS_LOGIN) { // client/application specific
4+
5+
const _ = require('lodash');
6+
console.log("Enter Rule: Enterprise-User-Registration");
7+
8+
const baseApiUrl = "https://api." + configuration.DOMAIN + "/v3";
9+
//console.log("register user rule executed- user", user);
10+
//console.log("register user rule executed - context", context);
11+
12+
const isEnterprise = (_.get(user, "identities[0].provider") !== 'auth0') &&
13+
!(_.get(user, "identities[0].isSocial")) ? true : false;
14+
15+
console.log("Is enterprise login: ", isEnterprise);
16+
if (isEnterprise) {
17+
let provider = _.get(user, "identities[0].connection");
18+
const providerType = _.get(user, "identities[0].provider");
19+
let userId = _.get(user, "identities[0].user_id");
20+
userId = userId.substring(userId.lastIndexOf('|') + 1);
21+
22+
let handle = _.get(user, "nickname", "");
23+
const lastName = _.get(user, "family_name");
24+
const firstName = _.get(user, "given_name");
25+
const email = _.get(user, "email");
26+
//const emailVerified = _.get(user, "email_verified", true);
27+
const name = _.get(user, "name");
28+
29+
let isoAlpha2Code = _.get(context, "request.geoip.country_code");
30+
let isoAlpha3Code = _.get(context, "request.geoip.country_code3");
31+
let countryCode = _.get(context, "request.geoip.country_name");
32+
let regSource = _.get(context, "request.query.regSource", null);
33+
let retUrl = _.get(context, "request.query.returnUrl", null);
34+
let utmSource = _.get(context, "request.query.utmSource", null);
35+
let utmMedium = _.get(context, "request.query.utmMedium", null);
36+
let utmCampaign = _.get(context, "request.query.utmCampaign", null);
37+
38+
const resourcePath = '/identityproviders?filter=handle=' + email;
39+
const afterActivationURL = configuration.DEFAULT_AFTER_ACTIVATION_URL;
40+
const hostName = _.get(context, "request.hostname", null);
41+
const registrationCompletetUrl = "https://" + hostName + "/continue";
42+
//const userHandleRedirectUrl = configuration.CUSTOM_PAGES_BASE_URL + '/signup.html?source='+ utmSource + '&formAction=' + registrationCompletetUrl;
43+
const userHandleRedirectUrl = configuration.CUSTOM_PAGES_BASE_URL +
44+
"/signup.html?regSource=" + regSource +
45+
"&firstName=" + encodeURIComponent(firstName) +
46+
"&lastName=" + encodeURIComponent(lastName) +
47+
"&utmSource=" + encodeURIComponent(utmSource) +
48+
"&utmMedium=" + encodeURIComponent(utmMedium) +
49+
"&utmCampaign=" + encodeURIComponent(utmCampaign) +
50+
"&formAction=" + registrationCompletetUrl +
51+
"&returnUrl=" + retUrl;
52+
53+
console.log("provider", provider, email);
54+
try {
55+
request.get({
56+
url: baseApiUrl + resourcePath
57+
}, function (err, response, body) {
58+
console.log("Enterprise user check - responseBody", body);
59+
60+
if (err) {
61+
console.log("Enterprise validation error:", err);
62+
}
63+
64+
/**
65+
* check if enterprise profile is valid for our TC database
66+
*/
67+
68+
/*
69+
Aug 2021 adding new wipro-sso connection with name wipro_azuread
70+
*/
71+
72+
if (_.includes([configuration.WIPRO_SSO_AZURE_AD_CONNECTION_NAME], provider)
73+
) {
74+
provider = configuration.WIPRO_SSO_ADFS_CONNECTION_NAME;
75+
}
76+
77+
let isSSOUserExist = (_.get(JSON.parse(body), "result.content.name") === provider) ?
78+
true : false;
79+
80+
console.log("Enterprise customer alreday available:", isSSOUserExist);
81+
if (!isSSOUserExist) {
82+
console.log("register enterprise user.");
83+
if (context.protocol === "redirect-callback") {
84+
// User was redirected to the /continue endpoint
85+
console.log("print data", typeof context);
86+
console.log("get user extra data from query param");
87+
handle = _.get(context, "request.query.handle", handle);
88+
console.log("...Handle....", handle);
89+
90+
const countryStr = _.get(context, "request.query.country", null);
91+
const countryObj = JSON.parse(countryStr);
92+
if (countryObj) {
93+
countryCode = _.get(countryObj, "code", countryCode);
94+
isoAlpha2Code = _.get(countryObj, "alpha2", isoAlpha2Code);
95+
isoAlpha3Code = _.get(countryObj, "alpha3", isoAlpha3Code);
96+
}
97+
utmSource = _.get(context, "request.query.source", utmSource);
98+
utmMedium = _.get(context, "request.query.utmMedium", utmMedium);
99+
utmCampaign = _.get(context, "request.query.utmCampaign", utmCampaign);
100+
} else {
101+
console.log('Redirect to choose user handle page.');
102+
context.redirect = {
103+
url: userHandleRedirectUrl
104+
};
105+
return callback(null, user, context);
106+
}
107+
// Enterprise profile will be active default
108+
let data = {
109+
"param": {
110+
"handle": handle,
111+
"firstName": firstName,
112+
"lastName": lastName,
113+
"email": email,
114+
"country": {
115+
"code": countryCode,
116+
"isoAlpha3Code": isoAlpha3Code,
117+
"isoAlpha2Code": isoAlpha2Code
118+
},
119+
"utmSource": utmSource,
120+
"utmMedium": utmMedium,
121+
"utmCampaign": utmCampaign,
122+
"active": true,
123+
"profile": {
124+
"name": name,
125+
"email": email,
126+
"providerType": providerType,
127+
"provider": provider,
128+
"userId": userId
129+
}
130+
},
131+
"options": {
132+
"afterActivationURL": encodeURIComponent( configuration.DEFAULT_AFTER_ACTIVATION_URL)
133+
}
134+
};
135+
console.log("Going to add enterprise", JSON.stringify(data));
136+
request.post({
137+
url: "https://api." + configuration.DOMAIN + "/v3/users",
138+
json: data
139+
}, function (error, response, body) {
140+
if (response.statusCode !== 200) {
141+
console.log("Enterprise registration error", error);
142+
}
143+
// on success
144+
return callback(null, user, context);
145+
//if (response.statusCode === 401) return callback();
146+
});
147+
} else { // valid social user if block end
148+
return callback(null, user, context);
149+
}
150+
}
151+
); // end validatesocial request
152+
} catch (e) {
153+
console.log(`Error in calling validate enterprise user ${e}`);
154+
return callback(null, user, context);
155+
}
156+
} else {// end isSocial if-block
157+
console.log("existing from Enterprise-User-Registration rule.");
158+
return callback(null, user, context);
159+
}
160+
} else { // END client-id check
161+
return callback(null, user, context);
162+
}
163+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
2+
function (user, context, callback) {
3+
if (context.clientID === configuration.CLIENT_ACCOUNTS_LOGIN) { // client/application specific
4+
// TODO: implement your rule
5+
const _ = require('lodash');
6+
7+
const resend = _.get(context, "request.query.resend", null);
8+
9+
if (context.protocol === 'redirect-callback' && resend) {
10+
console.log("----------:Entered Email Resend Rule:------------");
11+
let handle = _.get(user, "handle", null);
12+
const provider = _.get(user, "identities[0].provider", null);
13+
if (!handle && provider === "auth0") {
14+
handle = _.get(user, "nickname", null);
15+
}
16+
17+
global.AUTH0_CLAIM_NAMESPACE = "https://" + configuration.DOMAIN + "/";
18+
// trigger resend email event at identity servcie
19+
try {
20+
request.post({
21+
url: 'https://api.' + configuration.DOMAIN + '/v3/users/resendEmail',
22+
form: {
23+
email: user.email,
24+
handle: handle
25+
}
26+
}, function (err, response, body) {
27+
console.log("called topcoder api for resend email: response status - ", response.statusCode);
28+
if (err) return callback(err, user, context);
29+
if (response.statusCode !== 200) {
30+
//{"id":"2fb48e50:17a334870b1:-457c","result":{"success":true,"status":400,"metadata":null,"content":"User has been activated"},"version":"v3"}
31+
32+
const error_message = _.get(JSON.parse(body), 'result.content', 'unknown error');
33+
return callback(`Resend email error: ${error_message}`, user, context);
34+
}
35+
return callback(null, user, context);
36+
}
37+
);
38+
} catch (e) {
39+
return callback("Something went worng!. Please retry.", user, context);
40+
}
41+
// returnning from here no need to check further
42+
} else { // if it is not redirect, do nothing
43+
return callback(null, user, context);
44+
}
45+
} else {
46+
// for other apps do nothing
47+
return callback(null, user, context);
48+
}
49+
}

0 commit comments

Comments
 (0)