@semapps/auth 0.4.0-alpha.2 → 0.4.0-alpha.22

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/index.js CHANGED
@@ -4,5 +4,6 @@ module.exports = {
4
4
  AuthOIDCService: require('./services/auth.oidc'),
5
5
  AuthAccountService: require('./services/account'),
6
6
  AuthJWTService: require('./services/jwt'),
7
- AuthMigrationService: require('./services/migration')
7
+ AuthMigrationService: require('./services/migration'),
8
+ AuthMailService: require('./services/mail')
8
9
  };
package/mixins/auth.js CHANGED
@@ -1,7 +1,8 @@
1
+ const passport = require('passport');
2
+ const { Errors: E } = require('moleculer-web');
3
+ const { TripleStoreAdapter } = require('@semapps/triplestore');
1
4
  const AuthAccountService = require('../services/account');
2
5
  const AuthJWTService = require('../services/jwt');
3
- const { Errors: E } = require('moleculer-web');
4
- const passport = require('passport');
5
6
 
6
7
  const AuthMixin = {
7
8
  settings: {
@@ -9,18 +10,21 @@ const AuthMixin = {
9
10
  jwtPath: null,
10
11
  registrationAllowed: true,
11
12
  reservedUsernames: [],
12
- webIdSelection: []
13
+ webIdSelection: [],
14
+ accountSelection: [],
15
+ accountsDataset: 'settings'
13
16
  },
14
17
  dependencies: ['api', 'webid'],
15
18
  async created() {
16
- const { jwtPath, reservedUsernames } = this.settings;
19
+ const { jwtPath, reservedUsernames, accountsDataset } = this.settings;
17
20
 
18
21
  await this.broker.createService(AuthJWTService, {
19
22
  settings: { jwtPath }
20
23
  });
21
24
 
22
25
  await this.broker.createService(AuthAccountService, {
23
- settings: { reservedUsernames }
26
+ settings: { reservedUsernames },
27
+ adapter: new TripleStoreAdapter({ type: 'AuthAccount', dataset: accountsDataset })
24
28
  });
25
29
  },
26
30
  async started() {
@@ -108,6 +112,15 @@ const AuthMixin = {
108
112
  } else {
109
113
  return data;
110
114
  }
115
+ },
116
+ pickAccountData(data) {
117
+ if (this.settings.accountSelection.length > 0) {
118
+ return Object.fromEntries(
119
+ this.settings.accountSelection.filter(key => key in data).map(key => [key, data[key]])
120
+ );
121
+ } else {
122
+ return data || {};
123
+ }
111
124
  }
112
125
  }
113
126
  };
@@ -32,25 +32,29 @@ const AuthSSOMixin = {
32
32
  newUser = false;
33
33
 
34
34
  // TODO update account with recent information
35
- // await this.broker.call('webid.edit', profileData, { meta: { webId } });
35
+ // await ctx.call('webid.edit', profileData, { meta: { webId } });
36
36
 
37
- await this.broker.emit('auth.connected', { webId, accountData });
37
+ ctx.emit('auth.connected', { webId, accountData, ssoData }, { meta: { webId: null, dataset: null } });
38
38
  } else {
39
39
  if (!this.settings.registrationAllowed) {
40
40
  throw new Error('registration.not-allowed');
41
41
  }
42
42
 
43
43
  accountData = await ctx.call('auth.account.create', { uuid: profileData.uuid, email: profileData.email });
44
- webId = await ctx.call('webid.create', { nick: accountData.username, ...profileData });
44
+ webId = await ctx.call('webid.create', this.pickWebIdData({ nick: accountData.username, ...profileData }));
45
45
  newUser = true;
46
46
 
47
47
  // Link the webId with the account
48
48
  await ctx.call('auth.account.attachWebId', { accountUri: accountData['@id'], webId });
49
49
 
50
- ctx.emit('auth.registered', { webId, profileData, accountData }, { meta: { webId: null, dataset: null } });
50
+ ctx.emit(
51
+ 'auth.registered',
52
+ { webId, profileData, accountData, ssoData },
53
+ { meta: { webId: null, dataset: null } }
54
+ );
51
55
  }
52
56
 
53
- const token = await ctx.call('auth.jwt.generateToken', { payload: { webId: accountData.webId } });
57
+ const token = await ctx.call('auth.jwt.generateToken', { payload: { webId } });
54
58
 
55
59
  return { token, newUser };
56
60
  }
