How to use authenticate method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_authenticator.py

Source: test_authenticator.py Github

copy
1# encoding: utf-8
2
3import ckan
4
5import ckan.lib.create_test_data as ctd
6import ckan.lib.authenticator as authenticator
7
8CreateTestData = ctd.CreateTestData
9
10
11class TestUsernamePasswordAuthenticator(object):
12    @classmethod
13    def setup_class(cls):
14        auth = authenticator.UsernamePasswordAuthenticator()
15        cls.authenticate = auth.authenticate
16
17    @classmethod
18    def teardown(cls):
19        ckan.model.repo.rebuild_db()
20
21    def test_authenticate_succeeds_if_login_and_password_are_correct(self):
22        environ = {}
23        password = 'somepass'
24        user = CreateTestData.create_user('a_user', **{'password': password})
25        identity = {'login': user.name, 'password': password}
26
27        username = self.authenticate(environ, identity)
28        assert username == user.name, username
29
30    def test_authenticate_fails_if_user_is_deleted(self):
31        environ = {}
32        password = 'somepass'
33        user = CreateTestData.create_user('a_user', **{'password': password})
34        identity = {'login': user.name, 'password': password}
35        user.delete()
36
37        assert self.authenticate(environ, identity) is None
38
39    def test_authenticate_fails_if_user_is_pending(self):
40        environ = {}
41        password = 'somepass'
42        user = CreateTestData.create_user('a_user', **{'password': password})
43        identity = {'login': user.name, 'password': password}
44        user.set_pending()
45
46        assert self.authenticate(environ, identity) is None
47
48    def test_authenticate_fails_if_password_is_wrong(self):
49        environ = {}
50        user = CreateTestData.create_user('a_user')
51        identity = {'login': user.name, 'password': 'wrong-password'}
52        assert self.authenticate(environ, identity) is None
53
54    def test_authenticate_fails_if_received_no_login_or_pass(self):
55        environ = {}
56        identity = {}
57        assert self.authenticate(environ, identity) is None
58
59    def test_authenticate_fails_if_received_just_login(self):
60        environ = {}
61        identity = {'login': 'some-user'}
62        assert self.authenticate(environ, identity) is None
63
64    def test_authenticate_fails_if_received_just_password(self):
65        environ = {}
66        identity = {'password': 'some-password'}
67        assert self.authenticate(environ, identity) is None
68
69    def test_authenticate_fails_if_user_doesnt_exist(self):
70        environ = {}
71        identity = {'login': 'inexistent-user'}
72        assert self.authenticate(environ, identity) is None
73
Full Screen

SettingsTab.py

Source: SettingsTab.py Github

