zyket 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zyket",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "main": "index.js",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -4,7 +4,7 @@ const S3 = require("./s3");
4
4
  const { SocketIO } = require("./socketio");
5
5
 
6
6
  module.exports = [
7
- ["logger", require("./Logger"), ["@service_container", process.env.LOG_DIRECTORY || `${process.cwd()}/logs`, process.env.DEBUG === "true"]],
7
+ ["logger", require("./logger"), ["@service_container", process.env.LOG_DIRECTORY || `${process.cwd()}/logs`, process.env.DEBUG === "true"]],
8
8
  ["template-manager", require("./template-manager"), []],
9
9
  process.env.DATABASE_URL ? ["database", Database, ["@service_container", process.env.DATABASE_URL]] : null,
10
10
  process.env.CACHE_URL ? ["cache", Cache, ["@service_container", process.env.CACHE_URL]] : null,
@@ -50,6 +50,9 @@ module.exports = class TemplateManager extends Service {
50
50
  }
51
51
  }
52
52
 
53
+ uninstallTemplate(templateName) {
54
+ }
55
+
53
56
  getTemplates() {
54
57
  const uniqueTemplates = new Set();
55
58
  for (const template of Object.keys(this.templates)) {
@@ -0,0 +1,53 @@
1
+ module.exports = ({sequelize, container, Sequelize}) => {
2
+ const User = sequelize.define('user', {
3
+ id: {
4
+ type: Sequelize.UUID,
5
+ defaultValue: Sequelize.UUIDV4,
6
+ allowNull: false,
7
+ primaryKey: true
8
+ },
9
+ email: {
10
+ type: Sequelize.STRING,
11
+ allowNull: false
12
+ },
13
+ password: {
14
+ type: Sequelize.STRING,
15
+ allowNull: false
16
+ },
17
+ }, {
18
+ timestamps: true,
19
+ createdAt: 'created_at',
20
+ updatedAt: 'updated_at',
21
+ indexes: [
22
+ {
23
+ unique: true,
24
+ fields: ['email']
25
+ }
26
+ ]
27
+ });
28
+
29
+ User.associate = models => {
30
+ // User is associated to an application through ApplicationUser
31
+ User.belongsToMany(models.Application, {
32
+ through: models.ApplicationUser,
33
+ as: 'applications',
34
+ foreignKey: 'user_id',
35
+ otherKey: 'application_id'
36
+ });
37
+
38
+ User.addScope('defaultScope', {
39
+ attributes: { exclude: ['password'] },
40
+ include: [
41
+ {
42
+ model: models.Application,
43
+ as: 'applications',
44
+ through: { attributes: [] }
45
+ }
46
+ ]
47
+ });
48
+ }
49
+
50
+ require('./hooks/User')(User, container);
51
+
52
+ return User;
53
+ }
@@ -0,0 +1,46 @@
1
+ /* eslint-disable no-async-promise-executor */
2
+ const crypto = require('crypto')
3
+
4
+ module.exports = (User, container) => {
5
+ User.beforeCreate(async (user, options) => {
6
+ const salt = process.env.ENCRYPTION_SALT || ''
7
+ user.password = crypto.pbkdf2Sync(user.password, salt, 1000, 64, 'sha512').toString('hex')
8
+ })
9
+
10
+ /**
11
+ * Verify if the password is valid
12
+ * @param {string} password - The password to verify
13
+ * @returns {Boolean} - Boolean
14
+ */
15
+ User.prototype.isValidPassword = async function (password) {
16
+ const { User } = container.get('database').models
17
+ const user = await User.findByPk(this.id, {
18
+ attributes: ['password']
19
+ })
20
+ const hash = crypto.pbkdf2Sync(password, process.env.ENCRYPTION_SALT, 1000, 64, 'sha512').toString('hex')
21
+ return user.password === hash
22
+ }
23
+
24
+ User.prototype.generateAuthToken = async function () {
25
+ const token = crypto.randomBytes(32).toString('hex')
26
+ const cache = container.get('cache')
27
+ await cache.set(`auth:${token}`, JSON.stringify({
28
+ ...this.toJSON()
29
+ }))
30
+ await cache.expire(`auth:${token}`, 60 * 60 * 24 * 7)
31
+ return token
32
+ }
33
+
34
+ User.prototype.removeAuthToken = function (token) {
35
+ return new Promise((resolve, reject) => {
36
+ try {
37
+ const cache = container.get('cache')
38
+ cache.del(`auth:${token}`).then(() => {
39
+ resolve()
40
+ }).catch(err => reject(err))
41
+ } catch (err) {
42
+ reject(err)
43
+ }
44
+ })
45
+ }
46
+ }
@@ -0,0 +1,21 @@
1
+ const { Handler } = require("zyket");
2
+
3
+ module.exports = class LoginHandler extends Handler {
4
+ middleware = [];
5
+
6
+ async handle({ container, socket, data, io }) {
7
+ const {email, password} = data
8
+ const { User } = container.get('database').models
9
+ const user = await User.findOne({ where: { email } })
10
+
11
+ if(!user) return socket.emit("auth.login", { error: "User not found" })
12
+ if(!await user.isValidPassword(password)) return socket.emit("auth.login", { error: "Invalid password" })
13
+
14
+ const token = await user.generateAuthToken()
15
+
16
+ socket.user = user
17
+ socket.token = token
18
+
19
+ socket.emit("auth.login", { ...user.toJSON(), token })
20
+ }
21
+ };
@@ -0,0 +1,22 @@
1
+ const { Handler } = require("zyket");
2
+
3
+ module.exports = class LogoutHandler extends Handler {
4
+ middleware = [];
5
+
6
+ async handle({ container, socket, data, io }) {
7
+ if(!socket.user) return socket.emit('auth.logout', { error: 'Not authenticated' });
8
+ const { token } = socket;
9
+ if (!token) return socket.emit('auth.logout', { error: 'Not authenticated' });
10
+
11
+ const cache = container.get('cache');
12
+ const tokenData = await cache.get(`auth:${token}`);
13
+ if (!tokenData) return socket.emit('auth.logout', { error: 'Not authenticated' });
14
+
15
+ try {
16
+ await cache.del(`auth:${token}`);
17
+ socket.emit('auth.logout', { success: true });
18
+ } catch (error) {
19
+ socket.emit('auth.logout', { error: error.message });
20
+ }
21
+ }
22
+ };
@@ -0,0 +1,30 @@
1
+ const { Handler } = require("zyket");
2
+ const validator = require('validator');
3
+
4
+ module.exports = class RegisterHandler extends Handler {
5
+ middleware = [];
6
+
7
+ async handle({ container, socket, data, io }) {
8
+ const { email, password } = data;
9
+
10
+ if(!email) return socket.emit('auth.register', { error: 'Email is required' });
11
+ if(validator.isEmpty(email)) return socket.emit('auth.register', { error: 'Email is invalid' });
12
+ if(!validator.isEmail(email)) return socket.emit('auth.register', { error: 'Email is invalid' });
13
+
14
+ if(!password) return socket.emit('auth.register', { error: 'Password is required' });
15
+ if(validator.isEmpty(password)) return socket.emit('auth.register', { error: 'Password is invalid' });
16
+ if(!validator.isLength(password, { min: 6 })) return socket.emit('auth.register', { error: 'Password must be at least 6 characters' });
17
+
18
+ const { User } = container.get('database').models;
19
+
20
+ try {
21
+ await User.create({ email, password })
22
+ } catch (error) {
23
+ return socket.emit('auth.register', { error: 'Email already exists' });
24
+ }
25
+
26
+ const user = await User.findOne({ where: { email } });
27
+
28
+ socket.emit('auth.register', { user });
29
+ }
30
+ };