From d1557bcae8abc45ea655d2fe0cdb6732a0207aa0 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 3 Mar 2017 19:39:41 +0900 Subject: wip --- src/api/endpoints/auth/accept.ts | 97 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/api/endpoints/auth/accept.ts (limited to 'src/api/endpoints/auth/accept.ts') diff --git a/src/api/endpoints/auth/accept.ts b/src/api/endpoints/auth/accept.ts new file mode 100644 index 0000000000..2c104ef1c6 --- /dev/null +++ b/src/api/endpoints/auth/accept.ts @@ -0,0 +1,97 @@ +'use strict'; + +/** + * Module dependencies + */ +import rndstr from 'rndstr'; +const crypto = require('crypto'); +import it from '../../it'; +import App from '../../models/app'; +import AuthSess from '../../models/auth-session'; +import AccessToken from '../../models/access-token'; + +/** + * @swagger + * /auth/accept: + * post: + * summary: Accept a session + * parameters: + * - $ref: "#/parameters/NativeToken" + * - + * name: token + * description: Session Token + * in: formData + * required: true + * type: string + * responses: + * 204: + * description: OK + * + * default: + * description: Failed + * schema: + * $ref: "#/definitions/Error" + */ + +/** + * Accept + * + * @param {any} params + * @param {any} user + * @return {Promise} + */ +module.exports = (params, user) => + new Promise(async (res, rej) => +{ + // Get 'token' parameter + const [token, tokenErr] = it(params.token).expect.string().required().qed(); + if (tokenErr) return rej('invalid token param'); + + // Fetch token + const session = await AuthSess + .findOne({ token: token }); + + if (session === null) { + return rej('session not found'); + } + + // Generate access token + const accessToken = rndstr('a-zA-Z0-9', 32); + + // Fetch exist access token + const exist = await AccessToken.findOne({ + app_id: session.app_id, + user_id: user._id, + }); + + if (exist === null) { + // Lookup app + const app = await App.findOne({ + _id: session.app_id + }); + + // Generate Hash + const sha256 = crypto.createHash('sha256'); + sha256.update(accessToken + app.secret); + const hash = sha256.digest('hex'); + + // Insert access token doc + await AccessToken.insert({ + created_at: new Date(), + app_id: session.app_id, + user_id: user._id, + token: accessToken, + hash: hash + }); + } + + // Update session + await AuthSess.update(session._id, { + $set: { + user_id: user._id + } + }); + + // Response + res(); +}); -- cgit v1.2.3-freya