nitro-web 0.0.85 → 0.0.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/client/globals.ts +10 -6
  2. package/package.json +14 -6
  3. package/types/{required-globals.d.ts → globals.d.ts} +3 -1
  4. package/.editorconfig +0 -9
  5. package/components/auth/auth.api.js +0 -410
  6. package/components/auth/reset.tsx +0 -86
  7. package/components/auth/signin.tsx +0 -76
  8. package/components/auth/signup.tsx +0 -62
  9. package/components/billing/stripe.api.js +0 -268
  10. package/components/dashboard/dashboard.tsx +0 -32
  11. package/components/partials/element/accordion.tsx +0 -102
  12. package/components/partials/element/avatar.tsx +0 -40
  13. package/components/partials/element/button.tsx +0 -98
  14. package/components/partials/element/calendar.tsx +0 -125
  15. package/components/partials/element/dropdown.tsx +0 -248
  16. package/components/partials/element/filters.tsx +0 -194
  17. package/components/partials/element/github-link.tsx +0 -16
  18. package/components/partials/element/initials.tsx +0 -66
  19. package/components/partials/element/message.tsx +0 -141
  20. package/components/partials/element/modal.tsx +0 -90
  21. package/components/partials/element/sidebar.tsx +0 -195
  22. package/components/partials/element/tooltip.tsx +0 -154
  23. package/components/partials/element/topbar.tsx +0 -15
  24. package/components/partials/form/checkbox.tsx +0 -150
  25. package/components/partials/form/drop-handler.tsx +0 -68
  26. package/components/partials/form/drop.tsx +0 -141
  27. package/components/partials/form/field-color.tsx +0 -86
  28. package/components/partials/form/field-currency.tsx +0 -158
  29. package/components/partials/form/field-date.tsx +0 -252
  30. package/components/partials/form/field.tsx +0 -231
  31. package/components/partials/form/form-error.tsx +0 -27
  32. package/components/partials/form/location.tsx +0 -225
  33. package/components/partials/form/select.tsx +0 -360
  34. package/components/partials/is-first-render.ts +0 -14
  35. package/components/partials/not-found.tsx +0 -7
  36. package/components/partials/styleguide.tsx +0 -407
  37. package/semver-updater.cjs +0 -13
  38. package/tsconfig.json +0 -38
  39. package/tsconfig.types.json +0 -15
  40. package/types/core-only-globals.d.ts +0 -9
  41. package/types.ts +0 -60
