summaryrefslogblamecommitdiffstats
path: root/server/api/users.js
blob: a297033f99cb8725ab0fa070774cd54ede24d0a9 (plain) (tree)
1
2
3
4
5
6
7
                     
                          
                                                         


                                                   
                                                                          








                                                                                       





                            









                                                                      



                                 

                         
   




                                                                               
                                          
                                                    

                                                                                            












                                                                         
 
                                               
                                                     



                                                                  

                                                                        





                                                                
          
























                                                                                                                                                                                                                
       
     
                         
   


                                          
                                                       




                                                                                                                                                                                                               

  
                                      












                                                                                  

                                                                               
 
                              
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
var express = require('express')
const { decorateApp } = require('@awaitjs/express')
var router = decorateApp(express.Router())
var authentication = require(path.join(__appdir, 'lib', 'authentication'))

// ############################################################################
// ###########################  GET requests  #################################

/*
 * @return: Returns a list of all users in the database and their given roles.
 */
router.getAsync('', async (req, res) => {
  const users = await db.user.findAll({ include: ['roles'], order: [['name', 'ASC']] })

  // Remove passwords
  await users.forEach(x => {
    x = x.dataValues
    delete x.password
  })
  res.status(200).send(users)
})

/*
 * @return: Returns information about a specific user.
 */
router.getAsync('/:id', async (req, res) => {
  const id = req.params.id === 'current' ? req.user.id : req.params.id
  const user = await db.user.findOne({ where: { id } })
  if (user) {
    // Remove the hased password.
    let u = user.dataValues
    delete u.password
    res.status(200).send(u)
  } else {
    res.status(404).end()
  }
})

// ############################################################################
// ##########################  POST requests  #################################

// Post request for adding roles to users.
router.postAsync('/:id/roles', async (req, res) => {
  if (!await req.user.hasPermission('permissions.grantrevoke')) return res.status(403).end()

  const id = req.params.id === 'current' ? req.user.id : req.params.id
  const user = await db.user.findOne({ where: { id } })
  if (user) {
    if (req.query.delete !== undefined && req.query.delete !== 'false') {
      await user.removeRoles(req.body.ids)
    } else {
      await user.addRoles(req.body.ids)
    }
    res.status(200).end()
  } else {
    res.status(404).end()
  }
})

// Post request for creating new user accounts.
router.postAsync(['/', '/:id'], async (req, res) => {
  if (req.params.id !== 'current') {
    // TODO: Check for permission to delete / create / update user
  }

  if (req.query.delete !== undefined && req.query.delete !== 'false') {
    const count = await db.user.destroy({ where: { id: req.body.ids } })
    return res.status(200).send({ count })
  }

  if (req.params.id === undefined) {
    await authentication.signup(req, res)
    return res.status(200).send({ auth: true, status: 'VALID' })
  } else {
    const id = req.params.id === 'current' ? req.user.id : req.params.id

    let email = req.body.email
    if (!authentication.validateEmail(req.body.email)) return res.status(500).send({ status: 'EMAIL_INVALID', error_message: 'The provided email is invalid.' })

    let user
    user = await db.user.findOne({ where: { id: id } })

    if (user) {
      let userinfo = {
        name: req.body.name,
        email: email
      }

      // Check if the username is set and if it's valid.
      let username = req.body.username
      if (username && req.params.id !== 'current') {
        if (!authentication.validateUsername(username)) return res.status(400).send({ auth: false, status: 'INVALID_USERNAME', error_message: 'Username does not fullfill the requirements. (No whitespaces)' })
        userinfo.username = username
      }

      // Update the user.
      await user.update(userinfo)
      if (req.body.password) {
        return authentication.changePassword(req, res)
      }
    }
    res.status(200).end()
  }
})

// Post request for changing the password.
router.postAsync('/:id/password', async (req, res) => {
  // Check if passwords are set.
  if (req.body.passwordCurrent && req.body.password) {
    if (req.body.passwordCurrent === req.body.password) return res.status(500).send({ auth: false, status: 'PASSWORD_ERROR', error_message: 'The provided password must be different than the old password.' })
    return authentication.changePassword(req, res)
  } else res.status(400).send({ auth: false, status: 'PASSWORD_MISSING', error_message: 'This service requires the current and the new password.' })
})

// Function for deleting a single user
router.delete('/:id/', (req, res) => {
  // Check if the user has the permission for chaning those userdata. Else return.
  if (req.params.id !== 'current') {
    return res.status(500).end()
  }
  const id = req.params.id === 'current' ? req.user.id : req.params.id

  // Every user can delete his own account.
  db.user.destroy({ where: { id } }).then(() => {
    res.status(200).end()
  })
})

// ############################################################################
// ############################################################################

module.exports.router = router