forked from prismicio/javascript-nodejs-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprismic-helpers.js
More file actions
144 lines (122 loc) · 4.54 KB
/
prismic-helpers.js
File metadata and controls
144 lines (122 loc) · 4.54 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
var Prismic = require('prismic.io').Prismic,
Configuration = require('./prismic-configuration').Configuration,
http = require('http'),
https = require('https'),
url = require('url'),
querystring = require('querystring');
// -- Helpers
exports.getApiHome = function(accessToken, callback) {
Prismic.Api(Configuration.apiEndpoint, callback, accessToken);
};
exports.getDocument = function(ctx, id, slug, onSuccess, onNewSlug, onNotFound) {
ctx.api.forms('everything').ref(ctx.ref).query('[[:d = at(document.id, "' + id + '")]]').submit(function(err, documents) {
var results = documents.results;
var doc = results && results.length ? results[0] : undefined;
if (err) onSuccess(err);
else if(doc && (!slug || doc.slug == slug)) onSuccess(null, doc)
else if(doc && doc.slugs.indexOf(slug) > -1 && onNewSlug) onNewSlug(doc)
else if(onNotFound) onNotFound()
else onSuccess();
});
};
exports.getDocuments = function(ctx, ids, callback) {
if(ids && ids.length) {
ctx.api.forms('everything').ref(ctx.ref).query('[[:d = any(document.id, [' + ids.map(function(id) { return '"' + id + '"';}).join(',') + '])]]').submit(function(err, documents) {
callback(err, documents.results);
});
} else {
callback(null, []);
}
};
exports.getBookmark = function(ctx, bookmark, callback) {
var id = ctx.api.bookmarks[bookmark];
if(id) {
exports.getDocument(ctx, id, undefined, callback);
} else {
callback();
}
};
// -- Exposing as a helper what to do in the event of an error (please edit prismic-configuration.js to change this)
exports.onPrismicError = Configuration.onPrismicError;
// -- Route wrapper that provide a "prismic context" to the underlying function
exports.route = function(callback) {
return function(req, res) {
var accessToken = (req.session && req.session['ACCESS_TOKEN']) || Configuration.accessToken || undefined
exports.getApiHome(accessToken, function(err, Api) {
if (err) { exports.onPrismicError(err, req, res); return; }
var ref = req.query['ref'] || Api.master(),
ctx = {
api: Api,
ref: ref,
maybeRef: ref == Api.master() ? undefined : ref,
oauth: function() {
var token = accessToken;
return {
accessToken: token,
hasPrivilegedAccess: !!token
}
},
linkResolver: function(ctx, doc) {
return Configuration.linkResolver(ctx, doc);
}
};
res.locals.ctx = ctx;
callback(req, res, ctx);
});
};
};
// -- OAuth routes
var redirectUri = function(req) {
return req.protocol + '://' + req.get('Host') + '/auth_callback';
};
exports.signin = function(req, res) {
exports.getApiHome(undefined, function(err, Api) {
if (err) { exports.onPrismicError(err, req, res); return; }
var endpointSpec = url.parse(Api.data.oauthInitiate);
endpointSpec.query = endpointSpec.query || {};
endpointSpec.query['client_id'] = Configuration.clientId;
endpointSpec.query['redirect_uri'] = redirectUri(req);
endpointSpec.query['scope'] = 'master+releases';
res.redirect(301, url.format(endpointSpec));
});
};
exports.authCallback = function(req, res) {
exports.getApiHome(undefined, function(err, Api) {
if (err) { exports.onPrismicError(err, req, res); return; }
var endpointSpec = url.parse(Api.data.oauthToken),
h = endpointSpec.protocol == 'https:' ? https : http,
postData = querystring.stringify({
'grant_type' : 'authorization_code',
'code': req.query['code'],
'redirect_uri': redirectUri(req),
'client_id': Configuration.clientId,
'client_secret': Configuration.clientSecret
});
var postOptions = endpointSpec;
postOptions.method = 'POST';
postOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
};
var postRequest = h.request(postOptions, function(response) {
var jsonStr = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
jsonStr += chunk;
});
response.on('end', function () {
var accessToken = JSON.parse(jsonStr)['access_token'];
if(accessToken) {
req.session['ACCESS_TOKEN'] = accessToken;
}
res.redirect(301, '/');
});
});
postRequest.write(postData);
postRequest.end();
});
};
exports.signout = function(req, res) {
delete req.session['ACCESS_TOKEN'];
res.redirect(301, '/');
};