User profile page (#102)

* Added mock profile page

* Added translations

* Modularized page, added LoginProvider, started validation

* Re-adding profile route after router refactoring

* Added API calls for password and name change

* Added user deletion modal

* Refactored translations in profile-page to match new locales

* Fixed merge-conflicted locales/de.json

* Removed values for password fields

* Fixed capitalization of LoginProvider

* Fixed codestyle method declarations

* Fix names of methods and started countdown

* Fix countdown

Signed-off-by: Tilman Vatteroth <tilman.vatteroth@tu-dortmund.de>

Co-authored-by: Tilman Vatteroth <tilman.vatteroth@tu-dortmund.de>
This commit is contained in:
Erik Michelson 2020-05-31 21:56:39 +02:00 committed by GitHub
parent 515cf1f34d
commit 747d9686fa
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 356 additions and 13 deletions

View file

@ -67,6 +67,17 @@
}
},
"profile": {
"userProfile": "User profile",
"displayName": "Display name",
"displayNameInfo": "This name will be shown publicly on notes you created or edited.",
"changePassword": {
"title": "Change password",
"old": "Old password",
"new": "New password",
"newAgain": "New password again",
"info": "Your new password should contain at least 6 characters."
},
"accountManagement": "Account management",
"deleteUser": "Delete user",
"exportUserData": "Export user data",
"modal": {
@ -207,6 +218,7 @@
"cancel": "Cancel",
"ok": "OK",
"close": "Close",
"save": "Save",
"or": "or",
"and": "and"
},

View file

@ -2,5 +2,6 @@
"id": "mockUser",
"photo": "https://1.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?s=200&r=pg&d=mp",
"name": "Test",
"status": "ok"
"status": "ok",
"provider": "email"
}

View file