copy
1import wx
2from com.petroSoft.gui.custom.LabelText import LabelText
3from com.petroSoft.gui.custom.AskPassword import AskPwd
4from com.petroSoft.Delegate import Delegate
5from functools import partial
6from com.petroSoft.Constants import constants
7
8c=constants()
9class AuthenticatePanel:
10    def createAuthenticatePanel(self,parent):
11        authenticatePanel=wx.Panel(parent, c.defaultId, size=(800, 600))
12        authenticatePanel.authenticateLabel=wx.StaticText(authenticatePanel,c.defaultId,c.AUTHENTICATE,(50,50))
13        authenticatePanel.pwdLabelText=LabelText(c.PWDLABEL, (50,80), authenticatePanel,wx.TE_LINEWRAP)
14
15        authenticatePanel.loginButton=wx.Button(authenticatePanel,1,c.SUBMIT,(50, 130))
16        authenticatePanel.loginFailedTxt=wx.StaticText(authenticatePanel,c.defaultId,c.LOGINFAILEDLABEL,(50,160))
17        authenticatePanel.loginFailedTxt.Show(False)
18        authenticatePanel.isValid=False
19
20        return  authenticatePanel
21
22
23
24class InitPanel:
25    def createInitPanel(self,parent):
26        initPanel=wx.Panel(parent, c.defaultId, size=(800, 600))
27        initPanel.priceButton=wx.Button(initPanel,1,c.EDIT_PRICE_LABEL,(50, 130))
28        initPanel.Bind(wx.EVT_BUTTON, partial(self.OnEditPrice,initPanel),id=1)
29        return initPanel
30
31    def OnEditPrice(self,initPanel,event):
32        dial = wx.MessageDialog(None, 'Are you sure to edit current petrol and diesel price?', 'Question', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
33        ret=dial.ShowModal()
34        if ret==wx.ID_YES:
35            print 'yes'
36            print ret
37        else:
38            print 'no'
39
40
41class SettingsTab:
42    def createSettingsTab(self, noteBook):
43
44        settingsPanel= wx.Panel(noteBook, c.defaultId, size=(500, 500))
45        hbox=wx.BoxSizer(wx.HORIZONTAL)
46        settingsPanel.initPanel=InitPanel().createInitPanel(settingsPanel)
47        hbox.Add(settingsPanel.initPanel)
48        settingsPanel.authenticatePanel=AuthenticatePanel().createAuthenticatePanel(settingsPanel)
49        hbox.Add(settingsPanel.authenticatePanel)
50        settingsPanel.authenticatePanel.Bind(wx.EVT_BUTTON,partial(self.OnClick,settingsPanel.authenticatePanel,settingsPanel.initPanel))
51        settingsPanel.Bind(wx.EVT_SET_FOCUS,partial(self.OnFocus,settingsPanel.authenticatePanel,settingsPanel.initPanel))
52        settingsPanel.SetSizer(hbox)
53        settingsPanel.initPanel.Show(False)
54        return  settingsPanel
55    def OnClick(self,authenticatePanel,initPanel,event):
56        obj =Delegate()
57        isValid=obj.authenticate(authenticatePanel.pwdLabelText.getValue())
58        if isValid :
59            authenticatePanel.Show(False)
60            initPanel.Show(True)
61        else:
62            authenticatePanel.loginFailedTxt.Show(True)
63    def OnFocus(self,authenticatePanel,initPanel,event):
64        authenticatePanel.Show(True)
65        initPanel.Show(False)
66        
Full Screen

routes.js

Source: routes.js Github

copy
1var express = require('express'),
2    // This essentially provides the controllers for the routes
3    api = require('../../api'),
4
5    // Middleware
6    mw = require('./middleware'),
7
8    // API specific
9    auth = require('../../auth'),
10    cors = require('../middleware/api/cors'),
11    brute = require('../middleware/brute'),
12
13    // Handling uploads & imports
14    tmpdir = require('os').tmpdir,
15    upload = require('multer')({dest: tmpdir()}),
16    validation = require('../middleware/validation'),
17
18    // Temporary
19    // @TODO find a more appy way to do this!
20    labs = require('../middleware/labs');
21
22// @TODO refactor/clean this up - how do we want the routing to work long term?
23module.exports = function apiRoutes() {
24    var apiRouter = express.Router();
25
26    // alias delete with del
27    apiRouter.del = apiRouter.delete;
28
29    // ## CORS pre-flight check
30    apiRouter.options('*', cors);
31
32    // ## Configuration
33    apiRouter.get('/configuration', api.http(api.configuration.read));
34    apiRouter.get('/configuration/:key', mw.authenticatePrivate, api.http(api.configuration.read));
35
36    // ## Posts
37    apiRouter.get('/posts', mw.authenticatePublic, api.http(api.posts.browse));
38
39    apiRouter.post('/posts', mw.authenticatePrivate, api.http(api.posts.add));
40    apiRouter.get('/posts/:id', mw.authenticatePublic, api.http(api.posts.read));
41    apiRouter.get('/posts/slug/:slug', mw.authenticatePublic, api.http(api.posts.read));
42    apiRouter.put('/posts/:id', mw.authenticatePrivate, api.http(api.posts.edit));
43    apiRouter.del('/posts/:id', mw.authenticatePrivate, api.http(api.posts.destroy));
44
45    // ## Schedules
46    apiRouter.put('/schedules/posts/:id', [
47        auth.authenticate.authenticateClient,
48        auth.authenticate.authenticateUser
49    ], api.http(api.schedules.publishPost));
50
51    // ## Settings
52    apiRouter.get('/settings', mw.authenticatePrivate, api.http(api.settings.browse));
53    apiRouter.get('/settings/:key', mw.authenticatePrivate, api.http(api.settings.read));
54    apiRouter.put('/settings', mw.authenticatePrivate, api.http(api.settings.edit));
55
56    // ## Users
57    apiRouter.get('/users', mw.authenticatePublic, api.http(api.users.browse));
58    apiRouter.get('/users/:id', mw.authenticatePublic, api.http(api.users.read));
59    apiRouter.get('/users/slug/:slug', mw.authenticatePublic, api.http(api.users.read));
60    // NOTE: We don't expose any email addresses via the public api.
61    apiRouter.get('/users/email/:email', mw.authenticatePrivate, api.http(api.users.read));
62
63    apiRouter.put('/users/password', mw.authenticatePrivate, api.http(api.users.changePassword));
64    apiRouter.put('/users/owner', mw.authenticatePrivate, api.http(api.users.transferOwnership));
65    apiRouter.put('/users/:id', mw.authenticatePrivate, api.http(api.users.edit));
66    apiRouter.del('/users/:id', mw.authenticatePrivate, api.http(api.users.destroy));
67
68    // ## Tags
69    apiRouter.get('/tags', mw.authenticatePublic, api.http(api.tags.browse));
70    apiRouter.get('/tags/:id', mw.authenticatePublic, api.http(api.tags.read));
71    apiRouter.get('/tags/slug/:slug', mw.authenticatePublic, api.http(api.tags.read));
72    apiRouter.post('/tags', mw.authenticatePrivate, api.http(api.tags.add));
73    apiRouter.put('/tags/:id', mw.authenticatePrivate, api.http(api.tags.edit));
74    apiRouter.del('/tags/:id', mw.authenticatePrivate, api.http(api.tags.destroy));
75
76    // ## Subscribers
77    apiRouter.get('/subscribers', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.browse));
78    apiRouter.get('/subscribers/csv', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.exportCSV));
79    apiRouter.post('/subscribers/csv',
80        labs.subscribers,
81        mw.authenticatePrivate,
82        upload.single('subscribersfile'),
83        validation.upload({type: 'subscribers'}),
84        api.http(api.subscribers.importCSV)
85    );
86    apiRouter.get('/subscribers/:id', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.read));
87    apiRouter.get('/subscribers/email/:email', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.read));
88    apiRouter.post('/subscribers', labs.subscribers, mw.authenticatePublic, api.http(api.subscribers.add));
89    apiRouter.put('/subscribers/:id', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.edit));
90    apiRouter.del('/subscribers/:id', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.destroy));
91    apiRouter.del('/subscribers/email/:email', labs.subscribers, mw.authenticatePrivate, api.http(api.subscribers.destroy));
92
93    // ## Roles
94    apiRouter.get('/roles/', mw.authenticatePrivate, api.http(api.roles.browse));
95
96    // ## Clients
97    apiRouter.get('/clients/slug/:slug', api.http(api.clients.read));
98
99    // ## Slugs
100    apiRouter.get('/slugs/:type/:name', mw.authenticatePrivate, api.http(api.slugs.generate));
101
102    // ## Themes
103    apiRouter.get('/themes/', mw.authenticatePrivate, api.http(api.themes.browse));
104
105    apiRouter.get('/themes/:name/download',
106        mw.authenticatePrivate,
107        api.http(api.themes.download)
108    );
109
110    apiRouter.post('/themes/upload',
111        mw.authenticatePrivate,
112        upload.single('theme'),
113        validation.upload({type: 'themes'}),
114        api.http(api.themes.upload)
115    );
116
117    apiRouter.put('/themes/:name/activate',
118        mw.authenticatePrivate,
119        api.http(api.themes.activate)
120    );
121
122    apiRouter.del('/themes/:name',
123        mw.authenticatePrivate,
124        api.http(api.themes.destroy)
125    );
126
127    // ## Notifications
128    apiRouter.get('/notifications', mw.authenticatePrivate, api.http(api.notifications.browse));
129    apiRouter.post('/notifications', mw.authenticatePrivate, api.http(api.notifications.add));
130    apiRouter.del('/notifications/:id', mw.authenticatePrivate, api.http(api.notifications.destroy));
131
132    // ## DB
133    apiRouter.get('/db', mw.authenticatePrivate, api.http(api.db.exportContent));
134    apiRouter.post('/db',
135        mw.authenticatePrivate,
136        upload.single('importfile'),
137        validation.upload({type: 'db'}),
138        api.http(api.db.importContent)
139    );
140    apiRouter.del('/db', mw.authenticatePrivate, api.http(api.db.deleteAllContent));
141
142    // ## Mail
143    apiRouter.post('/mail', mw.authenticatePrivate, api.http(api.mail.send));
144    apiRouter.post('/mail/test', mw.authenticatePrivate, api.http(api.mail.sendTest));
145
146    // ## Slack
147    apiRouter.post('/slack/test', mw.authenticatePrivate, api.http(api.slack.sendTest));
148
149    // ## Authentication
150    apiRouter.post('/authentication/passwordreset',
151        brute.globalReset,
152        brute.userReset,
153        api.http(api.authentication.generateResetToken)
154    );
155    apiRouter.put('/authentication/passwordreset', brute.globalBlock, api.http(api.authentication.resetPassword));
156    apiRouter.post('/authentication/invitation', api.http(api.authentication.acceptInvitation));
157    apiRouter.get('/authentication/invitation', api.http(api.authentication.isInvitation));
158    apiRouter.post('/authentication/setup', api.http(api.authentication.setup));
159    apiRouter.put('/authentication/setup', mw.authenticatePrivate, api.http(api.authentication.updateSetup));
160    apiRouter.get('/authentication/setup', api.http(api.authentication.isSetup));
161    apiRouter.post('/authentication/token',
162        brute.globalBlock,
163        brute.userLogin,
164        auth.authenticate.authenticateClient,
165        auth.oauth.generateAccessToken
166    );
167
168    apiRouter.post('/authentication/revoke', mw.authenticatePrivate, api.http(api.authentication.revoke));
169
170    // ## Uploads
171    // @TODO: rename endpoint to /images/upload (or similar)
172    apiRouter.post('/uploads',
173        mw.authenticatePrivate,
174        upload.single('uploadimage'),
175        validation.upload({type: 'images'}),
176        api.http(api.uploads.add)
177    );
178
179    apiRouter.post('/db/backup',  mw.authenticateClient('Ghost Backup'), api.http(api.db.backupContent));
180
181    apiRouter.post('/uploads/icon',
182        mw.authenticatePrivate,
183        upload.single('uploadimage'),
184        validation.upload({type: 'icons'}),
185        validation.blogIcon(),
186        api.http(api.uploads.add)
187    );
188
189    // ## Invites
190    apiRouter.get('/invites', mw.authenticatePrivate, api.http(api.invites.browse));
191    apiRouter.get('/invites/:id', mw.authenticatePrivate, api.http(api.invites.read));
192    apiRouter.post('/invites', mw.authenticatePrivate, api.http(api.invites.add));
193    apiRouter.del('/invites/:id', mw.authenticatePrivate, api.http(api.invites.destroy));
194
195    // ## Redirects (JSON based)
196    apiRouter.get('/redirects/json', mw.authenticatePrivate, api.http(api.redirects.download));
197    apiRouter.post('/redirects/json',
198        mw.authenticatePrivate,
199        upload.single('redirects'),
200        validation.upload({type: 'redirects'}),
201        api.http(api.redirects.upload)
202    );
203
204    // ## Webhooks (RESTHooks)
205    apiRouter.post('/webhooks', mw.authenticatePrivate, api.http(api.webhooks.add));
206    apiRouter.del('/webhooks/:id', mw.authenticatePrivate, api.http(api.webhooks.destroy));
207
208    return apiRouter;
209};
210
Full Screen