package/package.json CHANGED
@@ -1,26 +1,28 @@
1
1
  {
2
2
  "name": "@semapps/auth",
3
- "version": "0.4.0-alpha.2",
3
+ "version": "0.4.0-alpha.22",
4
4
  "description": "Authentification module for SemApps",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Virtual Assembly",
7
7
  "dependencies": {
8
- "@semapps/mime-types": "0.4.0-alpha.2",
9
- "@semapps/triplestore": "0.4.0-alpha.2",
8
+ "@semapps/mime-types": "0.4.0-alpha.22",
9
+ "@semapps/triplestore": "0.4.0-alpha.22",
10
10
  "bcrypt": "^5.0.1",
11
11
  "express-session": "^1.17.0",
12
12
  "jsonwebtoken": "^8.5.1",
13
13
  "moleculer": "^0.14.17",
14
14
  "moleculer-db": "^0.8.16",
15
15
  "moleculer-web": "^0.10.0-beta1",
16
+ "node-sass": "^7.0.1",
16
17
  "openid-client": "^4.7.4",
17
18
  "passport": "^0.4.1",
18
- "passport-cas2": "0.0.11",
19
+ "passport-cas2": "0.0.12",
19
20
  "passport-local": "^1.0.0",
21
+ "pug": "^3.0.2",
20
22
  "url-join": "^4.0.1"
21
23
  },
22
24
  "publishConfig": {
23
25
  "access": "public"
24
26
  },
25
- "gitHead": "abf3d7f33a8864817adff5f1f529ff19f80cad90"
27
+ "gitHead": "e7b59751e1808d50cd8e6b7a7c8995a8e9357b66"
26
28
  }
@@ -1,6 +1,7 @@
1
1
  const bcrypt = require('bcrypt');
2
2
  const DbService = require('moleculer-db');
3
3
  const { TripleStoreAdapter } = require('@semapps/triplestore');
4
+ const crypto = require('crypto');
4
5
 