@ -1,3 +1,4 @@
import { LoginProvider } from '../redux/user/types'
import { expectResponseCode, getBackendUrl } from '../utils/apiUtils'
import { defaultFetchConfig } from './default'
@ -11,6 +12,7 @@ export interface meResponse {
id: string
name: string
photo: string
provider: LoginProvider
}
export const doEmailLogin = async (email: string, password: string): Promise<void> => {
@ -50,3 +52,37 @@ export const doOpenIdLogin = async (openId: string): Promise<void> => {
expectResponseCode(response)
}
export const updateDisplayName = async (displayName: string): Promise<void> => {
const response = await fetch(getBackendUrl() + '/me', {
...defaultFetchConfig,
method: 'POST',
body: JSON.stringify({
name: displayName
})
})
expectResponseCode(response)
}
export const changePassword = async (oldPassword: string, newPassword: string): Promise<void> => {
const response = await fetch(getBackendUrl() + '/me/password', {
...defaultFetchConfig,
method: 'POST',
body: JSON.stringify({
oldPassword,
newPassword
})
})
expectResponseCode(response)
}
export const deleteUser = async (): Promise<void> => {
const response = await fetch(getBackendUrl() + '/me', {
...defaultFetchConfig,
method: 'DELETE'
})
expectResponseCode(response)
}

View file

@ -9,7 +9,7 @@ import { Trans, useTranslation } from 'react-i18next'
import { UserAvatar } from '../../user-avatar/user-avatar'
export const UserDropdown: React.FC = () => {
useTranslation();
useTranslation()
const user = useSelector((state: ApplicationState) => state.user)
return (
@ -25,16 +25,12 @@ export const UserDropdown: React.FC = () => {
<Trans i18nKey="editor.help.documents.features"/>
</Dropdown.Item>
</LinkContainer>
<LinkContainer to={'/me/export'}>
<LinkContainer to={'/profile'}>
<Dropdown.Item>
<FontAwesomeIcon icon="cloud-download-alt" fixedWidth={true} className="mr-2"/>
<Trans i18nKey="profile.exportUserData"/>
<FontAwesomeIcon icon="user" fixedWidth={true} className="mr-2"/>
<Trans i18nKey="profile.userProfile"/>
</Dropdown.Item>
</LinkContainer>
<Dropdown.Item href="#">
<FontAwesomeIcon icon="trash" fixedWidth={true} className="mr-2"/>
<Trans i18nKey="profile.deleteUser"/>
</Dropdown.Item>
<Dropdown.Item
onClick={() => {
clearUser()

View file

@ -0,0 +1,31 @@
import React from 'react'
import { Col, Row } from 'react-bootstrap'
import { useSelector } from 'react-redux'
import { Redirect } from 'react-router'
import { ApplicationState } from '../../../../redux'
import { LoginProvider, LoginStatus } from '../../../../redux/user/types'
import { ProfileAccountManagement } from './settings/profile-account-management'
import { ProfileChangePassword } from './settings/profile-change-password'
import { ProfileDisplayName } from './settings/profile-display-name'
export const Profile: React.FC = () => {
const user = useSelector((state: ApplicationState) => state.user)
if (user.status === LoginStatus.forbidden) {
return (
<Redirect to={'/login'} />
)
}
return (
<div className="my-3">
<Row className="h-100 flex justify-content-center">
<Col lg={6}>
<ProfileDisplayName/>
{ user.provider === LoginProvider.EMAIL ? <ProfileChangePassword/> : null }
<ProfileAccountManagement/>
</Col>
</Row>
</div>
)
}

View file

@ -0,0 +1,87 @@
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import React, { Fragment, useEffect, useRef, useState } from 'react'
import { Button, Card, Modal } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import { deleteUser } from '../../../../../api/user'
import { clearUser } from '../../../../../redux/user/methods'
import { getBackendUrl } from '../../../../../utils/apiUtils'
export const ProfileAccountManagement: React.FC = () => {
useTranslation()
const [showDeleteModal, setShowDeleteModal] = useState(false)
const [deletionButtonActive, setDeletionButtonActive] = useState(false)
const [countdown, setCountdown] = useState(0)
const interval = useRef<NodeJS.Timeout>()
const stopCountdown = ():void => {
if (interval.current) {
clearTimeout(interval.current)
}
}
const startCountdown = ():void => {
interval.current = setInterval(() => {
setCountdown((oldValue) => oldValue - 1)
}, 1000)
}
const handleModalClose = () => {
setShowDeleteModal(false)
stopCountdown()
}
useEffect(() => {
if (!showDeleteModal) {
return
}
if (countdown === 0) {
setDeletionButtonActive(true)
stopCountdown()
}
}, [countdown, showDeleteModal])
const handleModalOpen = () => {
setShowDeleteModal(true)
setDeletionButtonActive(false)
setCountdown(10)
startCountdown()
}
const deleteUserAccount = async () => {
await deleteUser()
clearUser()
}
return (
<Fragment>
<Card className="bg-dark mb-4">
<Card.Body>
<Card.Title><Trans i18nKey="profile.accountManagement"/></Card.Title>
<Button variant="secondary" block href={getBackendUrl() + '/me/export'} className="mb-2">
<FontAwesomeIcon icon="cloud-download-alt" fixedWidth={true} className="mr-2"/>
<Trans i18nKey="profile.exportUserData"/>
</Button>
<Button variant="danger" block onClick={handleModalOpen}>
<FontAwesomeIcon icon="trash" fixedWidth={true} className="mr-2"/>
<Trans i18nKey="profile.deleteUser"/>
</Button>
</Card.Body>
</Card>
<Modal show={showDeleteModal} onHide={handleModalClose} animation={true}>
<Modal.Body className="text-dark">
<h3><Trans i18nKey="profile.modal.deleteUser.message"/></h3>
<Trans i18nKey="profile.modal.deleteUser.subMessage"/>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleModalClose}>
<Trans i18nKey="common.close"/>
</Button>
<Button variant="danger" onClick={deleteUserAccount} disabled={!deletionButtonActive}>
{deletionButtonActive ? <Trans i18nKey={'profile.modal.deleteUser.title'}/> : countdown}
</Button>
</Modal.Footer>
</Modal>
</Fragment>
)
}

View file

@ -0,0 +1,82 @@
import React, { ChangeEvent, FormEvent, useState } from 'react'
import { Button, Card, Form } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import { changePassword } from '../../../../../api/user'
export const ProfileChangePassword: React.FC = () => {
useTranslation()
const [oldPassword, setOldPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [newPasswordAgain, setNewPasswordAgain] = useState('')
const [newPasswordValid, setNewPasswordValid] = useState(false)
const [newPasswordAgainValid, setNewPasswordAgainValid] = useState(false)
const regexPassword = /^[^\s].{5,}$/
const onChangeNewPassword = (event: ChangeEvent<HTMLInputElement>) => {
setNewPassword(event.target.value)
setNewPasswordValid(regexPassword.test(event.target.value))
setNewPasswordAgainValid(event.target.value === newPasswordAgain)
}
const onChangeNewPasswordAgain = (event: ChangeEvent<HTMLInputElement>) => {
setNewPasswordAgain(event.target.value)
setNewPasswordAgainValid(event.target.value === newPassword)
}
const updatePasswordSubmit = async (event: FormEvent) => {
await changePassword(oldPassword, newPassword)
event.preventDefault()
}
return (
<Card className="bg-dark mb-4">
<Card.Body>
<Card.Title><Trans i18nKey="profile.changePassword.title"/></Card.Title>
<Form onSubmit={updatePasswordSubmit} className="text-left">
<Form.Group controlId="oldPassword">
<Form.Label><Trans i18nKey="profile.changePassword.old"/></Form.Label>
<Form.Control
type="password"
size="sm"
className="bg-dark text-white"
required
onChange={(event) => setOldPassword(event.target.value)}
/>
</Form.Group>
<Form.Group controlId="newPassword">
<Form.Label><Trans i18nKey="profile.changePassword.new"/></Form.Label>
<Form.Control
type="password"
size="sm"
className="bg-dark text-white"
required
onChange={onChangeNewPassword}
isValid={newPasswordValid}
/>
<Form.Text><Trans i18nKey="profile.changePassword.info"/></Form.Text>
</Form.Group>
<Form.Group controlId="newPasswordAgain">
<Form.Label><Trans i18nKey="profile.changePassword.newAgain"/></Form.Label>
<Form.Control
type="password"
size="sm"
className="bg-dark text-white"
required
onChange={onChangeNewPasswordAgain}
isValid={newPasswordAgainValid}
isInvalid={newPasswordAgain !== '' && !newPasswordAgainValid}
/>
</Form.Group>
<Button
type="submit"
variant="primary"
disabled={!newPasswordValid || !newPasswordAgainValid}>
<Trans i18nKey="common.save"/>
</Button>
</Form>
</Card.Body>
</Card>
)
}

View file

@ -0,0 +1,66 @@
import React, { ChangeEvent, FormEvent, useState } from 'react'
import { Button, Card, Form } from 'react-bootstrap'
import { Trans, useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux'
import { updateDisplayName } from '../../../../../api/user'
import { ApplicationState } from '../../../../../redux'
import { getAndSetUser } from '../../../../../utils/apiUtils'
export const ProfileDisplayName: React.FC = () => {
const { t } = useTranslation()
const user = useSelector((state: ApplicationState) => state.user)
const [submittable, setSubmittable] = useState(false)
const [error, setError] = useState(false)
const [displayName, setDisplayName] = useState(user.name)
const regexInvalidDisplayName = /^\s*$/
const changeNameField = (event: ChangeEvent<HTMLInputElement>) => {
setSubmittable(!regexInvalidDisplayName.test(event.target.value))
setDisplayName(event.target.value)
}
const doAsyncChange = async () => {
await updateDisplayName(displayName)
await getAndSetUser()
}
const changeNameSubmit = (event: FormEvent) => {
doAsyncChange().catch(() => setError(true))
event.preventDefault()
}
return (
<Card className="bg-dark mb-4">
<Card.Body>
<Card.Title>
<Trans i18nKey="profile.userProfile"/>
</Card.Title>
<Form onSubmit={changeNameSubmit} className="text-left">
<Form.Group controlId="displayName">
<Form.Label><Trans i18nKey="profile.displayName"/></Form.Label>
<Form.Control
type="text"
size="sm"
placeholder={t('profile.displayName')}
value={displayName}
className="bg-dark text-white"
onChange={changeNameField}
isValid={submittable}
isInvalid={error}
required
/>
<Form.Text><Trans i18nKey="profile.displayNameInfo"/></Form.Text>
</Form.Group>
<Button
type="submit"
variant="primary"
disabled={!submittable}>
<Trans i18nKey="common.save"/>
</Button>
</Form>
</Card.Body>
</Card>
)
}

View file

@ -8,6 +8,7 @@ import { LandingLayout } from './components/landing/landing-layout'
import { History } from './components/landing/pages/history/history'
import { Intro } from './components/landing/pages/intro/intro'
import { Login } from './components/landing/pages/login/login'
import { Profile } from './components/landing/pages/profile/profile'
import { setUpFontAwesome } from './initializers/fontAwesome'
import * as serviceWorker from './service-worker'
import { store } from './utils/store'
@ -35,6 +36,11 @@ ReactDOM.render(
<Login/>
</LandingLayout>
</Route>
<Route path="/profile">
<LandingLayout>
<Profile/>
</LandingLayout>
</Route>
<Route path="/n/:id">
<Editor/>
</Route>

View file

@ -46,12 +46,13 @@ import {
faTrash,
faTv,
faUpload,
faUser,
faUsers
} from '@fortawesome/free-solid-svg-icons'
export const setUpFontAwesome: (() => void) = () => {
library.add(faBolt, faPlus, faChartBar, faTv, faFileAlt, faCloudDownloadAlt,
faTrash, faSignOutAlt, faComment, faDiscourse, faMastodon, faGlobe,
faTrash, faSignOutAlt, faComment, faDiscourse, faMastodon, faGlobe, faUser,
faThumbtack, faClock, faTimes, faGithub, faGitlab, faGoogle, faFacebook,
faDropbox, faTwitter, faUsers, faAddressCard, faEye, faPencilAlt, faColumns,
faMoon, faQuestionCircle, faShareSquare, faHistory, faFileCode, faPaste,

View file

@ -1,11 +1,20 @@
import { Reducer } from 'redux'
import { CLEAR_USER_ACTION_TYPE, LoginStatus, SET_USER_ACTION_TYPE, SetUserAction, UserActions, UserState } from './types'
import {
CLEAR_USER_ACTION_TYPE,
LoginProvider,
LoginStatus,
SET_USER_ACTION_TYPE,
SetUserAction,
UserActions,
UserState
} from './types'
export const initialState: UserState = {
id: '',
name: '',
photo: '',
status: LoginStatus.forbidden
status: LoginStatus.forbidden,
provider: LoginProvider.EMAIL
}
export const UserReducer: Reducer<UserState, UserActions> = (state: UserState = initialState, action: UserActions) => {

View file

@ -20,6 +20,7 @@ export interface UserState {
id: string;
name: string;
photo: string;
provider: LoginProvider;
}
export enum LoginStatus {
@ -27,4 +28,18 @@ export enum LoginStatus {
ok = 'ok'
}
export enum LoginProvider {
FACEBOOK = 'facebook',
GITHUB = 'github',
TWITTER = 'twitter',
GITLAB = 'gitlab',
DROPBOX = 'dropbox',
GOOGLE = 'google',
SAML = 'saml',
OAUTH2 = 'oauth2',
EMAIL = 'email',
LDAP = 'ldap',
OPENID = 'openid'
}
export type UserActions = SetUserAction | ClearUserAction;

View file

@ -9,7 +9,8 @@ export const getAndSetUser: () => (Promise<void>) = async () => {
status: LoginStatus.ok,
id: me.id,
name: me.name,
photo: me.photo
photo: me.photo,
provider: me.provider
})
}