middleware.js

Source: middleware.js Github

copy
1var prettyURLs = require('../middleware/pretty-urls'),
2    cors = require('../middleware/api/cors'),
3    urlRedirects = require('../middleware/url-redirects'),
4    auth = require('../../auth');
5
6/**
7 * Auth Middleware Packages
8 *
9 * IMPORTANT
10 * - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost on redirect
11 * - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains
12 * - url redirects MUST happen after cors, otherwise cors header can get lost on redirect
13 */
14
15/**
16 * Authentication for public endpoints
17 */
18module.exports.authenticatePublic = [
19    auth.authenticate.authenticateClient,
20    auth.authenticate.authenticateUser,
21    // This is a labs-enabled middleware
22    auth.authorize.requiresAuthorizedUserPublicAPI,
23    cors,
24    urlRedirects,
25    prettyURLs
26];
27
28/**
29 * Authentication for private endpoints
30 */
31module.exports.authenticatePrivate = [
32    auth.authenticate.authenticateClient,
33    auth.authenticate.authenticateUser,
34    auth.authorize.requiresAuthorizedUser,
35    cors,
36    urlRedirects,
37    prettyURLs
38];
39
40/**
41 * Authentication for client endpoints
42 */
43module.exports.authenticateClient = function authenticateClient(client) {
44    return [
45        auth.authenticate.authenticateClient,
46        auth.authenticate.authenticateUser,
47        auth.authorize.requiresAuthorizedClient(client),
48        cors,
49        urlRedirects,
50        prettyURLs
51    ];
52};
53
Full Screen

