All files / src/controllers auth.js

92.59% Statements 50/54
48.28% Branches 14/29
96.97% Functions 32/33
92.59% Lines 50/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292  1x 1x 1x                             136x   136x       65x       41x 5x 36x 35x   1x                     16x       15x     1x                   1x       1x       1x                       1x         1x                   1x       1x                     1x       1x                 1x     1x                   1x       1x                   1x     1x                   1x     1x                         3x             3x   3x 3x   3x           3x                           2x       2x                         1x         1x                     1x       1x                       1x         1x                   2x         2x   2x   2x         1x  
const
  Jwt = require('../core/Jwt'),
  BaseController = require('./base'),
  User = require('./security/user');
 
/**
 * Auth controller
 *
 * @param kuzzle
 * @constructor
 */
class AuthController extends BaseController {
 
  /**
   * constructor
   * @param kuzzle
   */
  constructor (kuzzle) {
    super(kuzzle, 'auth');
 
    this._authenticationToken = null;
  }
 
  get authenticationToken () {
    return this._authenticationToken;
  }
 
  set authenticationToken (encodedJwt) {
    if (encodedJwt === undefined || encodedJwt === null) {
      this._authenticationToken = null;
    } else if (typeof encodedJwt === 'string') {
      this._authenticationToken = new Jwt(encodedJwt);
    } else {
      throw new Error(`Invalid token argument: ${encodedJwt}`);
    }
  }
 
  /**
   * Do not add the token for the checkToken route, to avoid getting a token error when
   * a developer simply wish to verify his token
   *
   * @param {object} request
   */
  authenticateRequest (request) {
    if ( !this.authenticationToken
      || (request.controller === 'auth'
      && (request.action === 'checkToken' || request.action === 'login'))
    ) {
      return;
    }
 
    request.jwt = this.authenticationToken.encodedJwt;
  }
 
  /**
   * Checks whether a given jwt token still represents a valid session in Kuzzle.
   *
   * @param  {string}   token     The jwt token to check
   * @return {Promise|*|PromiseLike<T>|Promise<T>}
   */
  checkToken (token) {
    Iif (token === undefined && this.authenticationToken) {
      token = this.authenticationToken.encodedJwt;
    }
 
    return this.query({
      action: 'checkToken',
      body: { token }
    }, { queuable: false })
      .then(response => response.result);
  }
 
  /**
   * Create credentials of the specified <strategy> for the current user.
   *
   * @param credentials
   * @param strategy
   * @param options
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  createMyCredentials (strategy, credentials, options = {}) {
    return this.query({
      strategy,
      action: 'createMyCredentials',
      body: credentials
    }, options)
      .then(response => response.result);
  }
 
  /**
   * Check the existence of the specified <strategy>'s credentials for the current user.
   *
   * @param strategy
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  credentialsExist (strategy, options = {}) {
    return this.query({
      strategy,
      action: 'credentialsExist'
    }, options)
      .then(response => response.result);
  }
 
  /**
   * Delete credentials of the specified <strategy> for the current user.
   *
   * @param strategy
   * @param options
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  deleteMyCredentials (strategy, options = {}) {
    return this.query({
      strategy,
      action: 'deleteMyCredentials'
    }, options)
      .then(response => response.result.acknowledged);
  }
 
  /**
   * Fetches the current user.
   *
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  getCurrentUser (options = {}) {
    return this.query({
      action: 'getCurrentUser'
    }, options)
      .then(response => new User(this.kuzzle, response.result._id, response.result._source));
  }
 
  /**
   * Get credential information of the specified <strategy> for the current user.
   *
   * @param strategy
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  getMyCredentials(strategy, options = {}) {
    return this.query({
      strategy,
      action: 'getMyCredentials'
    }, options)
      .then(response => response.result);
  }
 
  /**
   * Gets the rights array of the currently logged user.
   *
   * @param {object} [options] - Optional parameters
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  getMyRights (options = {}) {
    return this.query({
      action: 'getMyRights'
    }, options)
      .then(response => response.result.hits);
  }
 
  /**
   * Get all the strategies registered in Kuzzle by all auth plugins
   *
   * @param {object} [options] - Optional parameters
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  getStrategies (options = {}) {
    return this.query({
      action: 'getStrategies'
    }, options)
      .then(response => response.result);
  }
 
  /**
   * Send login request to kuzzle with credentials
   * If login success, store the jwt into kuzzle object
   *
   * @param strategy
   * @param credentials
   * @param expiresIn
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  login (strategy, credentials = {}, expiresIn = null) {
    const request = {
      strategy,
      expiresIn,
      body: credentials,
      action: 'login'
    };
 
    return this.query(request, {queuable: false})
      .then(response => {
        try {
          this._authenticationToken = new Jwt(response.result.jwt);
 
          this.kuzzle.emit('loginAttempt', {success: true});
        }
        catch (err) {
          return Promise.reject(err);
        }
 
        return response.result.jwt;
      })
      .catch(err => {
        this.kuzzle.emit('loginAttempt', {success: false, error: err.message});
        throw err;
      });
  }
 
  /**
   * Send logout request to kuzzle with jwt.
   *
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  logout () {
    return this.query({
      action: 'logout'
    }, {queuable: false})
      .then(() => {
        this._authenticationToken = null;
      });
  }
 
  /**
   * Update credentials of the specified <strategy> for the current user.
   *
   * @param strategy
   * @param credentals
   * @param options
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  updateMyCredentials (strategy, credentials, options = {}) {
    return this.query({
      strategy,
      body: credentials,
      action: 'updateMyCredentials'
    }, options)
      .then(response => response.result);
  }
 
  /**
   * Update current user in Kuzzle.
   *
   * @param {object} body - a plain javascript object representing the user's modification
   * @param {object} [options] - (optional) arguments
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  updateSelf (body, options = {}) {
    return this.query({
      body,
      action: 'updateSelf'
    }, options)
      .then(response => new User(this.kuzzle, response.result._id, response.result._source));
  }
 
  /**
   * Validate credentials of the specified <strategy> for the current user.
   *
   * @param strategy
   * @param credentials
   * @param options
   * @returns {Promise|*|PromiseLike<T>|Promise<T>}
   */
  validateMyCredentials (strategy, credentials, options = {}) {
    return this.query({
      strategy,
      body: credentials,
      action: 'validateMyCredentials'
    }, options)
      .then(response => response.result);
  }
 
  /**
   * Refresh an authentication token
   *
   * @param {Object} options
   * @returns {Promise.<Object>}
   */
  refreshToken(options = {}) {
    const query = {
      action: 'refreshToken',
      expiresIn: options.expiresIn
    };
 
    return this.query(query, options)
      .then(response => {
        this._authenticationToken = new Jwt(response.result.jwt);
 
        return response.result;
      });
  }
}
 
module.exports = AuthController;