web: Added ASC.Web.Login

This commit is contained in:
Alexey Safronov 2020-11-24 13:20:14 +03:00
parent 140459460c
commit 88144e827c
15 changed files with 928 additions and 0 deletions

View File

@ -0,0 +1,7 @@
{
"presets": ["@babel/preset-react", "@babel/preset-env"],
"plugins": [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-class-properties"
]
}

1
web/ASC.Web.Login/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
dist/* linguist-vendored=false

116
web/ASC.Web.Login/.gitignore vendored Normal file
View File

@ -0,0 +1,116 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

View File

@ -0,0 +1,15 @@
FROM node:12
WORKDIR /usr/src/app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install
COPY . .
RUN yarn build
EXPOSE 8080
CMD [ "yarn", "build:start" ]

View File

@ -0,0 +1,9 @@
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"components": ["@appserver/components/src/components"]
}
},
"exclude": ["node_modules"]
}

View File

@ -0,0 +1,55 @@
{
"name": "@appserver/login",
"version": "0.1.0",
"private": "true",
"scripts": {
"build": "webpack --mode production",
"build:dev": "webpack --mode development",
"build:start": "cd dist && PORT=8080 npx serve",
"start": "webpack-dev-server --open --mode development",
"start:live": "webpack-dev-server --open --mode development --liveReload",
"docker:build": "docker build . -t login",
"docker:run": "docker run -p 8080:8080 login"
},
"devDependencies": {
"@babel/core": "7.9.6",
"@babel/plugin-proposal-class-properties": "^7.12.1",
"@babel/plugin-proposal-export-default-from": "^7.12.1",
"@babel/plugin-transform-runtime": "^7.12.1",
"@babel/preset-env": "^7.12.7",
"@babel/preset-react": "7.9.4",
"@svgr/webpack": "^5.5.0",
"babel-loader": "8.1.0",
"css-loader": "^3.6.0",
"html-webpack-plugin": "4.5.0",
"i18next": "^19.8.4",
"json-loader": "^0.5.7",
"react-i18next": "^11.7.3",
"source-map-loader": "^1.1.2",
"style-loader": "1.2.1",
"webpack": "5.0.0",
"webpack-cli": "3.3.11",
"webpack-dev-server": "3.11.0"
},
"dependencies": {
"@babel/runtime": "^7.12.5",
"attr-accept": "^2.2.2",
"email-addresses": "^3.1.0",
"moment": "^2.29.1",
"prop-types": "^15.7.2",
"rc-tree": "^4.0.0-beta.2",
"react": "^16.14.0",
"react-autosize-textarea": "^7.1.0",
"react-custom-scrollbars": "^4.2.1",
"react-dom": "^16.14.0",
"react-dropzone": "^11.2.4",
"react-onclickoutside": "^6.9.0",
"react-text-mask": "^5.4.3",
"react-toastify": "^6.1.0",
"react-tooltip": "^4.2.11",
"react-virtualized-auto-sizer": "^1.0.2",
"react-window": "^1.8.6",
"resize-image": "^0.1.0",
"styled-components": "^5.2.1"
}
}

View File

@ -0,0 +1,519 @@
import React, { Component, useEffect } from "react";
import PropTypes from "prop-types";
//import { withRouter } from "react-router";
import Box from "@appserver/components/src/components/box";
import Button from "@appserver/components/src/components/button";
import Text from "@appserver/components/src/components/text";
import TextInput from "@appserver/components/src/components/text-input";
import Link from "@appserver/components/src/components/link";
import toastr from "@appserver/components/src/components/toast";
import Checkbox from "@appserver/components/src/components/checkbox";
import HelpButton from "@appserver/components/src/components/help-button";
import PasswordInput from "@appserver/components/src/components/password-input";
import FieldContainer from "@appserver/components/src/components/field-container";
//import PageLayout from "../../components/PageLayout";
//import { connect } from "react-redux";
import styled from "styled-components";
import { withTranslation } from "react-i18next";
import i18n from "./i18n";
//import ForgotPasswordModalDialog from "./sub-components/forgot-password-modal-dialog";
// import {
// login,
// setIsLoaded,
// reloadPortalSettings,
// } from "../../store/auth/actions";
//import { getLanguage } from "../../store/auth/selectors";
//import { sendInstructionsToChangePassword } from "../../api/people";
//import Register from "./sub-components/register-container";
//import { createPasswordHash } from "../../utils";
//import history from "../../history";
//import { redirectToDefaultPage } from "../../utils";
const LoginContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
margin: 120px auto 0 auto;
max-width: 960px;
@media (max-width: 768px) {
padding: 0 16px;
max-width: 475px;
}
@media (max-width: 375px) {
margin: 72px auto 0 auto;
max-width: 311px;
}
.greeting-title {
width: 100%;
@media (max-width: 768px) {
text-align: left;
}
@media (max-width: 375px) {
font-size: 23px;
}
}
.auth-form-container {
margin: 32px 213px 0 213px;
width: 311px;
@media (max-width: 768px) {
margin: 32px 0 0 0;
width: 100%;
}
@media (max-width: 375px) {
margin: 32px 0 0 0;
width: 100%;
}
.login-forgot-wrapper {
height: 36px;
padding: 14px 0;
.login-checkbox-wrapper {
position: absolute;
display: inline-flex;
.login-checkbox {
float: left;
span {
font-size: 12px;
}
}
.login-tooltip {
display: inline-flex;
@media (min-width: 1025px) {
margin-left: 8px;
margin-top: 4px;
}
@media (max-width: 1024px) {
padding: 4px 8px 8px 8px;
}
}
}
.login-link {
float: right;
line-height: 16px;
}
}
.login-button {
margin-bottom: 16px;
}
.login-button-dialog {
margin-right: 8px;
}
.login-bottom-border {
width: 100%;
height: 1px;
background: #eceef1;
}
.login-bottom-text {
margin: 0 8px;
}
}
`;
class Form extends Component {
constructor(props) {
super(props);
this.state = {
identifierValid: true,
identifier: "",
isLoading: false,
isDisabled: false,
passwordValid: true,
password: "",
isChecked: false,
openDialog: false,
email: "",
emailError: false,
errorText: "",
socialButtons: [],
};
}
onChangeLogin = (event) => {
this.setState({ identifier: event.target.value });
!this.state.identifierValid && this.setState({ identifierValid: true });
this.state.errorText && this.setState({ errorText: "" });
};
onChangePassword = (event) => {
this.setState({ password: event.target.value });
!this.state.passwordValid && this.setState({ passwordValid: true });
this.state.errorText && this.setState({ errorText: "" });
};
onChangeEmail = (event) => {
this.setState({ email: event.target.value, emailError: false });
};
onChangeCheckbox = () => this.setState({ isChecked: !this.state.isChecked });
onClick = () => {
this.setState({
openDialog: true,
isDisabled: true,
email: this.state.identifier,
});
};
onKeyPress = (event) => {
if (event.key === "Enter") {
!this.state.isDisabled
? this.onSubmit()
: this.onSendPasswordInstructions();
}
};
onSendPasswordInstructions = () => {
if (!this.state.email.trim()) {
this.setState({ emailError: true });
} else {
this.setState({ isLoading: true });
sendInstructionsToChangePassword(this.state.email)
.then(
(res) => toastr.success(res),
(message) => toastr.error(message)
)
.finally(this.onDialogClose());
}
};
onDialogClose = () => {
this.setState({
openDialog: false,
isDisabled: false,
isLoading: false,
email: "",
emailError: false,
});
};
onSubmit = () => {
const { errorText, identifier, password } = this.state;
const { login, setIsLoaded, history, hashSettings, homepage } = this.props;
errorText && this.setState({ errorText: "" });
let hasError = false;
const userName = identifier.trim();
if (!userName) {
hasError = true;
this.setState({ identifierValid: !hasError });
}
const pass = password.trim();
if (!pass) {
hasError = true;
this.setState({ passwordValid: !hasError });
}
if (hasError) return false;
this.setState({ isLoading: true });
const hash = createPasswordHash(pass, hashSettings);
login(userName, hash)
.then(() => {
if (!redirectToDefaultPage()) {
setIsLoaded(true);
}
})
.catch((error) => {
this.setState({ errorText: error, isLoading: false });
});
};
componentDidMount() {
const {
match,
t,
hashSettings,
reloadPortalSettings,
organizationName,
} = this.props;
const { error, confirmedEmail } = {}; //match.params;
document.title = `${t("Authorization")} ${organizationName}`; //TODO: implement the setDocumentTitle() utility in ASC.Web.Common
error && this.setState({ errorText: error });
confirmedEmail && this.setState({ identifier: confirmedEmail });
window.addEventListener("keyup", this.onKeyPress);
// if (!hashSettings) {
// reloadPortalSettings();
// }
}
componentWillUnmount() {
window.removeEventListener("keyup", this.onKeyPress);
}
settings = {
minLength: 6,
upperCase: false,
digits: false,
specSymbols: false,
};
render() {
const { greetingTitle, match, t } = this.props;
const {
identifierValid,
identifier,
isLoading,
passwordValid,
password,
isChecked,
openDialog,
email,
emailError,
errorText,
socialButtons,
} = this.state;
const { confirmedEmail } = {}; //match.params;
//console.log("Login render");
return (
<>
<LoginContainer>
<Text
fontSize="32px"
fontWeight={600}
textAlign="center"
className="greeting-title"
>
{greetingTitle}
</Text>
<form className="auth-form-container">
<FieldContainer
isVertical={true}
labelVisible={false}
hasError={!identifierValid}
errorMessage={t("RequiredFieldMessage")}
>
<TextInput
id="login"
name="login"
hasError={!identifierValid}
value={identifier}
placeholder={t("RegistrationEmailWatermark")}
size="large"
scale={true}
isAutoFocussed={true}
tabIndex={1}
isDisabled={isLoading}
autoComplete="username"
onChange={this.onChangeLogin}
onKeyDown={this.onKeyPress}
/>
</FieldContainer>
<FieldContainer
isVertical={true}
labelVisible={false}
hasError={!passwordValid}
errorMessage={t("RequiredFieldMessage")}
>
<PasswordInput
simpleView={true}
passwordSettings={this.settings}
id="password"
inputName="password"
placeholder={t("Password")}
type="password"
hasError={!passwordValid}
inputValue={password}
size="large"
scale={true}
tabIndex={1}
isDisabled={isLoading}
autoComplete="current-password"
onChange={this.onChangePassword}
onKeyDown={this.onKeyPress}
/>
</FieldContainer>
<div className="login-forgot-wrapper">
<div className="login-checkbox-wrapper">
<Checkbox
className="login-checkbox"
isChecked={isChecked}
onChange={this.onChangeCheckbox}
label={<Text fontSize="13px">{t("Remember")}</Text>}
/>
<HelpButton
className="login-tooltip"
helpButtonHeaderContent={t("CookieSettingsTitle")}
tooltipContent={
<Text fontSize="12px">{t("RememberHelper")}</Text>
}
/>
</div>
<Link
fontSize="13px"
color="#316DAA"
className="login-link"
type="page"
isHovered={false}
onClick={this.onClick}
>
{t("ForgotPassword")}
</Link>
</div>
{/* {openDialog && (
<ForgotPasswordModalDialog
openDialog={openDialog}
isLoading={isLoading}
email={email}
emailError={emailError}
onChangeEmail={this.onChangeEmail}
onSendPasswordInstructions={this.onSendPasswordInstructions}
onDialogClose={this.onDialogClose}
t={t}
/>
)} */}
<Button
id="button"
className="login-button"
primary
size="large"
scale={true}
label={isLoading ? t("LoadingProcessing") : t("LoginButton")}
tabIndex={1}
isDisabled={isLoading}
isLoading={isLoading}
onClick={this.onSubmit}
/>
{confirmedEmail && (
<Text isBold={true} fontSize="16px">
{t("MessageEmailConfirmed")} {t("MessageAuthorize")}
</Text>
)}
<Text fontSize="14px" color="#c30">
{errorText}
</Text>
{socialButtons.length ? (
<Box displayProp="flex" alignItems="center">
<div className="login-bottom-border"></div>
<Text className="login-bottom-text" color="#A3A9AE">
{t("Or")}
</Text>
<div className="login-bottom-border"></div>
</Box>
) : null}
</form>
</LoginContainer>
</>
);
}
}
// Form.propTypes = {
// login: PropTypes.func.isRequired,
// match: PropTypes.object.isRequired,
// //history: PropTypes.object.isRequired,
// setIsLoaded: PropTypes.func.isRequired,
// greetingTitle: PropTypes.string.isRequired,
// t: PropTypes.func.isRequired,
// i18n: PropTypes.object.isRequired,
// language: PropTypes.string.isRequired,
// socialButtons: PropTypes.array,
// organizationName: PropTypes.string,
// homepage: PropTypes.string,
// };
Form.defaultProps = {
identifier: "",
password: "",
email: "",
};
const FormWrapper = withTranslation()(Form);
const LoginForm = (props) => <FormWrapper i18n={i18n} {...props} />;
export default LoginForm;
// const RegisterWrapper = withTranslation()(Register);
// const LoginForm = (props) => {
// const { language, isLoaded, enabledJoin } = props;
// useEffect(() => {
// i18n.changeLanguage(language);
// }, [language]);
// return (
// <>
// {isLoaded && (
// <>
// <PageLayout>
// <PageLayout.SectionBody>
// <>
// <FormWrapper i18n={i18n} {...props} />
// {enabledJoin && <RegisterWrapper i18n={i18n} {...props} />}
// </>
// </PageLayout.SectionBody>
// </PageLayout>
// </>
// )}
// </>
// );
// };
// LoginForm.defaultProps = {
// language: "en",
// };
// LoginForm.propTypes = {
// language: PropTypes.string.isRequired,
// isLoaded: PropTypes.bool,
// enabledJoin: PropTypes.bool,
// };
// function mapStateToProps(state) {
// const { isLoaded, settings } = state.auth;
// const {
// greetingSettings,
// enabledJoin,
// organizationName,
// hashSettings,
// } = settings;
// return {
// isLoaded,
// enabledJoin,
// organizationName,
// language: getLanguage(state),
// greetingTitle: greetingSettings,
// hashSettings,
// };
// }
// export default connect(mapStateToProps, {
// login,
// setIsLoaded,
// reloadPortalSettings,
// })(withRouter(LoginForm));

