trashposs/src/api/endpoints/auth/session/userkey.js

116 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
'use strict';
/**
* Module dependencies
*/
import App from '../../../models/app';
import AuthSess from '../../../models/auth-session';
import AccessToken from '../../../models/access-token';
2016-12-28 23:49:51 +01:00
import serialize from '../../../serializers/user';
/**
* @swagger
* /auth/session/userkey:
* post:
2017-02-23 16:28:43 +01:00
* summary: Get an access token(userkey)
* parameters:
* -
* name: app_secret
* description: App Secret
* in: formData
* required: true
* type: string
* -
* name: token
2017-01-05 15:42:27 +01:00
* description: Session Token
* in: formData
* required: true
* type: string
2017-02-23 16:28:18 +01:00
*
* responses:
* 200:
* description: OK
* schema:
* type: object
* properties:
* userkey:
* type: string
2017-01-06 07:13:46 +01:00
* description: Access Token
* user:
* $ref: "#/definitions/User"
2017-01-05 16:39:56 +01:00
* default:
* description: Failed
* schema:
* $ref: "#/definitions/Error"
*/
2016-12-28 23:49:51 +01:00
/**
* Generate a session
*
2017-03-01 09:37:01 +01:00
* @param {any} params
* @return {Promise<any>}
2016-12-28 23:49:51 +01:00
*/
module.exports = (params) =>
2017-02-23 16:28:18 +01:00
new Promise(async (res, rej) => {
// Get 'app_secret' parameter
const appSecret = params.app_secret;
if (appSecret == null) {
return rej('app_secret is required');
}
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
// Lookup app
const app = await App.findOne({
secret: appSecret
});
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
if (app == null) {
return rej('app not found');
}
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
// Get 'token' parameter
const token = params.token;
if (token == null) {
return rej('token is required');
}
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
// Fetch token
const session = await AuthSess
.findOne({
token: token,
app_id: app._id
});
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
if (session === null) {
return rej('session not found');
}
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
if (session.user_id == null) {
return rej('this session is not allowed yet');
}
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
// Lookup access token
const accessToken = await AccessToken.findOne({
app_id: app._id,
user_id: session.user_id
});
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
// Delete session
2017-02-08 18:15:34 +01:00
2017-02-23 16:28:18 +01:00
/* https://github.com/Automattic/monk/issues/178
AuthSess.deleteOne({
_id: session._id
});
*/
AuthSess.remove({
_id: session._id
});
2016-12-28 23:49:51 +01:00
2017-02-23 16:28:18 +01:00
// Response
res({
access_token: accessToken.token,
user: await serialize(session.user_id, null, {
detail: true
})
});
2016-12-28 23:49:51 +01:00
});