5
6
  module.exports = {
6
7
  name: 'auth.account',
@@ -13,9 +14,11 @@ module.exports = {
13
14
  dependencies: ['triplestore'],
14
15
  actions: {
15
16
  async create(ctx) {
16
- let { uuid, username, password, email, webId } = ctx.params;
17
+ let { uuid, username, password, email, webId, ...rest } = ctx.params;
17
18
  const hashedPassword = password ? await this.hashPassword(password) : undefined;
18
19
 
20
+ email = email && email.toLowerCase();
21
+
19
22
  const emailExists = await ctx.call('auth.account.emailExists', { email });
20
23
  if (emailExists) {
21
24
  throw new Error('email.already.exists');
@@ -36,6 +39,7 @@ module.exports = {
36
39
  }
37
40
 
38
41
  return await this._create(ctx, {
42
+ ...rest,
39
43
  uuid,
40
44
  username,
41
45
  email,
@@ -54,11 +58,10 @@ module.exports = {
54
58
  async verify(ctx) {
55
59
  const { username, password } = ctx.params;
56
60
 
57
- const accounts = await this._find(ctx, {
58
- query: {
59
- username
60
- }
61
- });
61
+ // If the username includes a @, assume it is an email
62
+ const query = username.includes('@') ? { email: username } : { username };
63
+
64
+ const accounts = await this._find(ctx, { query });
62
65
 
63
66
  if (accounts.length > 0) {
64
67
  const passwordMatch = await this.comparePassword(password, accounts[0].hashedPassword);
@@ -86,21 +89,53 @@ module.exports = {
86
89
  const accounts = await this._find(ctx, { query: { webId } });
87
90
  return accounts.length > 0 ? accounts[0] : null;
88
91
  },
92
+ async findByEmail(ctx) {
93
+ const { email } = ctx.params;
94
+ const accounts = await this._find(ctx, { query: { email } });
95
+ return accounts.length > 0 ? accounts[0] : null;
96
+ },
89
97
  async setPassword(ctx) {
90
98
  const { webId, password } = ctx.params;
91
99
  const hashedPassword = await this.hashPassword(password);
92
100
  const account = await ctx.call('auth.account.findByWebId', { webId });
93
101
 
94
102
  return await this._update(ctx, {
95
- '@id': account.id,
103
+ '@id': account['@id'],
96
104
  hashedPassword
97
105
  });
106
+ },
107
+ async setNewPassword(ctx) {
108
+ const { webId, token, password } = ctx.params;
109
+ const hashedPassword = await this.hashPassword(password);
110
+ const account = await ctx.call('auth.account.findByWebId', { webId });
111
+
112
+ if (account.resetPasswordToken !== token) {
113
+ throw new Error('auth.password.invalid_reset_token');
114
+ }
115
+
116
+ return await this._update(ctx, {
117
+ '@id': account['@id'],
118
+ hashedPassword,
119
+ resetPasswordToken: undefined
120
+ });
121
+ },
122
+ async generateResetPasswordToken(ctx) {
123
+ const { webId } = ctx.params;
124
+ const resetPasswordToken = await this.generateResetPasswordToken();
125
+ const account = await ctx.call('auth.account.findByWebId', { webId });
126
+
127
+ await this._update(ctx, {
128
+ '@id': account['@id'],
129
+ resetPasswordToken
130
+ });
131
+
132
+ return resetPasswordToken;
98
133
  }
99
134
  },
100
135
  methods: {
101
136
  async isValidUsername(ctx, username) {
102
137
  // Ensure the username has no space or special characters
103
- if (!/^[a-zA-Z0-9\-_.]+$/.exec(username)) {
138
+ if (!/^[a-z0-9\-+_.]+$/.exec(username)) {
104
139
  throw new Error('username.invalid');
105
140
  }
106
141
 
@@ -136,6 +171,16 @@ module.exports = {
136
171
  }
137
172
  });
138
173
  });
174
+ },
175
+ async generateResetPasswordToken() {
176
+ return new Promise(resolve => {
177
+ crypto.randomBytes(32, function(ex, buf) {
178
+ if (ex) {
179
+ reject(ex);
180
+ }
181
+ resolve(buf.toString('hex'));
182
+ });
183
+ });
139
184
  }
140
185
  }
141
186
  };
@@ -2,6 +2,7 @@ const { Strategy } = require('passport-local');
2
2
  const AuthMixin = require('../mixins/auth');
3
3
  const sendToken = require('../middlewares/sendToken');
4
4
  const { MoleculerError } = require('moleculer').Errors;
5
+ const AuthMailService = require('../services/mail');
5
6
 
6
7
  const AuthLocalService = {
7
8
  name: 'auth',
@@ -11,18 +12,43 @@ const AuthLocalService = {
11
12
  jwtPath: null,
12
13
  registrationAllowed: true,
13
14
  reservedUsernames: [],
14
- webIdSelection: []
15
+ webIdSelection: [],
16
+ accountSelection: [],
17
+ mail: {
18
+ from: null,
19
+ transport: {
20
+ host: null,
21
+ port: null
22
+ },
23
+ defaults: {
24
+ locale: null,
25
+ frontUrl: null
26
+ }
27
+ }
15
28
  },
16
- created() {
29
+ async created() {
30
+ const { mail } = this.settings;
31
+
17
32
  this.passportId = 'local';
33
+
34
+ await this.broker.createService(AuthMailService, {
35
+ settings: {
36
+ ...mail
37
+ }
38
+ });
18
39
  },
19
40
  actions: {
20
41
  async signup(ctx) {
21
- const { username, email, password, ...otherData } = ctx.params;
42
+ const { username, email, password, ...rest } = ctx.params;
22
43
 
23
- let accountData = await ctx.call('auth.account.create', { username, email, password });
44
+ let accountData = await ctx.call('auth.account.create', {
45
+ username,
46
+ email,
47
+ password,
48
+ ...this.pickAccountData(rest)
49
+ });
24
50
 
25
- const profileData = { nick: username, email, ...otherData };
51
+ const profileData = { nick: username, email, ...rest };
26
52
  const webId = await ctx.call('webid.create', this.pickWebIdData(profileData));
27
53
 
28
54
  // Link the webId with the account
@@ -44,6 +70,33 @@ const AuthLocalService = {
44
70
  const token = await ctx.call('auth.jwt.generateToken', { payload: { webId: accountData.webId } });
45
71
 
46
72
  return { token, webId: accountData.webId, newUser: true };
73
+ },
74
+ async resetPassword(ctx) {
75
+ const { email } = ctx.params;
76
+
77
+ const account = await ctx.call('auth.account.findByEmail', { email });
78
+
79
+ if (!account) {
80
+ throw new Error('email.not.exists');
81
+ }
82
+
83
+ const token = await ctx.call('auth.account.generateResetPasswordToken', { webId: account.webId });
84
+
85
+ await ctx.call('auth.mail.sendResetPasswordEmail', {
86
+ account,
87
+ token
88
+ });
89
+ },
90
+ async setNewPassword(ctx) {
91
+ const { email, token, password } = ctx.params;
92
+
93
+ const account = await ctx.call('auth.account.findByEmail', { email });
94
+
95
+ if (!account) {
96
+ throw new Error('email.not.exists');
97
+ }
98
+
99
+ await ctx.call('auth.account.setNewPassword', { webId: account.webId, token, password });
47
100
  }
48
101
  },
49
102
  methods: {
@@ -83,10 +136,23 @@ const AuthLocalService = {
83
136
  }
84
137
  };
85
138
 
139
+ const resetPasswordRoute = {
140
+ path: '/auth/reset_password',
141
+ aliases: {
142
+ 'POST /': 'auth.resetPassword'
143
+ }
144
+ };
145
+ const setNewPasswordRoute = {
146
+ path: '/auth/new_password',
147
+ aliases: {
148
+ 'POST /': 'auth.setNewPassword'
149
+ }
150
+ };
151
+
86
152
  if (this.settings.registrationAllowed) {
87
- return [loginRoute, signupRoute];
153
+ return [loginRoute, signupRoute, resetPasswordRoute, setNewPasswordRoute];
88
154
  } else {
89
- return [loginRoute];
155
+ return [loginRoute, resetPasswordRoute, setNewPasswordRoute];
90
156
  }
91
157
  }
92
158
  }
package/services/jwt.js CHANGED
@@ -14,6 +14,9 @@ module.exports = {
14
14
 
15
15
  if (!fs.existsSync(privateKeyPath) && !fs.existsSync(publicKeyPath)) {
16
16
  console.log('JWT keypair not found, generating...');
17
+ if (!fs.existsSync(this.settings.jwtPath)) {
18
+ fs.mkdirSync(this.settings.jwtPath);
19
+ }
17
20
  await this.actions.generateKeyPair({ privateKeyPath, publicKeyPath });
18
21
  }
19
22
 
@@ -0,0 +1,49 @@
1
+ const MailService = require('moleculer-mail');
2
+ const path = require('path');
3
+
4
+ module.exports = {
5
+ name: 'auth.mail',
6
+ mixins: [MailService],
7
+ settings: {
8
+ defaults: {
9
+ locale: 'en',
10
+ frontUrl: null
11
+ },
12
+ templateFolder: path.join(__dirname, '../templates'),
13
+ from: null,
14
+ transport: null
15
+ },
16
+ actions: {
17
+ async sendResetPasswordEmail(ctx) {
18
+ const { account, token } = ctx.params;
19
+
20
+ await this.actions.send(
21
+ {
22
+ to: account.email,
23
+ template: 'reset-password',
24
+ locale: this.getTemplateLocale(account.preferredLocale || this.settings.defaults.locale),
25
+ data: {
26
+ account,
27
+ token,
28
+ frontUrl: account.preferredFrontUrl || this.settings.defaults.frontUrl
29
+ }
30
+ },
31
+ {
32
+ parentCtx: ctx
33
+ }
34
+ );
35
+ }
36
+ },
37
+ methods: {
38
+ getTemplateLocale(userLocale) {
39
+ switch (userLocale) {
40
+ case 'fr':
41
+ return 'fr-FR';
42
+ case 'en':
43
+ return 'en-EN';
44
+ default:
45
+ return 'en-EN';
46
+ }
47
+ }
48
+ }
49
+ };
@@ -1,4 +1,5 @@
1
1
  const { MIME_TYPES } = require('@semapps/mime-types');
2
+ const { getSlugFromUri } = require('@semapps/ldp');
2
3
 
3
4
  module.exports = {
4
5
  name: 'auth.migration',
@@ -13,7 +14,7 @@ module.exports = {
13
14
  try {
14
15
  await ctx.call('auth.account.create', {
15
16
  email: user[emailPredicate],
16
- username: user[usernamePredicate],
17
+ username: usernamePredicate ? user[usernamePredicate] : getSlugFromUri(user.id),
17
18
  webId: user.id
18
19
  });
19
20
  } catch (e) {
@@ -0,0 +1 @@
1
+ Password reset for {{account.username}} account
@@ -0,0 +1,7 @@
1
+ Hello {{account.username}},
2
+
3
+ In order to reset your password, please click on the link below:
4
+
5
+ {{frontUrl}}/login?new_password=true&token={{token}}
6
+
7
+ If you did not request a password reset, please ignore this message.
@@ -0,0 +1 @@
1
+ Réinitialisation du mot de passe du compte {{account.username}}
@@ -0,0 +1,7 @@
1
+ Bonjour {{account.username}},
2
+
3
+ Pour réinitialiser votre mot de passe, veuillez cliquer sur le lien ci-dessous:
4
+
5
+ {{frontUrl}}/login?new_password=true&token={{token}}
6
+
7
+ Si vous n'avez pas fait une telle demande, vous pouvez ignorer ce message.