View File

@ -0,0 +1,15 @@
import React from "react";
import ReactDOM from "react-dom";
import LoginContent from "./LoginContent.jsx";
const LoginPage = () => {
return (
<LoginContent />
// <Provider store={store}>
// <Frame page="checkout" />
// </Provider>
);
};
ReactDOM.render(<LoginPage />, document.getElementById("app"));

View File

@ -0,0 +1,37 @@
import i18n from "i18next";
import en from "./locales/en/translation.json";
import ru from "./locales/ru/translation.json";
//import { i18nBaseSettings } from "../../constants";
const newInstance = i18n.createInstance();
const resources = {
en: {
translation: en,
},
ru: {
translation: ru,
},
};
//newInstance.init({ ...i18nBaseSettings, resources });
newInstance.init({
resources: resources,
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
format: function (value, format) {
if (format === "lowercase") return value.toLowerCase();
return value;
},
},
react: {
useSuspense: false,
},
});
export default newInstance;

View File

@ -0,0 +1,3 @@
body {
font-family: Arial, Helvetica, sans-serif;
}

View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

View File

@ -0,0 +1 @@
import("./LoginPage.jsx");

View File

@ -0,0 +1,30 @@
{
"LoadingProcessing": "Loading...",
"LoginButton": "Sign In",
"Password": "Password",
"RegistrationEmailWatermark": "E-mail",
"MessageEmailConfirmed": "Your email was activated successfully.",
"MessageAuthorize": "Please authorize yourself.",
"ForgotPassword": "Forgot your password?",
"PasswordRecoveryTitle": "Password recovery",
"PasswordRecoveryPlaceholder": "Your registration e-mail",
"MessageSendPasswordRecoveryInstructionsOnEmail": "Please enter the email you used while registering on the portal. The password recovery instructions will be send to that email address.",
"RegisterTitle": "Registration request",
"RegisterTextBodyBeforeDomainsList": "Registration is available to users with an email account at",
"RegisterTextBodyAfterDomainsList": "To register, enter your email and click on Send request. An email message with a link to activate your account will be sent to the specified email. Please enter the email address where the invitation will be sent:",
"RegisterPlaceholder": "Your registration e-mail",
"RegisterSendButton": "Send request",
"RegisterProcessSending": "Sending...",
"SendButton": "Send",
"RequiredFieldMessage": "Required field",
"CancelButton": "Cancel",
"Remember": "Remember me",
"RememberHelper": "The default session lifetime is 20 minutes. Check this option to set it to 1 year. To set your own value, go to the settings.",
"CookieSettingsTitle": "Session Lifetime",
"Authorization": "Authorization",
"Or": "OR",
"Register": "Register"
}

