Sharkey/src/server/api/endpoints/sw/register.ts

57 lines
1 KiB
TypeScript
Raw Normal View History

2017-11-20 20:40:09 +02:00
import $ from 'cafy';
2018-03-29 14:32:18 +03:00
import Subscription from '../../../../models/sw-subscription';
2018-06-18 03:54:53 +03:00
import { ILocalUser } from '../../../../models/user';
2018-09-01 02:13:18 +03:00
import config from '../../../../config';
2018-11-02 05:49:08 +02:00
import getParams from '../../get-params';
2017-11-20 20:40:09 +02:00
2018-07-16 22:36:44 +03:00
export const meta = {
2018-11-02 05:49:08 +02:00
requireCredential: true,
2018-07-16 22:36:44 +03:00
2018-11-02 05:49:08 +02:00
params: {
endpoint: {
validator: $.str
},
auth: {
validator: $.str
},
2017-11-20 20:40:09 +02:00
2018-11-02 05:49:08 +02:00
publickey: {
validator: $.str
}
}
};
2017-11-20 20:40:09 +02:00
2018-11-02 05:49:08 +02:00
export default async (params: any, user: ILocalUser) => new Promise(async (res, rej) => {
const [ps, psErr] = getParams(meta, params);
if (psErr) return rej(psErr);
2017-11-20 20:40:09 +02:00
// if already subscribed
const exist = await Subscription.findOne({
2018-03-29 08:48:47 +03:00
userId: user._id,
2018-11-02 05:49:08 +02:00
endpoint: ps.endpoint,
auth: ps.auth,
publickey: ps.publickey,
2018-03-29 08:48:47 +03:00
deletedAt: { $exists: false }
2017-11-20 20:40:09 +02:00
});
2018-09-01 02:13:18 +03:00
if (exist != null) {
return res({
state: 'already-subscribed',
key: config.sw.public_key
});
2017-11-20 20:40:09 +02:00
}
await Subscription.insert({
2018-03-29 08:48:47 +03:00
userId: user._id,
2018-11-02 05:49:08 +02:00
endpoint: ps.endpoint,
auth: ps.auth,
publickey: ps.publickey
2017-11-20 20:40:09 +02:00
});
2018-09-01 02:13:18 +03:00
res({
state: 'subscribed',
key: config.sw.public_key
});
2017-11-20 20:40:09 +02:00
});