app.js

Source: app.js Github

copy
1// # API routes
2var debug = require('debug')('ghost:api'),
3    express = require('express'),
4    tmpdir = require('os').tmpdir,
5
6    // This essentially provides the controllers for the routes
7    api = require('../api'),
8
9    // Include the middleware
10
11    // API specific
12    auth = require('../auth'),
13    cors = require('../middleware/api/cors'),   // routes only?!
14    brute = require('../middleware/brute'),  // routes only
15    versionMatch = require('../middleware/api/version-match'), // global
16
17    // Handling uploads & imports
18    upload = require('multer')({dest: tmpdir()}), // routes only
19    validation = require('../middleware/validation'), // routes only
20
21    // Shared
22    bodyParser = require('body-parser'), // global, shared
23    cacheControl = require('../middleware/cache-control'), // global, shared
24    urlRedirects = require('../middleware/url-redirects'),
25    prettyURLs = require('../middleware/pretty-urls'),
26    maintenance = require('../middleware/maintenance'), // global, shared
27    errorHandler = require('../middleware/error-handler'), // global, shared
28
29    // Temporary
30    // @TODO find a more appy way to do this!
31    labs = require('../middleware/labs'),
32
33    /**
34     * Authentication for public endpoints
35     * @TODO find a better way to bundle these authentication packages
36     *
37     * IMPORTANT
38     * - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost
39     * - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains
40     */
41    authenticatePublic = [
42        auth.authenticate.authenticateClient,
43        auth.authenticate.authenticateUser,
44        auth.authorize.requiresAuthorizedUserPublicAPI,
45        cors,
46        prettyURLs
47    ],
48    // Require user for private endpoints
49    authenticatePrivate = [
50        auth.authenticate.authenticateClient,
51        auth.authenticate.authenticateUser,
52        auth.authorize.requiresAuthorizedUser,
53        cors,
54        prettyURLs
55    ];
56
57// @TODO refactor/clean this up - how do we want the routing to work long term?
58function apiRoutes() {
59    var apiRouter = express.Router();
60
61    // alias delete with del
62    apiRouter.del = apiRouter.delete;
63
64    // ## CORS pre-flight check
65    apiRouter.options('*', cors);
66
67    // ## Configuration
68    apiRouter.get('/configuration', api.http(api.configuration.read));
69    apiRouter.get('/configuration/:key', authenticatePrivate, api.http(api.configuration.read));
70    apiRouter.get('/configuration/timezones', authenticatePrivate, api.http(api.configuration.read));
71
72    // ## Posts
73    apiRouter.get('/posts', authenticatePublic, api.http(api.posts.browse));
74
75    apiRouter.post('/posts', authenticatePrivate, api.http(api.posts.add));
76    apiRouter.get('/posts/:id', authenticatePublic, api.http(api.posts.read));
77    apiRouter.get('/posts/slug/:slug', authenticatePublic, api.http(api.posts.read));
78    apiRouter.put('/posts/:id', authenticatePrivate, api.http(api.posts.edit));
79    apiRouter.del('/posts/:id', authenticatePrivate, api.http(api.posts.destroy));
80
81    // ## Schedules
82    apiRouter.put('/schedules/posts/:id', [
83        auth.authenticate.authenticateClient,
84        auth.authenticate.authenticateUser
85    ], api.http(api.schedules.publishPost));
86
87    // ## Settings
88    apiRouter.get('/settings', authenticatePrivate, api.http(api.settings.browse));
89    apiRouter.get('/settings/:key', authenticatePrivate, api.http(api.settings.read));
90    apiRouter.put('/settings', authenticatePrivate, api.http(api.settings.edit));
91
92    // ## Users
93    apiRouter.get('/users', authenticatePublic, api.http(api.users.browse));
94    apiRouter.get('/users/:id', authenticatePublic, api.http(api.users.read));
95    apiRouter.get('/users/slug/:slug', authenticatePublic, api.http(api.users.read));
96    apiRouter.get('/users/email/:email', authenticatePublic, api.http(api.users.read));
97
98    apiRouter.put('/users/password', authenticatePrivate, api.http(api.users.changePassword));
99    apiRouter.put('/users/owner', authenticatePrivate, api.http(api.users.transferOwnership));
100    apiRouter.put('/users/:id', authenticatePrivate, api.http(api.users.edit));
101
102    apiRouter.post('/users', authenticatePrivate, api.http(api.users.add));
103    apiRouter.del('/users/:id', authenticatePrivate, api.http(api.users.destroy));
104
105    // ## Tags
106    apiRouter.get('/tags', authenticatePublic, api.http(api.tags.browse));
107    apiRouter.get('/tags/:id', authenticatePublic, api.http(api.tags.read));
108    apiRouter.get('/tags/slug/:slug', authenticatePublic, api.http(api.tags.read));
109    apiRouter.post('/tags', authenticatePrivate, api.http(api.tags.add));
110    apiRouter.put('/tags/:id', authenticatePrivate, api.http(api.tags.edit));
111    apiRouter.del('/tags/:id', authenticatePrivate, api.http(api.tags.destroy));
112
113    // ## Subscribers
114    apiRouter.get('/subscribers', labs.subscribers, authenticatePrivate, api.http(api.subscribers.browse));
115    apiRouter.get('/subscribers/csv', labs.subscribers, authenticatePrivate, api.http(api.subscribers.exportCSV));
116    apiRouter.post('/subscribers/csv',
117        labs.subscribers,
118        authenticatePrivate,
119        upload.single('subscribersfile'),
120        validation.upload({type: 'subscribers'}),
121        api.http(api.subscribers.importCSV)
122    );
123    apiRouter.get('/subscribers/:id', labs.subscribers, authenticatePrivate, api.http(api.subscribers.read));
124    apiRouter.post('/subscribers', labs.subscribers, authenticatePublic, api.http(api.subscribers.add));
125    apiRouter.put('/subscribers/:id', labs.subscribers, authenticatePrivate, api.http(api.subscribers.edit));
126    apiRouter.del('/subscribers/:id', labs.subscribers, authenticatePrivate, api.http(api.subscribers.destroy));
127
128    // ## Roles
129    apiRouter.get('/roles/', authenticatePrivate, api.http(api.roles.browse));
130
131    // ## Clients
132    apiRouter.get('/clients/slug/:slug', api.http(api.clients.read));
133
134    // ## Slugs
135    apiRouter.get('/slugs/:type/:name', authenticatePrivate, api.http(api.slugs.generate));
136
137    // ## Themes
138    apiRouter.get('/themes/', authenticatePrivate, api.http(api.themes.browse));
139
140    apiRouter.get('/themes/:name/download',
141        authenticatePrivate,
142        api.http(api.themes.download)
143    );
144
145    apiRouter.post('/themes/upload',
146        authenticatePrivate,
147        upload.single('theme'),
148        validation.upload({type: 'themes'}),
149        api.http(api.themes.upload)
150    );
151
152    apiRouter.put('/themes/:name/activate',
153        authenticatePrivate,
154        api.http(api.themes.activate)
155    );
156
157    apiRouter.del('/themes/:name',
158        authenticatePrivate,
159        api.http(api.themes.destroy)
160    );
161
162    // ## Notifications
163    apiRouter.get('/notifications', authenticatePrivate, api.http(api.notifications.browse));
164    apiRouter.post('/notifications', authenticatePrivate, api.http(api.notifications.add));
165    apiRouter.del('/notifications/:id', authenticatePrivate, api.http(api.notifications.destroy));
166
167    // ## DB
168    apiRouter.get('/db', authenticatePrivate, api.http(api.db.exportContent));
169    apiRouter.post('/db',
170        authenticatePrivate,
171        upload.single('importfile'),
172        validation.upload({type: 'db'}),
173        api.http(api.db.importContent)
174    );
175    apiRouter.del('/db', authenticatePrivate, api.http(api.db.deleteAllContent));
176
177    // ## Mail
178    apiRouter.post('/mail', authenticatePrivate, api.http(api.mail.send));
179    apiRouter.post('/mail/test', authenticatePrivate, api.http(api.mail.sendTest));
180
181    // ## Slack
182    apiRouter.post('/slack/test', authenticatePrivate, api.http(api.slack.sendTest));
183
184    // ## Authentication
185    apiRouter.post('/authentication/passwordreset',
186        brute.globalReset,
187        brute.userReset,
188        api.http(api.authentication.generateResetToken)
189    );
190    apiRouter.put('/authentication/passwordreset', brute.globalBlock, api.http(api.authentication.resetPassword));
191    apiRouter.post('/authentication/invitation', api.http(api.authentication.acceptInvitation));
192    apiRouter.get('/authentication/invitation', api.http(api.authentication.isInvitation));
193    apiRouter.post('/authentication/setup', api.http(api.authentication.setup));
194    apiRouter.put('/authentication/setup', authenticatePrivate, api.http(api.authentication.updateSetup));
195    apiRouter.get('/authentication/setup', api.http(api.authentication.isSetup));
196    apiRouter.post('/authentication/token',
197        brute.globalBlock,
198        brute.userLogin,
199        auth.authenticate.authenticateClient,
200        auth.oauth.generateAccessToken
201    );
202
203    apiRouter.post('/authentication/revoke', authenticatePrivate, api.http(api.authentication.revoke));
204
205    // ## Uploads
206    // @TODO: rename endpoint to /images/upload (or similar)
207    apiRouter.post('/uploads',
208        authenticatePrivate,
209        upload.single('uploadimage'),
210        validation.upload({type: 'images'}),
211        api.http(api.uploads.add)
212    );
213
214    apiRouter.post('/uploads/icon',
215        authenticatePrivate,
216        upload.single('uploadimage'),
217        validation.upload({type: 'icons'}),
218        validation.blogIcon(),
219        api.http(api.uploads.add)
220    );
221
222    // ## Invites
223    apiRouter.get('/invites', authenticatePrivate, api.http(api.invites.browse));
224    apiRouter.get('/invites/:id', authenticatePrivate, api.http(api.invites.read));
225    apiRouter.post('/invites', authenticatePrivate, api.http(api.invites.add));
226    apiRouter.del('/invites/:id', authenticatePrivate, api.http(api.invites.destroy));
227
228    return apiRouter;
229}
230
231module.exports = function setupApiApp() {
232    debug('API setup start');
233    var apiApp = express();
234
235    // @TODO finish refactoring this away.
236    apiApp.use(function setIsAdmin(req, res, next) {
237        // api === isAdmin
238        res.isAdmin = true;
239        next();
240    });
241
242    // API middleware
243
244    // Body parsing
245    apiApp.use(bodyParser.json({limit: '1mb'}));
246    apiApp.use(bodyParser.urlencoded({extended: true, limit: '1mb'}));
247
248    // send 503 json response in case of maintenance
249    apiApp.use(maintenance);
250
251    // Force SSL if required
252    // must happen AFTER asset loading and BEFORE routing
253    apiApp.use(urlRedirects);
254
255    // Check version matches for API requests, depends on res.locals.safeVersion being set
256    // Therefore must come after themeHandler.ghostLocals, for now
257    apiApp.use(versionMatch);
258
259    // API shouldn't be cached
260    apiApp.use(cacheControl('private'));
261
262    // Routing
263    apiApp.use(apiRoutes());
264
265    // API error handling
266    apiApp.use(errorHandler.resourceNotFound);
267    apiApp.use(errorHandler.handleJSONResponse);
268
269    debug('API setup end');
270
271    return apiApp;
272};
273
Full Screen

