users.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /* global WIKI */
  2. const bcrypt = require('bcryptjs-then')
  3. const _ = require('lodash')
  4. const tfa = require('node-2fa')
  5. const securityHelper = require('../helpers/security')
  6. const jwt = require('jsonwebtoken')
  7. const Model = require('objection').Model
  8. const validate = require('validate.js')
  9. const bcryptRegexp = /^\$2[ayb]\$[0-9]{2}\$[A-Za-z0-9./]{53}$/
  10. /**
  11. * Users model
  12. */
  13. module.exports = class User extends Model {
  14. static get tableName() { return 'users' }
  15. static get jsonSchema () {
  16. return {
  17. type: 'object',
  18. required: ['email'],
  19. properties: {
  20. id: {type: 'integer'},
  21. email: {type: 'string', format: 'email'},
  22. name: {type: 'string', minLength: 1, maxLength: 255},
  23. providerId: {type: 'string'},
  24. password: {type: 'string'},
  25. role: {type: 'string', enum: ['admin', 'guest', 'user']},
  26. tfaIsActive: {type: 'boolean', default: false},
  27. tfaSecret: {type: 'string'},
  28. jobTitle: {type: 'string'},
  29. location: {type: 'string'},
  30. pictureUrl: {type: 'string'},
  31. isSystem: {type: 'boolean'},
  32. isActive: {type: 'boolean'},
  33. isVerified: {type: 'boolean'},
  34. createdAt: {type: 'string'},
  35. updatedAt: {type: 'string'}
  36. }
  37. }
  38. }
  39. static get relationMappings() {
  40. return {
  41. groups: {
  42. relation: Model.ManyToManyRelation,
  43. modelClass: require('./groups'),
  44. join: {
  45. from: 'users.id',
  46. through: {
  47. from: 'userGroups.userId',
  48. to: 'userGroups.groupId'
  49. },
  50. to: 'groups.id'
  51. }
  52. },
  53. provider: {
  54. relation: Model.BelongsToOneRelation,
  55. modelClass: require('./authentication'),
  56. join: {
  57. from: 'users.providerKey',
  58. to: 'authentication.key'
  59. }
  60. },
  61. defaultEditor: {
  62. relation: Model.BelongsToOneRelation,
  63. modelClass: require('./editors'),
  64. join: {
  65. from: 'users.editorKey',
  66. to: 'editors.key'
  67. }
  68. },
  69. locale: {
  70. relation: Model.BelongsToOneRelation,
  71. modelClass: require('./locales'),
  72. join: {
  73. from: 'users.localeCode',
  74. to: 'locales.code'
  75. }
  76. }
  77. }
  78. }
  79. async $beforeUpdate(opt, context) {
  80. await super.$beforeUpdate(opt, context)
  81. this.updatedAt = new Date().toISOString()
  82. if (!(opt.patch && this.password === undefined)) {
  83. await this.generateHash()
  84. }
  85. }
  86. async $beforeInsert(context) {
  87. await super.$beforeInsert(context)
  88. this.createdAt = new Date().toISOString()
  89. this.updatedAt = new Date().toISOString()
  90. await this.generateHash()
  91. }
  92. // ------------------------------------------------
  93. // Instance Methods
  94. // ------------------------------------------------
  95. async generateHash() {
  96. if (this.password) {
  97. if (bcryptRegexp.test(this.password)) { return }
  98. this.password = await bcrypt.hash(this.password, 12)
  99. }
  100. }
  101. async verifyPassword(pwd) {
  102. if (await bcrypt.compare(pwd, this.password) === true) {
  103. return true
  104. } else {
  105. throw new WIKI.Error.AuthLoginFailed()
  106. }
  107. }
  108. async enableTFA() {
  109. let tfaInfo = tfa.generateSecret({
  110. name: WIKI.config.site.title
  111. })
  112. return this.$query.patch({
  113. tfaIsActive: true,
  114. tfaSecret: tfaInfo.secret
  115. })
  116. }
  117. async disableTFA() {
  118. return this.$query.patch({
  119. tfaIsActive: false,
  120. tfaSecret: ''
  121. })
  122. }
  123. async verifyTFA(code) {
  124. let result = tfa.verifyToken(this.tfaSecret, code)
  125. return (result && _.has(result, 'delta') && result.delta === 0)
  126. }
  127. getGlobalPermissions() {
  128. return _.uniq(_.flatten(_.map(this.groups, 'permissions')))
  129. }
  130. getGroups() {
  131. return _.uniq(_.map(this.groups, 'id'))
  132. }
  133. // ------------------------------------------------
  134. // Model Methods
  135. // ------------------------------------------------
  136. static async processProfile({ profile, providerKey }) {
  137. const provider = _.get(WIKI.auth.strategies, providerKey, {})
  138. provider.info = _.find(WIKI.data.authentication, ['key', providerKey])
  139. // Find existing user
  140. let user = await WIKI.models.users.query().findOne({
  141. providerId: _.toString(profile.id),
  142. providerKey
  143. })
  144. // Parse email
  145. let primaryEmail = ''
  146. if (_.isArray(profile.emails)) {
  147. const e = _.find(profile.emails, ['primary', true])
  148. primaryEmail = (e) ? e.value : _.first(profile.emails).value
  149. } else if (_.isString(profile.email) && profile.email.length > 5) {
  150. primaryEmail = profile.email
  151. } else if (_.isString(profile.mail) && profile.mail.length > 5) {
  152. primaryEmail = profile.mail
  153. } else if (profile.user && profile.user.email && profile.user.email.length > 5) {
  154. primaryEmail = profile.user.email
  155. } else {
  156. throw new Error('Missing or invalid email address from profile.')
  157. }
  158. primaryEmail = _.toLower(primaryEmail)
  159. // Find pending social user
  160. if (!user) {
  161. user = await WIKI.models.users.query().findOne({
  162. email: primaryEmail,
  163. providerId: null,
  164. providerKey
  165. })
  166. if (user) {
  167. user = await user.$query().patchAndFetch({
  168. providerId: _.toString(profile.id)
  169. })
  170. }
  171. }
  172. // Parse display name
  173. let displayName = ''
  174. if (_.isString(profile.displayName) && profile.displayName.length > 0) {
  175. displayName = profile.displayName
  176. } else if (_.isString(profile.name) && profile.name.length > 0) {
  177. displayName = profile.name
  178. } else {
  179. displayName = primaryEmail.split('@')[0]
  180. }
  181. // Parse picture URL
  182. let pictureUrl = _.get(profile, 'picture', _.get(user, 'pictureUrl', null))
  183. // Update existing user
  184. if (user) {
  185. if (!user.isActive) {
  186. throw new WIKI.Error.AuthAccountBanned()
  187. }
  188. if (user.isSystem) {
  189. throw new Error('This is a system reserved account and cannot be used.')
  190. }
  191. user = await user.$query().patchAndFetch({
  192. email: primaryEmail,
  193. name: displayName,
  194. pictureUrl: pictureUrl
  195. })
  196. return user
  197. }
  198. // Self-registration
  199. if (provider.selfRegistration) {
  200. // Check if email domain is whitelisted
  201. if (_.get(provider, 'domainWhitelist', []).length > 0) {
  202. const emailDomain = _.last(primaryEmail.split('@'))
  203. if (!_.includes(provider.domainWhitelist, emailDomain)) {
  204. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  205. }
  206. }
  207. // Create account
  208. user = await WIKI.models.users.query().insertAndFetch({
  209. providerKey: providerKey,
  210. providerId: _.toString(profile.id),
  211. email: primaryEmail,
  212. name: displayName,
  213. pictureUrl: pictureUrl,
  214. localeCode: WIKI.config.lang.code,
  215. defaultEditor: 'markdown',
  216. tfaIsActive: false,
  217. isSystem: false,
  218. isActive: true,
  219. isVerified: true
  220. })
  221. // Assign to group(s)
  222. if (provider.autoEnrollGroups.length > 0) {
  223. await user.$relatedQuery('groups').relate(provider.autoEnrollGroups)
  224. }
  225. return user
  226. }
  227. throw new Error('You are not authorized to login.')
  228. }
  229. static async login (opts, context) {
  230. if (_.has(WIKI.auth.strategies, opts.strategy)) {
  231. const strInfo = _.find(WIKI.data.authentication, ['key', opts.strategy])
  232. // Inject form user/pass
  233. if (strInfo.useForm) {
  234. _.set(context.req, 'body.email', opts.username)
  235. _.set(context.req, 'body.password', opts.password)
  236. }
  237. // Authenticate
  238. return new Promise((resolve, reject) => {
  239. WIKI.auth.passport.authenticate(opts.strategy, {
  240. session: !strInfo.useForm,
  241. scope: strInfo.scopes ? strInfo.scopes : null
  242. }, async (err, user, info) => {
  243. if (err) { return reject(err) }
  244. if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
  245. // Is 2FA required?
  246. if (user.tfaIsActive) {
  247. try {
  248. let loginToken = await securityHelper.generateToken(32)
  249. await WIKI.redis.set(`tfa:${loginToken}`, user.id, 'EX', 600)
  250. return resolve({
  251. tfaRequired: true,
  252. tfaLoginToken: loginToken
  253. })
  254. } catch (err) {
  255. WIKI.logger.warn(err)
  256. return reject(new WIKI.Error.AuthGenericError())
  257. }
  258. } else {
  259. // No 2FA, log in user
  260. return context.req.logIn(user, { session: !strInfo.useForm }, async err => {
  261. if (err) { return reject(err) }
  262. const jwtToken = await WIKI.models.users.refreshToken(user)
  263. resolve({
  264. jwt: jwtToken.token,
  265. tfaRequired: false
  266. })
  267. })
  268. }
  269. })(context.req, context.res, () => {})
  270. })
  271. } else {
  272. throw new WIKI.Error.AuthProviderInvalid()
  273. }
  274. }
  275. static async refreshToken(user) {
  276. if (_.isSafeInteger(user)) {
  277. user = await WIKI.models.users.query().findById(user).eager('groups').modifyEager('groups', builder => {
  278. builder.select('groups.id', 'permissions')
  279. })
  280. if (!user) {
  281. WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
  282. throw new WIKI.Error.AuthGenericError()
  283. }
  284. } else if (_.isNil(user.groups)) {
  285. await user.$relatedQuery('groups').select('groups.id', 'permissions')
  286. }
  287. return {
  288. token: jwt.sign({
  289. id: user.id,
  290. email: user.email,
  291. name: user.name,
  292. pictureUrl: user.pictureUrl,
  293. timezone: user.timezone,
  294. localeCode: user.localeCode,
  295. defaultEditor: user.defaultEditor,
  296. permissions: user.getGlobalPermissions(),
  297. groups: user.getGroups()
  298. }, {
  299. key: WIKI.config.certs.private,
  300. passphrase: WIKI.config.sessionSecret
  301. }, {
  302. algorithm: 'RS256',
  303. expiresIn: WIKI.config.auth.tokenExpiration,
  304. audience: WIKI.config.auth.audience,
  305. issuer: 'urn:wiki.js'
  306. }),
  307. user
  308. }
  309. }
  310. static async loginTFA(opts, context) {
  311. if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
  312. let result = await WIKI.redis.get(`tfa:${opts.loginToken}`)
  313. if (result) {
  314. let userId = _.toSafeInteger(result)
  315. if (userId && userId > 0) {
  316. let user = await WIKI.models.users.query().findById(userId)
  317. if (user && user.verifyTFA(opts.securityCode)) {
  318. return Promise.fromCallback(clb => {
  319. context.req.logIn(user, clb)
  320. }).return({
  321. succeeded: true,
  322. message: 'Login Successful'
  323. }).catch(err => {
  324. WIKI.logger.warn(err)
  325. throw new WIKI.Error.AuthGenericError()
  326. })
  327. } else {
  328. throw new WIKI.Error.AuthTFAFailed()
  329. }
  330. }
  331. }
  332. }
  333. throw new WIKI.Error.AuthTFAInvalid()
  334. }
  335. static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
  336. // Input sanitization
  337. email = _.toLower(email)
  338. // Input validation
  339. let validation = null
  340. if (providerKey === 'local') {
  341. validation = validate({
  342. email,
  343. passwordRaw,
  344. name
  345. }, {
  346. email: {
  347. email: true,
  348. length: {
  349. maximum: 255
  350. }
  351. },
  352. passwordRaw: {
  353. presence: {
  354. allowEmpty: false
  355. },
  356. length: {
  357. minimum: 6
  358. }
  359. },
  360. name: {
  361. presence: {
  362. allowEmpty: false
  363. },
  364. length: {
  365. minimum: 2,
  366. maximum: 255
  367. }
  368. }
  369. }, { format: 'flat' })
  370. } else {
  371. validation = validate({
  372. email,
  373. name
  374. }, {
  375. email: {
  376. email: true,
  377. length: {
  378. maximum: 255
  379. }
  380. },
  381. name: {
  382. presence: {
  383. allowEmpty: false
  384. },
  385. length: {
  386. minimum: 2,
  387. maximum: 255
  388. }
  389. }
  390. }, { format: 'flat' })
  391. }
  392. if (validation && validation.length > 0) {
  393. throw new WIKI.Error.InputInvalid(validation[0])
  394. }
  395. // Check if email already exists
  396. const usr = await WIKI.models.users.query().findOne({ email, providerKey })
  397. if (!usr) {
  398. // Create the account
  399. let newUsrData = {
  400. providerKey,
  401. email,
  402. name,
  403. locale: 'en',
  404. defaultEditor: 'markdown',
  405. tfaIsActive: false,
  406. isSystem: false,
  407. isActive: true,
  408. isVerified: true,
  409. mustChangePwd: false
  410. }
  411. if (providerKey === `local`) {
  412. newUsrData.password = passwordRaw
  413. newUsrData.mustChangePwd = (mustChangePassword === true)
  414. }
  415. const newUsr = await WIKI.models.users.query().insert(newUsrData)
  416. // Assign to group(s)
  417. if (groups.length > 0) {
  418. await newUsr.$relatedQuery('groups').relate(groups)
  419. }
  420. if (sendWelcomeEmail) {
  421. // Send welcome email
  422. await WIKI.mail.send({
  423. template: 'accountWelcome',
  424. to: email,
  425. subject: `Welcome to the wiki ${WIKI.config.title}`,
  426. data: {
  427. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  428. title: `You've been invited to the wiki ${WIKI.config.title}`,
  429. content: `Click the button below to access the wiki.`,
  430. buttonLink: `${WIKI.config.host}/login`,
  431. buttonText: 'Login'
  432. },
  433. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  434. })
  435. }
  436. } else {
  437. throw new WIKI.Error.AuthAccountAlreadyExists()
  438. }
  439. }
  440. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  441. const localStrg = await WIKI.models.authentication.getStrategy('local')
  442. // Check if self-registration is enabled
  443. if (localStrg.selfRegistration || bypassChecks) {
  444. // Input sanitization
  445. email = _.toLower(email)
  446. // Input validation
  447. const validation = validate({
  448. email,
  449. password,
  450. name
  451. }, {
  452. email: {
  453. email: true,
  454. length: {
  455. maximum: 255
  456. }
  457. },
  458. password: {
  459. presence: {
  460. allowEmpty: false
  461. },
  462. length: {
  463. minimum: 6
  464. }
  465. },
  466. name: {
  467. presence: {
  468. allowEmpty: false
  469. },
  470. length: {
  471. minimum: 2,
  472. maximum: 255
  473. }
  474. }
  475. }, { format: 'flat' })
  476. if (validation && validation.length > 0) {
  477. throw new WIKI.Error.InputInvalid(validation[0])
  478. }
  479. // Check if email domain is whitelisted
  480. if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  481. const emailDomain = _.last(email.split('@'))
  482. if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
  483. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  484. }
  485. }
  486. // Check if email already exists
  487. const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
  488. if (!usr) {
  489. // Create the account
  490. const newUsr = await WIKI.models.users.query().insert({
  491. provider: 'local',
  492. email,
  493. name,
  494. password,
  495. locale: 'en',
  496. defaultEditor: 'markdown',
  497. tfaIsActive: false,
  498. isSystem: false,
  499. isActive: true,
  500. isVerified: false
  501. })
  502. // Assign to group(s)
  503. if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  504. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  505. }
  506. if (verify) {
  507. // Create verification token
  508. const verificationToken = await WIKI.models.userKeys.generateToken({
  509. kind: 'verify',
  510. userId: newUsr.id
  511. })
  512. // Send verification email
  513. await WIKI.mail.send({
  514. template: 'accountVerify',
  515. to: email,
  516. subject: 'Verify your account',
  517. data: {
  518. preheadertext: 'Verify your account in order to gain access to the wiki.',
  519. title: 'Verify your account',
  520. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  521. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  522. buttonText: 'Verify'
  523. },
  524. text: `You must open the following link in your browser to verify your account and gain access to the wiki: ${WIKI.config.host}/verify/${verificationToken}`
  525. })
  526. }
  527. return true
  528. } else {
  529. throw new WIKI.Error.AuthAccountAlreadyExists()
  530. }
  531. } else {
  532. throw new WIKI.Error.AuthRegistrationDisabled()
  533. }
  534. }
  535. static async getGuestUser () {
  536. const user = await WIKI.models.users.query().findById(2).eager('groups').modifyEager('groups', builder => {
  537. builder.select('groups.id', 'permissions')
  538. })
  539. if (!user) {
  540. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  541. process.exit(1)
  542. }
  543. user.permissions = user.getGlobalPermissions()
  544. return user
  545. }
  546. }