View File

@ -0,0 +1,30 @@
{
"LoadingProcessing": "Загрузка...",
"LoginButton": "Войти",
"Password": "Пароль",
"RegistrationEmailWatermark": "Регистрационный email",
"MessageEmailConfirmed": "Ваш email успешно активирован.",
"MessageAuthorize": "Пожалуйста авторизуйтесь.",
"ForgotPassword": "Забыли пароль?",
"PasswordRecoveryTitle": "Восстановление пароля",
"PasswordRecoveryPlaceholder": "Ваш регистрационный email",
"MessageSendPasswordRecoveryInstructionsOnEmail": "Пожалуйста, введите адрес электронной почты, указанный при регистрации на портале. Инструкции для восстановления пароля будут отправлены на этот адрес электронной почты.",
"RegisterTitle": "Запрос на регистрацию",
"RegisterTextBodyBeforeDomainsList": "Регистрация доступна для пользователей, которые имеют почтовый ящик на",
"RegisterTextBodyAfterDomainsList": "Чтобы зарегистрироваться, введите свой email и нажмите кнопку Отправить запрос. Сообщение со ссылкой для активации вашей учётной записи будет отправлено на указанный адрес.",
"RegisterPlaceholder": "Ваш регистрационный email",
"RegisterSendButton": "Отправить запрос",
"RegisterProcessSending": "Отправка...",
"SendButton": "Отправить",
"RequiredFieldMessage": "Обязательное поле",
"CancelButton": "Отмена",
"Remember": "Запомнить",
"RememberHelper": "Время существования сессии по умолчанию составляет 20 минут. Отметьте эту опцию, чтобы установить значение 1 год. Чтобы задать собственное значение, перейдите в настройки.",
"CookieSettingsTitle": "Время жизни сессии",
"Authorization": "Авторизация",
"Or": "ИЛИ",
"Register": "Регистрация"
}

View File

@ -0,0 +1,79 @@
const HtmlWebPackPlugin = require("html-webpack-plugin");
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const deps = require("./package.json").dependencies;
module.exports = {
output: {
publicPath: "http://localhost:8080/",
},
resolve: {
extensions: [".jsx", ".js", ".json"],
},
devServer: {
port: 8080,
},
module: {
rules: [
{
test: /\.m?js/,
type: "javascript/auto",
resolve: {
fullySpecified: false,
},
},
{
test: /\.react.svg$/,
use: ["@svgr/webpack"],
},
{ test: /\.json$/, loader: "json-loader" },
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-react", "@babel/preset-env"],
plugins: [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-export-default-from",
],
},
},
"source-map-loader",
],
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "login",
filename: "remoteEntry.js",
remotes: {},
exposes: {},
shared: {
...deps,
react: {
singleton: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
requiredVersion: deps["react-dom"],
},
},
}),
new HtmlWebPackPlugin({
template: "./src/index.html",
}),
],
};