package/client/globals.ts CHANGED
@@ -1,12 +1,16 @@
1
- import { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
1
+ import { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, Dispatch, SetStateAction } from 'react'
2
2
  import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
3
3
  import { onChange } from 'nitro-web'
4
+ import { Store } from 'nitro-web/types'
4
5
 
5
6
  declare global {
6
- // Common application globals
7
- const onChange: typeof import('nitro-web').onChange
7
+ // useTracked global (normally defined in ./client/index.ts)
8
+ const useTracked: () => [Store, Dispatch<SetStateAction<Store>>]
8
9
 
9
- // Common aependency globals
10
+ // nitro-web global
11
+ const onChange: typeof import('nitro-web').onChange
12
+
13
+ // common daependency globals
10
14
  /** The public API for rendering a history-aware `<a>`. */
11
15
  const Link: typeof import('react-router-dom').Link
12
16
  const useCallback: typeof import('react').useCallback
@@ -21,9 +25,9 @@ declare global {
21
25
  }
22
26
 
23
27
  Object.assign(window, {
24
- // application globals
28
+ // nitro-web global
25
29
  onChange: onChange,
26
- // dependency globals
30
+ // common dependency globals
27
31
  Link: Link,
28
32
  useCallback: useCallback,
29
33
  useEffect: useEffect,
package/package.json CHANGED
@@ -1,26 +1,34 @@
1
1
  {
2
2
  "name": "nitro-web",
3
- "version": "0.0.85",
3
+ "version": "0.0.87",
4
4
  "repository": "github:boycce/nitro-web",
5
5
  "homepage": "https://boycce.github.io/nitro-web/",
6
6
  "description": "Nitro is a battle-tested, modular base project to turbocharge your projects, styled using Tailwind 🚀",
7
- "main": "./client/index.ts",
8
7
  "type": "module",
8
+ "main": "./client/index.ts",
9
+ "types": "./types/globals.d.ts",
9
10
  "exports": {
10
11
  ".": "./client/index.ts",
12
+ "./.eslintrc.json": "./.eslintrc.json",
11
13
  "./client/imgs/*": "./client/imgs/*",
12
14
  "./client/globals": "./client/globals.ts",
13
15
  "./server": "./server/index.js",
14
16
  "./types": "./types.ts",
15
- "./.eslintrc.json": "./.eslintrc.json",
16
- "./tsconfig.json": "./tsconfig.json",
17
- "./webpack.config.js": "./webpack.config.js",
18
17
  "./util": {
19
18
  "require": "./util.js",
20
19
  "import": "./util.js",
21
20
  "types": "./types/util.d.ts"
22
- }
21
+ },
22
+ "./webpack.config.js": "./webpack.config.js"
23
23
  },
24
+ "files": [
25
+ ".eslintrc.json",
26
+ "client",
27
+ "server",
28
+ "types",
29
+ "util.js",
30
+ "webpack.config.js"
31
+ ],
24
32
  "scripts": {
25
33
  "major": "npm run types && standard-version -a --release-as major && npm publish && cd ../webpack && npm publish",
26
34
  "minor": "npm run types && standard-version -a --release-as minor && npm publish && cd ../webpack && npm publish",
@@ -1,4 +1,3 @@
1
- // Required global types
2
1
  import 'twin.macro'
3
2
  import { css as cssImport } from '@emotion/react'
4
3
  import styledImport from '@emotion/styled'
@@ -17,6 +16,7 @@ declare global {
17
16
  const content: string
18
17
  export default content
19
18
  }
19
+
20
20
  }
21
21
 
22
22
  // Webpack: Twin.macro css extension
@@ -37,3 +37,5 @@ declare module 'react' {
37
37
  for?: string | undefined
38
38
  }
39
39
  }
40
+
41
+ export {}
package/.editorconfig DELETED
@@ -1,9 +0,0 @@
1
- root = true
2
-
3
- [*]
4
- charset = utf-8
5
- indent_style = space
6
- indent_size = 2
7
- end_of_line = lf
8
- insert_final_newline = true
9
- trim_trailing_whitespace = true
@@ -1,410 +0,0 @@
1
- import crypto from 'crypto'
2
- import bcrypt from 'bcrypt'
3
- import passport from 'passport'
4
- import passportLocal from 'passport-local'
5
- import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'
6
- import db from 'monastery'
7
- import jsonwebtoken from 'jsonwebtoken'
8
- import { sendEmail } from 'nitro-web/server'
9
- import { isArray, pick, ucFirst, fullNameSplit } from 'nitro-web/util'
10
-
11
- let authConfig = null
12
- const JWT_SECRET = process.env.JWT_SECRET || 'replace_this_with_secure_env_secret'
13
-
14
- export const routes = {
15
- // Routes
16
- 'get /api/store': [store],
17
- 'get /api/signout': [signout],
18
- 'post /api/signin': [signin],
19
- 'post /api/signup': [signup],
20
- 'post /api/reset-instructions': [resetInstructions],
21
- 'post /api/reset-password': [resetPassword],
22
- 'post /api/invite-instructions': [inviteInstructions],
23
- 'post /api/invite-accept': [resetPassword],
24
- 'delete /api/account/:uid': [remove],
25
-
26
- // Overridable helpers
27
- setup: setup,
28
- findUserFromProvider: findUserFromProvider,
29
- getStore: getStore,
30
- signinAndGetStore: signinAndGetStore,
31
- tokenCreate: tokenCreate,
32
- tokenParse: tokenParse,
33
- userCreate: userCreate,
34
- validatePassword: validatePassword,
35
- }
36
-
37
- function setup(middleware, _config) {
38
- // routes.setup is called automatically when express starts
39
- // Set config values
40
- const configKeys = ['clientUrl', 'emailFrom', 'env', 'name', 'mailgunDomain', 'mailgunKey', 'masterPassword', 'isNotMultiTenant']
41
- authConfig = pick(_config, configKeys)
42
- for (const key of ['clientUrl', 'emailFrom', 'env', 'name']) {
43
- if (!authConfig[key]) throw new Error(`Missing config value for: config.${key}`)
44
- }
45
-
46
- passport.use(
47
- new passportLocal.Strategy(
48
- { usernameField: 'email' },
49
- async (email, password, next) => {
50
- try {
51
- const user = await this.findUserFromProvider({ email }, password)
52
- next(null, user)
53
- } catch (err) {
54
- next(err.message)
55
- }
56
- }
57
- )
58
- )
59
-
60
- passport.use(
61
- new JwtStrategy(
62
- {
63
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
64
- secretOrKey: JWT_SECRET,
65
- },
66
- async (payload, done) => {
67
- try {
68
- const user = await this.findUserFromProvider({ _id: payload._id })
69
- if (!user) return done(null, false)
70
- return done(null, user)
71
- } catch (err) {
72
- return done(err, false)
73
- }
74
- }
75
- )
76
- )
77
-
78
- middleware.order.splice(3, 0, 'passport', 'passportError', 'jwtAuth', 'blocked')
79
-
80
- Object.assign(middleware, {
81
- blocked: function (req, res, next) {
82
- if (req.user && req.user.loginActive === false) {
83
- res.status(403).error('This user is not available.')
84
- } else {
85
- next()
86
- }
87
- },
88
- jwtAuth: function(req, res, next) {
89
- passport.authenticate('jwt', { session: false }, function(err, user) {
90
- if (user) req.user = user
91
- next()
92
- })(req, res, next)
93
- },
94
- passport: passport.initialize(),
95
- passportError: function (err, req, res, next) {
96
- if (!err) return next()
97
- res.error(err)
98
- },
99
- })
100
- }
101
-
102
- async function store(req, res) {
103
- res.json(await this.getStore(req.user))
104
- }
105
-
106
- async function signup(req, res) {
107
- try {
108
- const desktop = req.query.desktop
109
- let user = await this.userCreate(req.body)
110
- sendEmail({
111
- config: authConfig,
112
- template: 'welcome',
113
- to: `${ucFirst(user.firstName)}<${user.email}>`,
114
- }).catch(console.error)
115
- res.send(await this.signinAndGetStore(user, desktop, this.getStore))
116
- } catch (err) {
117
- res.error(err)
118
- }
119
- }
120
-
121
- function signin(req, res) {
122
- const desktop = req.query.desktop
123
- if (!req.body.email) return res.error('email', 'The email you entered is incorrect.')
124
- if (!req.body.password) return res.error('password', 'The password you entered is incorrect.')
125
-
126
- passport.authenticate('local', { session: false }, async (err, user, info) => {
127
- if (err) return res.error(err)
128
- if (!user && info) return res.error('email', info.message)
129
- try {
130
- const response = await this.signinAndGetStore(user, desktop, this.getStore)
131
- res.send(response)
132
- } catch (err) {
133
- res.error(err)
134
- }
135
- })(req, res)
136
- }
137
-
138
- function signout(req, res) {
139
- res.json('{}')
140
- }
141
-
142
- async function resetInstructions(req, res) {
143
- try {
144
- let email = (req.body.email || '').trim().toLowerCase()
145
- if (!email) throw { title: 'email', detail: 'The email you entered is incorrect.' }
146
-
147
- let user = await db.user.findOne({ query: { email }, _privateData: true })
148
- if (!user) throw { title: 'email', detail: 'The email you entered is incorrect.' }
149
-
150
- let resetToken = await tokenCreate(user._id)
151
- await db.user.update({ query: { email }, $set: { resetToken }})
152
-
153
- res.json({})
154
- sendEmail({
155
- config: authConfig,
156
- template: 'reset-password',
157
- to: `${ucFirst(user.firstName)}<${email}>`,
158
- data: {
159
- token: resetToken + (req.query.hasOwnProperty('desktop') ? '?desktop' : ''),
160
- },
161
- }).catch(err => console.error('sendEmail(..) mailgun error', err))
162
- } catch (err) {
163
- res.error(err)
164
- }
165
- }
166
-
167
- async function resetPassword(req, res) {
168
- try {
169
- const { token, password, password2 } = req.body
170
- const name = req.path.includes('invite') ? 'inviteToken' : 'resetToken'
171
- const desktop = req.query.desktop
172
- const id = tokenParse(token)
173
- await validatePassword(password, password2)
174
-
175
- let user = await db.user.findOne({ query: id, blacklist: ['-' + name], _privateData: true })
176
- if (!user || user[name] !== token) throw new Error('Sorry your token is invalid or has already been used.')
177
-
178
- await db.user.update({
179
- query: user._id,
180
- data: {
181
- password: await bcrypt.hash(password, 10),
182
- resetToken: '',
183
- },
184
- blacklist: ['-' + name, '-password'],
185
- })
186
- res.send(await this.signinAndGetStore({ ...user, [name]: undefined }, desktop, this.getStore))
187
- } catch (err) {
188
- res.error(err)
189
- }
190
- }
191
-
192
- async function inviteInstructions(req, res) {
193
- try {
194
- // Check if user is admin here rather than in middleware (which may not exist yet)
195
- if (req.user.type != 'admin' && !req.user.isAdmin) {
196
- throw new Error('You are not authorized to invite users.')
197
- }
198
- const inviteToken = await tokenCreate()
199
- const userData = await db.user.validate({
200
- ...pick(req.body, ['email', 'firstName', 'lastName']),
201
- status: 'invited',
202
- inviteToken: inviteToken,
203
- })
204
-
205
- // Check if user already exists
206
- if (await db.user.findOne({ query: { email: userData.email } })) {
207
- throw { title: 'email', detail: 'User already exists.' }
208
- }
209
-
210
- // Create user
211
- const user = await db.user.insert({
212
- data: userData,
213
- })
214
-
215
- // Send email
216
- res.send(user)
217
- sendEmail({
218
- config: authConfig,
219
- template: 'invite-user',
220
- to: `${ucFirst(userData.firstName)}<${userData.email}>`,
221
- data: {
222
- token: inviteToken + (req.query.hasOwnProperty('desktop') ? '?desktop' : ''),
223
- },
224
- }).catch(err => console.error('sendEmail(..) mailgun error', err))
225
-
226
- } catch (err) {
227
- return res.error(err)
228
- }
229
- }
230
-
231
- async function remove(req, res) {
232
- try {
233
- const uid = db.id(req.params.uid || 'badid')
234
- // Check for active subscription first...
235
- if (req.user.stripeSubscription?.status == 'active') {
236
- throw { title: 'subscription', detail: 'You need to cancel your subscription first.' }
237
- }
238
- // // Get companies owned by user
239
- // const companyIdsOwned = (await db.company.find({
240
- // query: { users: { $elemMatch: { _id: uid, role: 'owner' } } },
241
- // project: { _id: 1 },
242
- // })).map(o => o._id)
243
-
244
- // if (companyIdsOwned.length) {
245
- // await db.product.remove({ query: { company: { $in: companyIdsOwned }}})
246
- // await db.company.remove({ query: { _id: { $in: companyIdsOwned }}})
247
- // }
248
- await db.user.remove({ query: { _id: uid }})
249
- // Logout now so that an error doesn't throw when naviating to /signout
250
- req.logout()
251
- res.send(`User: '${uid}' removed successfully`)
252
- } catch (err) {
253
- res.error(err)
254
- }
255
- }
256
-
257
- /* ---- Overridable helpers ------------------ */
258
-
259
- export async function findUserFromProvider(query, passwordToCheck) {
260
- /**
261
- * Find user for state (and verify password if signing in with email)
262
- * @param {object} query - e.g. { email: 'test@test.com' }
263
- * @param {string} <passwordToCheck> - password to test
264
- */
265
- const isMultiTenant = !authConfig.isNotMultiTenant
266
- const checkPassword = arguments.length > 1
267
- const user = await db.user.findOne({
268
- query: query,
269
- blacklist: ['-password'],
270
- populate: db.user.loginPopulate(),
271
- _privateData: true,
272
- })
273
- if (isMultiTenant && user?.company) {
274
- user.company = await db.company.findOne({
275
- query: user.company,
276
- populate: db.company.loginPopulate(),
277
- _privateData: true,
278
- })
279
- }
280
- if (!user) {
281
- throw new Error(checkPassword ? 'Email or password is incorrect.' : 'Session-user is invalid.')
282
- } else if (isMultiTenant && !user.company) {
283
- throw new Error('The current company is no longer associated with this user')
284
- } else if (isMultiTenant && user.company.status != 'active') {
285
- throw new Error('This user is not associated with an active company')
286
- } else {
287
- if (checkPassword) {
288
- if (!user.password) {
289
- throw new Error('There is no password associated with this account, please try signing in with another method.')
290
- }
291
- const match = user.password ? await bcrypt.compare(passwordToCheck, user.password) : false
292
- if (!match && !(authConfig.masterPassword && passwordToCheck == authConfig.masterPassword)) {
293
- throw new Error('Email or password is incorrect.')
294
- }
295
- }
296
- // Successful return user
297
- delete user.password
298
- return user
299
- }
300
- }
301
-
302
- export async function getStore(user) {
303
- // Initial store
304
- return {
305
- user: user || undefined,
306
- }
307
- }
308
-
309
- export async function signinAndGetStore(user, isDesktop, getStore) {
310
- if (user.loginActive === false) throw 'This user is not available.'
311
- user.desktop = isDesktop
312
-
313
- const jwt = jsonwebtoken.sign({ _id: user._id }, JWT_SECRET, { expiresIn: '30d' })
314
- const store = await getStore(user)
315
- return { ...store, jwt }
316
- }
317
-
318
- export async function userCreate({ business, password, ...userDataProp }) {
319
- try {
320
- if (!this.findUserFromProvider) {
321
- throw new Error('this.findUserFromProvider doesn\'t exist, make sure the context is available when calling this function')
322
- }
323
-
324
- const options = { blacklist: ['-_id'] }
325
- const isMultiTenant = !authConfig.isNotMultiTenant
326
- const userId = db.id()
327
- const companyData = isMultiTenant && {
328
- _id: db.id(),
329
- ...(business ? { business } : {}),
330
- users: [{ _id: userId, role: 'owner', status: 'active' }],
331
- }
332
- const userData = {
333
- ...userDataProp,
334
- _id: userId,
335
- ...(userDataProp.name ? {
336
- firstName: fullNameSplit(userDataProp.name)[0],
337
- lastName: fullNameSplit(userDataProp.name)[1],
338
- } : {}),
339
- password: password ? await bcrypt.hash(password, 10) : undefined,
340
- ...(isMultiTenant ? { company: companyData._id } : {}),
341
- }
342
- // First validate the data so we don't have to create a transaction
343
- const results = await Promise.allSettled([
344
- db.user.validate(userData, options),
345
- ...(isMultiTenant ? [db.company.validate(companyData, options)] : []),
346
- typeof password === 'undefined' ? Promise.resolve() : validatePassword(password),
347
- ])
348
-
349
- // Throw all the errors from at once
350
- const errors = results.filter(o => o.status == 'rejected').reduce((acc, o) => {
351
- if (isArray(o.reason)) acc.push(...o.reason)
352
- else throw o.reason
353
- return acc
354
- }, [])
355
- if (errors.length) throw errors
356
-
357
- // Insert company & user
358
- await db.user.insert({ data: userData, ...options })
359
- if (isMultiTenant) await db.company.insert({ data: companyData, ...options })
360
-
361
- // Return the user
362
- return await findUserFromProvider({ _id: userId })
363
-
364
- } catch (err) {
365
- if (!isArray(err)) throw err
366
- else throw err //...
367
- }
368
- }
369
-
370
- export function tokenCreate(id) {
371
- return new Promise((resolve) => {
372
- crypto.randomBytes(16, (err, buff) => {
373
- let hash = buff.toString('hex') // 32 chars
374
- resolve(`${hash}${id || ''}:${Date.now()}`)
375
- })
376
- })
377
- }
378
-
379
- export function tokenParse(token) {
380
- let split = (token || '').split(':')
381
- let hash = split[0].slice(0, 32)
382
- let userId = split[0].slice(32)
383
- let time = split[1]
384
- if (!hash || !userId || !time) {
385
- throw { title: 'error', detail: 'Sorry your code is invalid.' }
386
- } else if (parseFloat(time) + 1000 * 60 * 60 * 24 < Date.now()) {
387
- throw { title: 'error', detail: 'Sorry your code has timed out.' }
388
- } else {
389
- return userId
390
- }
391
- }
392
-
393
- export async function validatePassword(password='', password2) {
394
- // let hasLowerChar = password.match(/[a-z]/)
395
- // let hasUpperChar = password.match(/[A-Z]/)
396
- // let hasNumber = password.match(/\d/)
397
- // let hasSymbol = password.match(/\W/)
398
- if (!password) {
399
- throw [{ title: 'password', detail: 'This field is required.' }]
400
- } else if (authConfig.env !== 'development' && password.length < 8) {
401
- throw [{ title: 'password', detail: 'Your password needs to be atleast 8 characters long' }]
402
- // } else if (!hasLowerChar || !hasUpperChar || !hasNumber || !hasSymbol) {
403
- // throw {
404
- // title: 'password',
405
- // detail: 'You need to include uppercase and lowercase letters, and a number'
406
- // }
407
- } else if (typeof password2 != 'undefined' && password !== password2) {
408
- throw [{ title: 'password2', detail: 'Your passwords need to match.' }]
409
- }
410
- }
@@ -1,86 +0,0 @@
1
- import { Topbar, Field, FormError, Button, request } from 'nitro-web'
2
- import { Errors } from 'nitro-web/types'
3
-
4
- export function ResetInstructions() {
5
- const navigate = useNavigate()
6
- const isLoading = useState(false)
7
- const [, setStore] = useTracked()
8
- const [state, setState] = useState({ email: '', errors: [] as Errors })
9
-
10
- async function onSubmit (event: React.FormEvent<HTMLFormElement>) {
11
- try {
12
- await request('post /api/reset-instructions', state, event, isLoading, setState)
13
- setStore((s) => ({ ...s, message: 'Done! Please check your email.' }))
14
- navigate('/signin')
15
- } catch (e) {
16
- return setState({ ...state, errors: e as Errors })
17
- }
18
- }
19
-
20
- return (
21
- <div class="">
22
- <Topbar title={<>Reset your Password</>} />
23
-
24
- <form onSubmit={onSubmit}>
25
- <div>
26
- <label for="email">Email Address</label>
27
- <Field name="email" type="email" state={state} onChange={(e) => onChange(setState, e)} placeholder="Your email address..." />
28
- </div>
29
-
30
- <div class="mb-14">
31
- Remembered your password? You can <Link to="/signin" class="underline2 is-active">sign in here</Link>.
32
- <FormError state={state} className="pt-2" />
33
- </div>
34
-
35
- <Button className="w-full" isLoading={isLoading[0]} type="submit">Email me a reset password link</Button>
36
- </form>
37
- </div>
38
- )
39
- }
40
-
41
- export function ResetPassword() {
42
- const navigate = useNavigate()
43
- const params = useParams()
44
- const isLoading = useState(false)
45
- const [, setStore] = useTracked()
46
- const [state, setState] = useState(() => ({
47
- password: '',
48
- password2: '',
49
- token: params.token,
50
- errors: [] as Errors,
51
- }))
52
-
53
- async function onSubmit (event: React.FormEvent<HTMLFormElement>) {
54
- try {
55
- const data = await request('post /api/reset-password', state, event, isLoading, setState)
56
- setStore((s) => ({ ...s, ...data }))
57
- navigate('/')
58
- } catch (e) {
59
- return setState({ ...state, errors: e as Errors })
60
- }
61
- }
62
-
63
- return (
64
- <div class="">
65
- <Topbar title={<>Reset your Password</>} />
66
-
67
- <form onSubmit={onSubmit}>
68
- <div>
69
- <label for="password">Your New Password</label>
70
- <Field name="password" type="password" state={state} onChange={(e) => onChange(setState, e)} />
71
- </div>
72
- <div>
73
- <label for="password2">Repeat Your New Password</label>
74
- <Field name="password2" type="password" state={state} onChange={(e) => onChange(setState, e)} />
75
- </div>
76
-
77
- <div class="mb-14">
78
- Remembered your password? You can <Link to="/signin" class="underline2 is-active">sign in here</Link>.
79
- <FormError state={state} className="pt-2" />
80
- </div>
81
-
82
- <Button class="w-full" isLoading={isLoading[0]} type="submit">Reset Password</Button>
83
- </form>
84
- </div>
85
- )
86
- }
@@ -1,76 +0,0 @@
1
- import { Topbar, Field, Button, FormError, request, queryObject, injectedConfig, updateJwt } from 'nitro-web'
2
- import { Errors } from 'nitro-web/types'
3
-
4
- export function Signin() {
5
- const navigate = useNavigate()
6
- const location = useLocation()
7
- const isSignout = location.pathname == '/signout'
8
- const isLoading = useState(isSignout)
9
- const [, setStore] = useTracked()
10
- const [state, setState] = useState({
11
- email: injectedConfig.env == 'development' ? (injectedConfig.placeholderEmail || '') : '',
12
- password: injectedConfig.env == 'development' ? '1234' : '',
13
- errors: [] as Errors,
14
- })
15
-
16
- useEffect(() => {
17
- // Autofill the email input from ?email=
18
- const query = queryObject(location.search, true)
19
- if (query.email) setState({ ...state, email: query.email as string })
20
- }, [location.search])
21
-
22
- useEffect(() => {
23
- if (isSignout) {
24
- setStore((s) => ({ ...s, user: undefined }))
25
- // util.axios().get('/api/signout')
26
- Promise.resolve()
27
- .then(() => isLoading[1](false))
28
- .then(() => updateJwt())
29
- .then(() => navigate({ pathname: '/signin', search: location.search }, { replace: true }))
30
- .catch(err => (console.error(err), isLoading[1](false)))
31
- }
32
- }, [isSignout])
33
-
34
- async function onSubmit (e: React.FormEvent<HTMLFormElement>) {
35
- try {
36
- const data = await request('post /api/signin', state, e, isLoading, setState)
37
- // Keep it loading until we navigate
38
- isLoading[1](true)
39
- setStore((s) => ({ ...s, ...data }))
40
- setTimeout(() => { // wait for setStore
41
- if (location.search.includes('redirect')) navigate(location.search.replace('?redirect=', ''))
42
- else navigate('/')
43
- }, 100)
44
- } catch (e) {
45
- return setState({ ...state, errors: e as Errors})
46
- }
47
- }
48
-
49
- return (
50
- <div>
51
- <Topbar title={<>Sign in to your Account</>} />
52
-
53
- <form onSubmit={onSubmit}>
54
- <div>
55
- <label for="email">Email Address</label>
56
- <Field name="email" type="email" state={state} onChange={(e) => onChange(setState, e)}
57
- placeholder="Your email address..." />
58
- </div>
59
- <div>
60
- <div class="flex justify-between">
61
- <label for="password">Password</label>
62
- <Link to="/reset" class="label underline2">Forgot?</Link>
63
- </div>
64
- <Field name="password" type="password" state={state} onChange={(e) => onChange(setState, e)}/>
65
- </div>
66
-
67
- <div class="mb-14">
68
- Don&apos;t have an account? You can <Link to="/signup" class="underline2 is-active">sign up here</Link>.
69
- <FormError state={state} className="pt-2" />
70
- </div>
71
-
72
- <Button class="w-full" isLoading={isLoading[0]} type="submit">Sign In</Button>
73
- </form>
74
- </div>
75
- )
76
- }