AuthContext.js

Source: AuthContext.js Github

copy
1import nutritionAPI from "_api/nutritionAPI";
2import { NavigationService } from "_navigation/utils";
3import AsyncStorage from "@react-native-async-storage/async-storage";
4import createContext from "./helper/createContext";
5
6const AUTHENTICATE_START = "AUTHENTICATE_START";
7const AUTHENTICATE_FAIL = "AUTHENTICATE_FAIL";
8const AUTHENTICATE_REFRESH = "AUTHENTICATE_REFRESH";
9
10const initialState = {
11  authFail: false,
12  authStart: false,
13  errorMessage: "",
14};
15
16const authReducer = (state, action) => {
17  switch (action.type) {
18    case AUTHENTICATE_REFRESH:
19      return initialState;
20    case AUTHENTICATE_START:
21      return {
22        ...initialState,
23        authStart: true,
24      };
25    case AUTHENTICATE_FAIL:
26      return {
27        ...state,
28        authStart: false,
29        authFail: true,
30        errorMessage: action.errorMessage,
31      };
32    default:
33      return state;
34  }
35};
36
37const refreshAuth = (dispatch) => () => {
38  dispatch({ type: AUTHENTICATE_REFRESH });
39};
40
41const tryLocalSignin = () => async () => {
42  try {
43    await nutritionAPI.get("/auth/validateToken");
44    NavigationService.navigate("App");
45  } catch (err) {
46    NavigationService.navigate("Onboarding");
47  }
48};
49
50const signup = (dispatch) => async (userInfo) => {
51  dispatch({ type: AUTHENTICATE_START });
52
53  try {
54    const response = await nutritionAPI.post("/auth/signup", userInfo);
55
56    await AsyncStorage.setItem("token", response.data.token);
57
58    dispatch({ type: AUTHENTICATE_REFRESH });
59    NavigationService.navigate("App");
60    //
61  } catch ({ response }) {
62    dispatch({
63      type: AUTHENTICATE_FAIL,
64      errorMessage:
65        response.status === 409
66          ? "An account with this email address already exists"
67          : "Unable to register at this time. Please try again later.",
68    });
69  }
70};
71
72const signin = (dispatch) => async (email, password) => {
73  dispatch({ type: AUTHENTICATE_START });
74
75  try {
76    const response = await nutritionAPI.post("/auth/signin", {
77      email,
78      password,
79    });
80
81    await AsyncStorage.setItem("token", response.data.token);
82    dispatch({ type: AUTHENTICATE_REFRESH });
83    NavigationService.navigate("App");
84    //
85  } catch ({ response }) {
86    dispatch({
87      type: AUTHENTICATE_FAIL,
88      errorMessage:
89        response.status === 401
90          ? "Email or Password is invalid"
91          : "Unable to sign in at this time. Please try again later.",
92    });
93  }
94};
95
96const signout = (dispatch) => async () => {
97  await AsyncStorage.removeItem("token");
98  dispatch({ type: AUTHENTICATE_REFRESH });
99  NavigationService.navigate("Onboarding");
100};
101
102export const { Provider, Context } = createContext(
103  authReducer,
104  {
105    signin,
106    signup,
107    signout,
108    refreshAuth,
109    tryLocalSignin,
110  },
111  initialState
112);
113
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)