generated from EasyWebApp/WebCell-scaffold
-
Notifications
You must be signed in to change notification settings - Fork 7
Implement simplified Material UI login system with server-side JWT validation and configure @idea2app/data-server package integration #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c3391dd
Initial plan
Copilot 51fba97
Initial plan for SMS verification login system
Copilot eb83a59
Implement SMS verification login system with Material UI
Copilot a0af9b7
Complete SMS verification system with working API endpoints
Copilot e5d6eb2
Address review feedback: delete files, simplify components, update Us…
Copilot 42b8d42
Implement server-side JWT validation and add i18n translations
Copilot 26e37e6
Fix package-lock.json issue and address all review feedback
Copilot 039af9a
Merge remote-tracking branch 'origin/main' into copilot/fix-83
TechQuery ed3bae2
[fix] many GitHub copilot bugs
TechQuery a558d15
Fix i18n translations in SessionForm by using t() function properly
Copilot 0ce9f38
Configure @idea2app/data-server package access and update types
Copilot 96e9c9b
[fix] many GitHub copilot bugs
TechQuery File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,8 @@ | |
| /node_modules | ||
| /.pnp | ||
| .pnp.js | ||
| package-lock.json | ||
| yarn.lock | ||
|
|
||
| # testing | ||
| /coverage | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import { Drawer, List, ListItem, ListItemButton, ListItemText } from '@mui/material'; | ||
| import { observable } from 'mobx'; | ||
| import { observer } from 'mobx-react'; | ||
| import Link from 'next/link'; | ||
| import { Component, HTMLAttributes, JSX } from 'react'; | ||
|
|
||
| import { PageHead } from '../PageHead'; | ||
| import { SessionForm } from './SessionForm'; | ||
|
|
||
| export type MenuItem = Pick<JSX.IntrinsicElements['a'], 'href' | 'title'>; | ||
|
|
||
| export interface SessionBoxProps extends HTMLAttributes<HTMLDivElement> { | ||
| path?: string; | ||
| menu?: MenuItem[]; | ||
| jwtPayload?: any; // TODO: Define proper JWT payload type | ||
| } | ||
|
|
||
| @observer | ||
| export class SessionBox extends Component<SessionBoxProps> { | ||
| @observable | ||
| accessor modalShown = false; | ||
|
|
||
| componentDidMount() { | ||
| this.modalShown = !this.props.jwtPayload; | ||
| } | ||
|
|
||
| render() { | ||
| const { className = '', title, children, path, menu = [], jwtPayload, ...props } = this.props; | ||
|
|
||
| return ( | ||
| <div className={`flex ${className}`} {...props}> | ||
| <div> | ||
| <List | ||
| component="nav" | ||
| className="flex-col px-3 sticky-top" | ||
| style={{ top: '5rem', minWidth: '200px' }} | ||
| > | ||
| {menu.map(({ href, title }) => ( | ||
| <ListItem key={href} disablePadding> | ||
| <ListItemButton | ||
| component={Link} | ||
| href={href || '#'} | ||
| selected={path?.split('?')[0].startsWith(href || '')} | ||
| className="rounded" | ||
| > | ||
| <ListItemText primary={title} /> | ||
| </ListItemButton> | ||
| </ListItem> | ||
| ))} | ||
| </List> | ||
| </div> | ||
| <main className="flex-1 pb-3"> | ||
| <PageHead title={title} /> | ||
|
|
||
| <h1 className="text-3xl font-bold mb-4">{title}</h1> | ||
|
|
||
| {children} | ||
|
|
||
| <Drawer | ||
| anchor="right" | ||
| open={this.modalShown} | ||
| PaperProps={{ | ||
| className: 'p-4', | ||
| style: { width: '400px' }, | ||
| }} | ||
| onClose={() => (this.modalShown = false)} | ||
| > | ||
| <SessionForm onSignIn={() => window.location.reload()} /> | ||
| </Drawer> | ||
| </main> | ||
| </div> | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import { Button, IconButton, InputAdornment, Tab, Tabs, TextField } from '@mui/material'; | ||
| import { observable } from 'mobx'; | ||
| import { observer } from 'mobx-react'; | ||
| import { ObservedComponent } from 'mobx-react-helper'; | ||
| import { FormEvent, MouseEvent } from 'react'; | ||
| import { formToJSON } from 'web-utility'; | ||
|
|
||
| import { i18n, I18nContext } from '../../models/Translation'; | ||
| import userStore from '../../models/User'; | ||
| import { SymbolIcon } from '../Icon'; | ||
|
|
||
| export interface SessionFormProps { | ||
| onSignIn?: (data?: SignInData) => any; | ||
| } | ||
|
|
||
| export interface SignInData { | ||
| phone: string; | ||
| password: string; | ||
| } | ||
TechQuery marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| @observer | ||
| export class SessionForm extends ObservedComponent<SessionFormProps, typeof i18n> { | ||
| static contextType = I18nContext; | ||
|
|
||
| @observable | ||
| accessor signType: 'up' | 'in' = 'in'; | ||
|
|
||
| handleWebAuthn = async (event: MouseEvent<HTMLButtonElement>) => { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
|
|
||
| if (this.signType === 'up') { | ||
| const { phone } = formToJSON<SignInData>(event.currentTarget.form!); | ||
|
|
||
| if (!phone) throw new Error('手机号是WebAuthn注册的必填项'); | ||
|
|
||
| await userStore.signUpWebAuthn(phone); | ||
| } else { | ||
| await userStore.signInWebAuthn(); | ||
| } | ||
| this.props.onSignIn?.(); | ||
| }; | ||
|
|
||
| handleSubmit = async (event: FormEvent<HTMLFormElement>) => { | ||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
|
|
||
| const { phone, password } = formToJSON<SignInData>(event.currentTarget); | ||
|
|
||
| if (this.signType === 'up') { | ||
| await userStore.signUp(phone, password); | ||
|
|
||
| this.signType = 'in'; | ||
|
|
||
| alert('注册成功,请登录'); | ||
| } else { | ||
| await userStore.signIn(phone, password); | ||
|
|
||
| this.props.onSignIn?.({ phone, password }); | ||
| } | ||
| }; | ||
|
|
||
| render() { | ||
| const { signType } = this, | ||
| loading = userStore.uploading > 0; | ||
|
|
||
| const { t } = this.observedContext; | ||
|
|
||
| return ( | ||
| <form className="flex flex-col gap-4" onSubmit={this.handleSubmit}> | ||
| <Tabs | ||
| value={signType} | ||
| variant="fullWidth" | ||
| className="mb-4" | ||
| onChange={(_, newValue: 'up' | 'in') => (this.signType = newValue)} | ||
| > | ||
| <Tab label={t('register')} value="up" /> | ||
| <Tab label={t('login')} value="in" /> | ||
| </Tabs> | ||
|
|
||
| <TextField | ||
| name="phone" | ||
| type="tel" | ||
| required | ||
| fullWidth | ||
| variant="outlined" | ||
| label={t('phone_number')} | ||
| placeholder={t('please_enter_phone')} | ||
| slotProps={{ | ||
| htmlInput: { | ||
| pattern: '1[3-9]\\d{9}', | ||
| title: t('please_enter_correct_phone'), | ||
| }, | ||
| input: { | ||
| startAdornment: <InputAdornment position="start">+86</InputAdornment>, | ||
| }, | ||
| }} | ||
| /> | ||
| <div className="flex items-center gap-2"> | ||
| <TextField | ||
| name="password" | ||
| type="password" | ||
| required | ||
| fullWidth | ||
| variant="outlined" | ||
| label={t('password')} | ||
| placeholder={t('please_enter_password')} | ||
| /> | ||
|
|
||
| <IconButton | ||
| size="large" | ||
| className="mb-2 self-end" | ||
| disabled={loading} | ||
| onClick={this.handleWebAuthn} | ||
| > | ||
| <SymbolIcon name="fingerprint" /> | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fingerprint 没有在 html link 处引入,不会生效的
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
好的,没注意这么细节的问题,主要是先想让 AI 把通用的登录框代码移植过来,马上要做的下个 PR 我修复一下。 |
||
| </IconButton> | ||
| </div> | ||
|
|
||
| <Button | ||
| className="mt-4" | ||
| type="submit" | ||
| variant="contained" | ||
| fullWidth | ||
| size="large" | ||
| disabled={loading} | ||
| > | ||
| {signType === 'up' ? t('register') : t('login')} | ||
| </Button> | ||
| </form> | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TechQuery marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| import { clear } from 'idb-keyval'; | ||
| import { HTTPClient } from 'koajax'; | ||
| import { observable, reaction } from 'mobx'; | ||
| import { persist, restore, toggle } from 'mobx-restful'; | ||
| import { setCookie } from 'web-utility'; | ||
|
|
||
| import { TableModel } from './Base'; | ||
| import { API_Host, isServer } from './configuration'; | ||
|
|
||
| export interface User { | ||
| id?: string; | ||
| email?: string; | ||
| nickname?: string; | ||
| avatar?: string; | ||
| token?: string; | ||
| } | ||
|
|
||
| export interface WebAuthnChallenge { | ||
| string: string; | ||
| } | ||
TechQuery marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| export class UserModel extends TableModel<User> { | ||
| baseURI = 'user'; | ||
|
|
||
| @persist() | ||
| @observable | ||
| accessor session: User | undefined; | ||
|
|
||
| disposer = reaction( | ||
| () => this.session?.token, | ||
| token => setCookie('token', token || '', { path: '/' }), | ||
| ); | ||
| restored = !isServer() && restore(this, 'User'); | ||
|
|
||
| client = new HTTPClient({ baseURI: API_Host, responseType: 'json' }).use(({ request }, next) => { | ||
| const isSameDomain = API_Host.startsWith(new URL(request.path, API_Host).origin); | ||
|
|
||
| if (isSameDomain && this.session) | ||
| request.headers = { | ||
| ...request.headers, | ||
| Authorization: `Bearer ${this.session.token}`, | ||
| }; | ||
|
|
||
| return next(); | ||
| }); | ||
|
|
||
| @toggle('uploading') | ||
| async sendOTP(address: string) { | ||
| await this.client.post(`user/session/email/${address}/OTP`); | ||
| } | ||
|
|
||
| @toggle('uploading') | ||
| async signUp(email: string, password: string) { | ||
| const { body } = await this.client.post<User>('user', { email, password }); | ||
|
|
||
| return body; | ||
| } | ||
|
|
||
| @toggle('uploading') | ||
| async signIn(email: string, password: string) { | ||
| const { body } = await this.client.post<User>('user/session', { email, password }); | ||
|
|
||
| return (this.session = body); | ||
| } | ||
|
|
||
| @toggle('uploading') | ||
| async createChallenge() { | ||
| const { body } = await this.client.post<WebAuthnChallenge>('user/WebAuthn/challenge'); | ||
|
|
||
| return body!.string; | ||
| } | ||
|
|
||
| @toggle('uploading') | ||
| async signUpWebAuthn(email: string) { | ||
| if (isServer()) throw new Error('WebAuthn not available on server side'); | ||
|
|
||
| const { client } = await import('@passwordless-id/webauthn'); | ||
|
|
||
| const challenge = await this.createChallenge(); | ||
|
|
||
| const registration = await client.register({ user: email, challenge }); | ||
|
|
||
| const { body } = await this.client.post<User>('user/WebAuthn/registration', { | ||
| ...registration, | ||
| challenge, | ||
| }); | ||
|
|
||
| return (this.session = body); | ||
| } | ||
|
|
||
| @toggle('uploading') | ||
| async signInWebAuthn() { | ||
| if (isServer()) throw new Error('WebAuthn not available on server side'); | ||
|
|
||
| const { client } = await import('@passwordless-id/webauthn'); | ||
|
|
||
| const challenge = await this.createChallenge(); | ||
|
|
||
| const authentication = await client.authenticate({ challenge }); | ||
|
|
||
| const { body } = await this.client.post<User>('user/WebAuthn/authentication', { | ||
| ...authentication, | ||
| challenge, | ||
| }); | ||
|
|
||
| return (this.session = body); | ||
| } | ||
|
|
||
| @toggle('uploading') | ||
| async signOut() { | ||
| await clear(); | ||
|
|
||
| location.hash = ''; | ||
| } | ||
| } | ||
|
|
||
| export default new UserModel(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.