ban.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const Errors = require('../lib/errors')
  2. module.exports = (sequelize, DataTypes) => {
  3. let Ban = sequelize.define('Ban', {
  4. canCreatePosts: {
  5. type: DataTypes.BOOLEAN,
  6. defaultValue: true,
  7. validate: {
  8. isBoolean (val) {
  9. if(typeof val !== 'boolean') {
  10. throw new sequelize.ValidationError('canCreateThreads must be a string')
  11. }
  12. }
  13. }
  14. },
  15. canCreateThreads: {
  16. type: DataTypes.BOOLEAN,
  17. defaultValue: true,
  18. validate: {
  19. isBoolean (val) {
  20. if(typeof val !== 'boolean') {
  21. throw new sequelize.ValidationError('canCreateThreads must be a string')
  22. }
  23. }
  24. }
  25. },
  26. message: {
  27. type: DataTypes.TEXT,
  28. validate: {
  29. isString (val) {
  30. if(typeof val !== 'string') {
  31. throw new sequelize.ValidationError('description must be a string')
  32. }
  33. },
  34. len: {
  35. args: [0, 1024],
  36. msg: 'message must be less than 1024 characters'
  37. }
  38. }
  39. }
  40. }, {
  41. classMethods: {
  42. associate (models) {
  43. Ban.belongsTo(models.User)
  44. },
  45. async getBanInstance (username) {
  46. let user = await sequelize.models.User.findOne({ where: { username } })
  47. let ban = await Ban.findOne({ where: { UserId: user.id } })
  48. return ban
  49. },
  50. async canCreatePosts (username) {
  51. let ban = await this.getBanInstance(username)
  52. if(ban && !ban.canCreatePosts) {
  53. throw Errors.sequelizeValidation(sequelize.Sequelize, {
  54. error: ban.message || 'You have been banned from posting'
  55. })
  56. } else {
  57. false
  58. }
  59. },
  60. async canCreateThreads (username) {
  61. let ban = await this.getBanInstance(username)
  62. if(ban && !ban.canCreateThreads) {
  63. throw Errors.sequelizeValidation(sequelize.Sequelize, {
  64. error: ban.message || 'You have been banned from creating threads'
  65. })
  66. } else {
  67. false
  68. }
  69. }
  70. }
  71. })
  72. return Ban
  73. }