Skip to content

Commit

Permalink
Create token api with tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
pallavi2209 committed Dec 1, 2016
1 parent 4b87a1b commit ecff29a
Show file tree
Hide file tree
Showing 10 changed files with 170 additions and 160 deletions.
53 changes: 25 additions & 28 deletions api/v1/controllers/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,52 +7,49 @@
*/

/**
* api/v1/controllers/apiaccess.js
* api/v1/controllers/token.js
*/

const configuredPassport = require('../../../index').passportModule;
const httpStatus = require('../constants').httpStatus;
const u = require('../helpers/verbs/utils');
const apiErrors = require('../apiErrors');
const jwtUtil = require('../../../utils/jwtUtil');
const helper = require('../helpers/nouns/tokens');

const resourceName = 'token';

module.exports = {

/**
* Authenticates user and sends token in response with status code 200
* if authenticated else responds with error.
* Authenticates user using provided token and creates new token with given
* name. Saves created token to db and sends token in response with status
* code 201 if token craeted, else responds with error.
* @param {IncomingMessage} req - The request object
* @param {ServerResponse} res - The response object
* @param {Function} next - The next middleware function in the stack
*
*/

// this endpoint will be replaced with new create token endpoint.
postToken(req, res, next) {
configuredPassport.authenticate('local-login', (err, user/* , info */) => {
if (err) {
return u.handleError(next, err, resourceName);
}

if (!user || !user.name) {
const loginErr = new apiErrors.LoginError({
explanation: 'Invalid credentials.',
});
loginErr.resource = resourceName;
return u.handleError(next, loginErr, resourceName);
}

// just changing this to pass tests for now.
const createdToken = jwtUtil.createToken(user.name, user.name);

return res.status(httpStatus.OK).json({
success: true,
message: 'Enjoy your token!',
token: createdToken,
if (!req.user || !req.user.name) {
const tokenErr = new apiErrors.LoginError({
explanation: 'Token not provided.',
});
})(req, res, next);
tokenErr.resource = resourceName;
return u.handleError(next, tokenErr, resourceName);
}

const tokenName = req.swagger.params.queryBody.value.name;

const tokenValue = jwtUtil.createToken(tokenName, req.user.name);
return helper.model.create({
name: tokenName,
createdby: req.user.id,
})
.then((createdToken) => {
const tokenObj = u.responsify(createdToken, helper, req.method);
tokenObj.token = tokenValue;
return res.status(httpStatus.CREATED).json(tokenObj);
})
.catch((err) => u.handleError(next, err, helper.modelName));
},

}; // exports
2 changes: 0 additions & 2 deletions api/v1/helpers/nouns/tokens.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ module.exports = {
apiLinks: {
DELETE: `Delete this ${m}`,
GET: `Retrieve this ${m}`,
PATCH: `Update selected attributes of this ${m}`,
POST: `Create a new ${m}`,
PUT: `Overwrite all attributes of this ${m}`,
},
baseUrl: '/v1/tokens',
model: Token,
Expand Down
77 changes: 53 additions & 24 deletions api/v1/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4470,11 +4470,17 @@ paths:
/token:
x-swagger-router-controller: token
post:
summary: Create an api access token
security:
- jwt: []
summary: Create a new api access token
tags: [ token ]
description: >-
Authenticate a user with email and password and create an api access
token.
Create a new api access token by providing a token in header. You may
also optionally specify a list of fields to include in the response.
If the Refocus configuration parameter `useAccessToken` is set to
`true`, you must include an `Authorization` request header with your
[JSON Web Token](https://tools.ietf.org/html/rfc7519) (JWT) as the
value. You can get a token using `POST /v1/register` or `POST /v1/token`.
operationId: postToken
parameters:
-
Expand All @@ -4484,33 +4490,40 @@ paths:
schema:
type: object
description: >
Credentials of person who interacts with the Refocus system.
Name of token.
properties:
email:
name:
type: string
maxLength: 254
description: >
The user's email address.
password:
type: string
format: password
description: >
The user's password.
The name of token. Token name should be unique for a user.
required:
- email
- password
- name
responses:
200:
description: >-
Success, returns a token.
201:
description: Token created.
schema:
$ref: "#/definitions/TokenResponse"
400:
$ref: "#/responses/400"
401:
description: >-
Caller did not supply credentials or did not provide the correct
credentials. If you are using an API key, it may be invalid or your
Authorization header may be malformed.
schema:
$ref: '#/definitions/AuthenticationError'
403:
$ref: "#/responses/403"
description: >-
Caller is not authorized to create token. While your authentication
is valid, the authenticated user or token does not have permission
to perform this action.
schema:
$ref: '#/definitions/ErrorResponse'
default:
$ref: "#/responses/genericError"
description: >-
An unexpected error occurred. Please review the response for error
details.
schema:
$ref: '#/definitions/ErrorResponse'
# =============================================================================
definitions:

Expand Down Expand Up @@ -5500,17 +5513,33 @@ definitions:
Success:
type: boolean
readOnly: true
message:
id:
type: string
isDisabled:
type: string
readOnly: true
maxLength: 2082
description: >
API access message.
name:
type: string
readOnly: true
description:
Name of token.
token:
type: string
readOnly: true
description: >
API token.
createdBy:
readOnly: true
type: string
description: >
TODO
apiLinks:
readOnly: true
type: array
items:
$ref: "#/definitions/HATEOAS"
description: >
Hypertext As The Engine Of Application State.
AuthenticationResponse:
type: object
Expand Down
36 changes: 13 additions & 23 deletions tests/api/v1/globalconfig/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@ const tu = require('../../../testUtils');
const u = require('./utils');
const path = '/v1/globalconfig';
const expect = require('chai').expect;
const jwtUtil = require('../../../../utils/jwtUtil');

describe(`api: DELETE ${path}`, () => {
let testUserToken;
let predefinedAdminUserToken;
let token;
const predefinedAdminUserToken = jwtUtil.createToken(
adminUser.name, adminUser.name
);

before((done) => {
tu.createToken()
Expand Down Expand Up @@ -51,31 +54,18 @@ describe(`api: DELETE ${path}`, () => {
done(err);
} else {
testUserToken = res.body.token;
api.post('/v1/token')
api.post(path)
.set('Authorization', predefinedAdminUserToken)
.send({
username: adminUser.name,
email: adminUser.name,
password: adminUser.password,
key: `${tu.namePrefix}_GLOBAL_CONFIG_ABC`,
value: 'def',
})
.end((err2, res2) => {
if (err2) {
done(err2);
.expect(constants.httpStatus.CREATED)
.end((err3 /* , res3*/) => {
if (err3) {
done(err3);
} else {
predefinedAdminUserToken = res2.body.token;
api.post(path)
.set('Authorization', predefinedAdminUserToken)
.send({
key: `${tu.namePrefix}_GLOBAL_CONFIG_ABC`,
value: 'def',
})
.expect(constants.httpStatus.CREATED)
.end((err3, res3) => {
if (err3) {
done(err3);
} else {
done();
}
});
done();
}
});
}
Expand Down
32 changes: 11 additions & 21 deletions tests/api/v1/globalconfig/get.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@ const tu = require('../../../testUtils');
const u = require('./utils');
const path = '/v1/globalconfig';
const expect = require('chai').expect;
const jwtUtil = require('../../../../utils/jwtUtil');

describe(`api: GET ${path}`, () => {
let testUserToken;
let predefinedAdminUserToken;
let token;
const predefinedAdminUserToken = jwtUtil.createToken(
adminUser.name, adminUser.name
);

before((done) => {
tu.createToken()
Expand Down Expand Up @@ -51,28 +54,15 @@ describe(`api: GET ${path}`, () => {
done(err);
} else {
testUserToken = res.body.token;
api.post('/v1/token')
api.post(path)
.set('Authorization', predefinedAdminUserToken)
.send({
username: adminUser.name,
email: adminUser.name,
password: adminUser.password,
key: `${tu.namePrefix}_GLOBAL_CONFIG_ABC`,
value: 'def',
})
.end((err2, res2) => {
if (err2) {
done(err2);
} else {
predefinedAdminUserToken = res2.body.token;
api.post(path)
.set('Authorization', predefinedAdminUserToken)
.send({
key: `${tu.namePrefix}_GLOBAL_CONFIG_ABC`,
value: 'def',
})
.expect(constants.httpStatus.CREATED)
.end((err3, res3) => {
done();
});
}
.expect(constants.httpStatus.CREATED)
.end((err3, res3) => {
done();
});
}
});
Expand Down
32 changes: 11 additions & 21 deletions tests/api/v1/globalconfig/patch.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@ const tu = require('../../../testUtils');
const u = require('./utils');
const path = '/v1/globalconfig';
const expect = require('chai').expect;
const jwtUtil = require('../../../../utils/jwtUtil');

describe(`api: PATCH ${path}`, () => {
let testUserToken;
let predefinedAdminUserToken;
let token;
const predefinedAdminUserToken = jwtUtil.createToken(
adminUser.name, adminUser.name
);

before((done) => {
tu.createToken()
Expand Down Expand Up @@ -51,28 +54,15 @@ describe(`api: PATCH ${path}`, () => {
done(err);
} else {
testUserToken = res.body.token;
api.post('/v1/token')
api.post(path)
.set('Authorization', predefinedAdminUserToken)
.send({
username: adminUser.name,
email: adminUser.name,
password: adminUser.password,
key: `${tu.namePrefix}_GLOBAL_CONFIG_ABC`,
value: 'def',
})
.end((err2, res2) => {
if (err2) {
done(err2);
} else {
predefinedAdminUserToken = res2.body.token;
api.post(path)
.set('Authorization', predefinedAdminUserToken)
.send({
key: `${tu.namePrefix}_GLOBAL_CONFIG_ABC`,
value: 'def',
})
.expect(constants.httpStatus.CREATED)
.end((err3, res3) => {
//
});
}
.expect(constants.httpStatus.CREATED)
.end((err3, res3) => {
//
});
done();
}
Expand Down

0 comments on commit ecff29a

Please sign in to comment.