iceshrimp-legacy/src/api/endpoints/auth/accept.js

99 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
'use strict';
/**
* Module dependencies
*/
import rndstr from 'rndstr';
2017-01-06 03:50:46 +01:00
const crypto = require('crypto');
import App from '../../models/app';
2016-12-28 23:49:51 +01:00
import AuthSess from '../../models/auth-session';
import AccessToken from '../../models/access-token';
2016-12-28 23:49:51 +01:00
2017-01-05 17:28:59 +01:00
/**
* @swagger
* /auth/accept:
* post:
* summary: Accept a session
* parameters:
2017-01-06 07:13:46 +01:00
* - $ref: "#/parameters/NativeToken"
2017-03-01 09:37:01 +01:00
* -
2017-01-05 17:28:59 +01:00
* name: token
* description: Session Token
* in: formData
* required: true
* type: string
* responses:
* 204:
* description: OK
2017-03-01 09:37:01 +01:00
*
2017-01-05 17:28:59 +01:00
* default:
* description: Failed
* schema:
* $ref: "#/definitions/Error"
*/
2016-12-28 23:49:51 +01:00
/**
* Accept
*
2017-03-01 09:37:01 +01:00
* @param {any} params
* @param {any} user
* @return {Promise<any>}
2016-12-28 23:49:51 +01:00
*/
module.exports = (params, user) =>
new Promise(async (res, rej) =>
{
// Get 'token' parameter
const sesstoken = params.token;
if (sesstoken == null) {
2016-12-28 23:49:51 +01:00
return rej('token is required');
}
// Fetch token
const session = await AuthSess
.findOne({ token: sesstoken });
2016-12-28 23:49:51 +01:00
if (session === null) {
return rej('session not found');
}
// Generate access token
const token = rndstr('a-zA-Z0-9', 32);
2016-12-28 23:49:51 +01:00
// Fetch exist access token
const exist = await AccessToken.findOne({
2016-12-28 23:49:51 +01:00
app_id: session.app_id,
user_id: user._id,
});
if (exist === null) {
2017-01-06 03:50:46 +01:00
// Lookup app
const app = await App.findOne({
2017-01-26 15:29:55 +01:00
_id: session.app_id
2017-01-06 03:50:46 +01:00
});
// Generate Hash
2017-02-08 14:43:46 +01:00
const sha256 = crypto.createHash('sha256');
sha256.update(token + app.secret);
const hash = sha256.digest('hex');
2017-01-06 03:50:46 +01:00
// Insert access token doc
await AccessToken.insert({
2016-12-28 23:49:51 +01:00
created_at: new Date(),
app_id: session.app_id,
user_id: user._id,
token: token,
2017-01-06 03:50:46 +01:00
hash: hash
2016-12-28 23:49:51 +01:00
});
}
// Update session
2017-01-17 03:11:22 +01:00
await AuthSess.update(session._id, {
2017-02-08 17:34:22 +01:00
$set: {
user_id: user._id
}
2016-12-28 23:49:51 +01:00
});
// Response
res();
});