forked from sunbird-cb/sunbird-cb-uiproxy
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathssoUserHelper.ts
More file actions
154 lines (149 loc) · 6.54 KB
/
ssoUserHelper.ts
File metadata and controls
154 lines (149 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import axios from 'axios'
import lodash from 'lodash'
import { axiosRequestConfig } from '../configs/request.config'
import { CONSTANTS } from '../utils/env'
import { logError, logInfo } from '../utils/logger'
import { getKeyCloakClient } from './keycloakHelper'
const API_END_POINTS = {
// cbExtSignUpUser: `${CONSTANTS.KONG_API_BASE}/user/v1/ext/signup`,
cbExtSignUpUser: `${CONSTANTS.KONG_API_BASE}/user/v5/parichay/create`,
}
export async function fetchUserByEmailId(emailId: string) {
const sbUserSearchRes = await axios({
...axiosRequestConfig,
data: { request: {
fields : ['userId', 'status', 'channel', 'rootOrgId', 'organisations'],
filters: { email: emailId.toLowerCase() },
} },
method: 'POST',
url: CONSTANTS.LEARNER_SERVICE_API_BASE + '/private/user/v1/search',
})
const result = {
errMessage : '', rootOrgId: '', userExist : false,
}
if (sbUserSearchRes.data.responseCode.toUpperCase() === 'OK') {
if (sbUserSearchRes.data.result.response.count === 0) {
logInfo('user accound doesnot exist. returning false')
} else if (sbUserSearchRes.data.result.response.count === 1) {
const contentObj = sbUserSearchRes.data.result.response.content[0]
const status = contentObj.status
logInfo('ssoUserHelper:: user account exist for :: ' + emailId + ', Status: ' + status)
if (status === 1) {
logInfo('ssoUserHelper:: user account enabled. returning true')
result.userExist = true
result.rootOrgId = contentObj.rootOrgId
} else {
logInfo('ssoUserHelper:: user account is diabled. throwing error')
result.errMessage = 'Account Disabled. Please contact Admin.'
}
} else {
result.errMessage = 'More than one user account exists. Please contact Admin.'
}
} else {
logError('ssoUserHelper:: fetchUserByEmailId failed' + JSON.stringify(sbUserSearchRes.data))
result.errMessage = 'Failed to verify email exist. Internal Server Error.'
}
return Promise.resolve(result)
}
export async function createUserWithMailId(emailId: string, firstNameStr: string, lastNameStr: string, mobileNoStr = '') {
const result = {
errMessage : '', userCreated : false, userId: '',
}
const signUpErr = 'SIGN_UP_ERR-'
let statusString = ''
let _reqPayload = {
request:
{
email: emailId,
emailVerified: true,
firstName: firstNameStr.trim() + ' ' + lastNameStr.trim(),
phone: '',
roles: [ 'PUBLIC' ],
},
}
let _validPhone
try {
// Check mobile number is valid for length
if (mobileNoStr && mobileNoStr.length >= 10) {
// Check phone number starts with `+` and country code belongs to 91
if (mobileNoStr.charAt(0) === '+' && mobileNoStr.slice(1, 3) === '91' &&
mobileNoStr.slice(3, mobileNoStr.length).length === 10) {
_validPhone = mobileNoStr.slice(3, mobileNoStr.length)
} else if (mobileNoStr.slice(0, 2) === '91' && mobileNoStr.slice(2, mobileNoStr.length).length === 10) {
// Check phone number starts with 91
_validPhone = mobileNoStr.slice(2, mobileNoStr.length)
} else {
// Accept the incoming phone number as it is; since it is not prefixed with `+` or country code
_validPhone = mobileNoStr
}
}
} catch (error) {
logError('ssoUserHelper:createUserWithMailId - Error while validating phone number')
}
// Update the request object
if (_validPhone) {
_reqPayload.request.phone = _validPhone
} else {
_reqPayload = lodash.omit(_reqPayload, 'phone')
}
let signUpResponse
try {
signUpResponse = await axios({
...axiosRequestConfig,
data: _reqPayload,
headers: {
Authorization: CONSTANTS.SB_API_KEY,
},
method: 'POST',
url: API_END_POINTS.cbExtSignUpUser,
})
statusString = signUpResponse.data.params.status
if (statusString.toUpperCase() !== 'SUCCESS') {
result.errMessage = signUpErr + 'FAILED_TO_CREATE_USER'
} else {
result.userCreated = true
result.userId = signUpResponse.data.result.userId
}
} catch (signUpErr) {
const errMsg = signUpErr.response.data.params.errmsg
logError ('ssoUserHelper:: Failed to create User, error msg : ' + errMsg)
result.errMessage = errMsg
}
return Promise.resolve(result)
}
// tslint:disable-next-line: no-any
export async function updateKeycloakSession(emailId: string, req: any, res: any) {
const scope = 'offline_access'
const keycloakClient = getKeyCloakClient()
// tslint:disable-next-line: no-any
let grant: { access_token: { token: any }; refresh_token: { token: any } }
const result = {
access_token: '', errMessage : '', keycloakSessionCreated: false, refresh_token: '',
}
try {
grant = await keycloakClient.grantManager.obtainDirectly(emailId, undefined, undefined, scope)
keycloakClient.storeGrant(grant, req, res)
req.kauth.grant = grant
const userId = req.kauth.grant.access_token.content.sub.split(':')
req.session.userId = userId[userId.length - 1]
logInfo('ssoUserHelper::updateKeycloakSession:: userId ::', userId, ' dateTime :: ', new Date().toString())
req.session.keycloakClientId = CONSTANTS.KEYCLOAK_GOOGLE_CLIENT_ID
req.session.keycloakClientSecret = CONSTANTS.KEYCLOAK_GOOGLE_CLIENT_SECRET
result.access_token = grant.access_token.token
result.refresh_token = grant.refresh_token.token
result.keycloakSessionCreated = true
// tslint:disable-next-line: no-any
keycloakClient.authenticated(req, (error: any) => {
logInfo('ssoUserHelper::keycloakClient::authenticated..')
if (error) {
logError('ssoUserHelper:: keycloak.authenticate failed Email: ' + emailId + ', Error: ' + JSON.stringify(error))
result.errMessage = 'FAILED_TO_CREATE_KEYCLOAK_SESSION'
}
})
return Promise.resolve(result)
} catch (err) {
logError('ssoUserHelper: createSession failed for Email: ' + emailId + ', Error: ' + JSON.stringify(err))
result.errMessage = 'FAILED_TO_CREATE_KEYCLOAK_SESSION'
}
return Promise.resolve(result)
}