aboutsummaryrefslogtreecommitdiff
path: root/src/server/ApiManagers/GeneralGoogleManager.ts
blob: e8debfc1292c079c68b6a89f9452e364f39fe528 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import ApiManager, { Registration } from './ApiManager';
import { Method, _success } from '../RouteManager';
import { GoogleApiServerUtils } from '../apis/google/GoogleApiServerUtils';
import RouteSubscriber from '../RouteSubscriber';
import { Database } from '../database';
import { google } from 'googleapis';

const EndpointHandlerMap = new Map<GoogleApiServerUtils.Action, GoogleApiServerUtils.ApiRouter>([
    ['create', (api, params) => api.create(params)],
    ['retrieve', (api, params) => api.get(params)],
    ['update', (api, params) => api.batchUpdate(params)],
]);

export default class GeneralGoogleManager extends ApiManager {
    protected initialize(register: Registration): void {
        register({
            method: Method.GET,
            subscription: '/readGoogleAccessToken',
            secureHandler: async ({ user, res }) => {
                const { credentials } = await GoogleApiServerUtils.retrieveCredentials(user);
                if (!credentials?.access_token) {
                    const url = GoogleApiServerUtils.generateAuthenticationUrl();
                    return res.send(url);
                }
                return res.send(credentials);
            },
        });

        register({
            method: Method.POST,
            subscription: '/writeGoogleAccessToken',
            secureHandler: async ({ user, req, res }) => {
                res.send(await GoogleApiServerUtils.processNewUser(user.id, req.body.authenticationCode));
            },
        });

        register({
            method: Method.GET,
            subscription: '/revokeGoogleAccessToken',
            secureHandler: async ({ user, res }) => {
                await Database.Auxiliary.GoogleAccessToken.Revoke(user.id);
                res.send();
            },
        });

        register({
            method: Method.POST,
            subscription: new RouteSubscriber('googleDocs').add('sector', 'action'),
            secureHandler: async ({ req, res, user }) => {
                const sector: GoogleApiServerUtils.Service = req.params.sector as GoogleApiServerUtils.Service;
                const action: GoogleApiServerUtils.Action = req.params.action as GoogleApiServerUtils.Action;
                const endpoint = await GoogleApiServerUtils.GetEndpoint(GoogleApiServerUtils.Service[sector], user);
                const handler = EndpointHandlerMap.get(action);
                if (endpoint && handler) {
                    try {
                        const response = await handler(endpoint, req.body);
                        res.send(response.data);
                    } catch (e) {
                        res.send(e);
                    }
                    return;
                }
                res.send(undefined);
            },
        });

        // AARAV ADD (creating a task)

        register({
            method: Method.POST,
            subscription: new RouteSubscriber('googleTasks').add('create'),
            secureHandler: async ({ req, res, user }) => {
                try {
                    const { credentials } = await GoogleApiServerUtils.retrieveCredentials(user.id);
                    const access_token = user.googleToken || credentials?.access_token; // if googleToken expires, we need to renew it.

                    if (!access_token) {
                        return res.status(401).send('Google access token not found.');
                    }

                    const auth = new google.auth.OAuth2();
                    auth.setCredentials({ access_token: access_token });

                    const tasks = google.tasks({ version: 'v1', auth });

                    const { title, notes, due } = req.body;
                    const result = await tasks.tasks.insert({
                        tasklist: '@default',
                        requestBody: { title, notes, due },
                    });

                    res.status(200).send(result.data);
                } catch (err) {
                    console.error('Google Tasks error:', err);
                    res.status(500).send('Failed to create task.');
                }
            },
        });

        register({
            method: Method.GET,
            subscription: '/refreshGoogle',
            secureHandler: async ({ user, req, res }) => {
                const code = req.query.code as string;
                _success(res, code);
                user.googleToken = code;
                user.save();

                // const response2 = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode });
                // runInAction(() => {
                //     this.success = true;
                //     this.credentials = response2 as { user_info: { name: string; picture: string }; access_token: string };
                // });
            },
        });
    }
}