@material-ui/icons#VisibilityOff JavaScript Examples

The following examples show how to use @material-ui/icons#VisibilityOff. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InputAdornmentPassword.js    From AED-Map with MIT License 6 votes vote down vote up
InputAdornmentPassword = ({ showPassword, handleClickShowPassword, handleMouseDownPassword }) => (
  <InputAdornment position="end">
    <IconButton
      onClick={handleClickShowPassword}
      onMouseDown={handleMouseDownPassword}
    >
      {showPassword ? <Visibility /> : <VisibilityOff />}
    </IconButton>
  </InputAdornment>
)
Example #2
Source File: eyeToggle.js    From horondi_client_fe with MIT License 6 votes vote down vote up
export function endAdornment(isVisible, setShowPass) {
  return {
    endAdornment: (
      <InputAdornment position='end'>
        <IconButton
          aria-label='toggle password visibility'
          onClick={(e) => toggleInputType(e, setShowPass)}
        >
          {isVisible ? <VisibilityOff /> : <Visibility />}
        </IconButton>
      </InputAdornment>
    )
  };
}
Example #3
Source File: LoginPage.js    From Quizzie with MIT License 4 votes vote down vote up
function LoginPage(props) {
	const [email, changeEmail] = useState("");
	const [emailError, setEmailError] = useState("");
	const [emailChanged, setEmailChanged] = useState(false);
	const [password, changePassword] = useState("");
	const [passwordError, setPasswordError] = useState("");
	const [passwordChanged, setPasswordChanged] = useState(false);

	const [showPassword, setShowPassword] = useState(false);

	const [didLogin, setDidLogin] = useState(null);
	const [errorText, setErrorText] = useState(
		"Error Logging In! Try again...."
	);
	const [redirect, setRedirect] = useState(false);
	const [ownerRedirect, setOwnerRedirect] = useState(false);
	const [loginRedirect, setLoginRedirect] = useState(false);

	const [notVerified, setNotVerified] = useState(false);
	const [verifyMail, setVerifyMail] = useState("");

	const type = props.match.params.type;
	const type1 = type === "user" ? "user" : "organizer";

	const [isLoading, setLoading] = useState(false);

	const { executeRecaptcha } = useGoogleReCaptcha();

	const { setLoggedIn, changeName, setAuthToken, setAdmin } = useContext(
		InfoContext
	);

	const mailErrorText = "Email cannot be empty";
	const passwordErrorText = "Password cannot be empty";

	const handleEmailChange = (event) => {
		setEmailChanged(true);
		changeEmail(event.target.value);
	};

	const handlePasswordChange = (event) => {
		setPasswordChanged(true);
		changePassword(event.target.value);
	};

	const togglePasswordVisibility = () => {
		setShowPassword(!showPassword);
	};

	const keyPress = (event) => {
		if (event.key === "Enter") {
			handleSubmit();
		}
	};

	useEffect(() => {
		if (email.length === 0) setEmailError(mailErrorText);
		else setEmailError("");

		if (password.length === 0) setPasswordError(passwordErrorText);
		else setPasswordError("");
	}, [email, password]);

	const handleSubmit = async (event) => {
		// event.preventDefault();

		setEmailChanged(true);
		setPasswordChanged(true);

		let errors = false;

		if (email.length === 0) {
			setEmailError(mailErrorText);
			errors = true;
		} else if (!EmailValidator.validate(email)) {
			setEmailError("Invalid email address!");
			errors = true;
		}
		if (password.length === 0) {
			setPasswordError(passwordErrorText);
			errors = true;
		} else if (password.length < 8) {
			setPasswordError("Minimum length of password must be 8.");
			errors = true;
		}

		if (!errors && emailError.length === 0 && passwordError.length === 0) {
			setLoading(true);
			let lType = type;

			if (type === "organizer") lType = "admin";

			let url = `https://quizzie-api.herokuapp.com/${lType}/login`;
			let token = await executeRecaptcha("login_page");

			let data = {
				email: email,
				password: password,
				captcha: token,
			};

			let response = null;
			try {
				await axios.post(url, data).then((res) => {
					response = res;
				});

				if (response.status === 200) {
					changeName(response.data.userDetails.name);
					setLoggedIn(true);
					setAuthToken(response.data.token);

					localStorage.setItem("userLoggedIn", true);
					localStorage.setItem(
						"name",
						response.data.userDetails.name
					);
					localStorage.setItem("authToken", response.data.token);

					if (type === "owner") {
						setOwnerRedirect(true);
						//TODO: Redirect dashboard shit
					} else {
						setRedirect(true);
					}
				}
			} catch (error) {
				console.log(error);
				if (error.response.status === 409) {
					setVerifyMail(data.email);
					setNotVerified(true);
				} else if (error.response.status === 401) {
					setErrorText("Invalid Credentials...");
					setDidLogin(false);
				} else {
					setErrorText("Error Logging In! Try again....");
					setDidLogin(false);
				}
			}
		}
		setLoading(false);
	};

	useEffect(() => {
		if (type !== "user" && type !== "organizer" && type !== "owner") {
			setRedirect(true);
		}
	}, [type]);

	if (redirect === true) {
		return <Redirect to="/" />;
	} else if (ownerRedirect) {
		return <Redirect to="/coronilOP" />;
	}
	return isLoading ? (
		<Loading />
	) : (
		<Container className="login-page">
			<div className="login-form">
				<Typography variant="h3" color="primary" className="login-head">
					{type === "user"
						? "Login Now"
						: type === "organizer"
						? "Organizer Login"
						: "Owner Login"}
				</Typography>
				<br />
				{didLogin === false ? (
					<Alert severity="error">{errorText}</Alert>
				) : null}
				{notVerified ? (
					<Alert severity="error">
						Your email is not verified.
						<Link
							className="link"
							style={{ color: "red" }}
							to={{
								pathname: `/verify/${type}`,
								state: {
									email: verifyMail,
									sendCode: true,
								},
							}}
						>
							Click here to verify...
						</Link>
					</Alert>
				) : null}
				{type !== "owner" ? (
					<a
						href={
							type === "user"
								? "https://quizzie-api.herokuapp.com/auth/google"
								: "https://quizzie-api.herokuapp.com/auth/admin/google"
						}
						className="google-link"
					>
						<div className="google-btn">
							<div className="google-icon-wrapper">
								<img
									className="google-icon"
									src="https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg"
								/>
							</div>
							<p className="btn-text">
								<b>Sign in with Google</b>
							</p>
						</div>
					</a>
				) : null}
				<form className="form">
					<TextInput
						error={
							emailChanged
								? emailError.length === 0
									? false
									: true
								: false
						}
						helperText={
							emailChanged
								? emailError.length === 0
									? null
									: emailError
								: null
						}
						id="email"
						label="Email"
						type="email"
						className="form-input"
						variant="outlined"
						value={email}
						onChange={handleEmailChange}
						onKeyPress={keyPress}
					></TextInput>
					<br />
					<TextInput
						error={
							passwordChanged
								? passwordError.length === 0
									? false
									: true
								: false
						}
						helperText={
							passwordChanged
								? passwordError.length === 0
									? null
									: passwordError
								: null
						}
						id="password"
						type={showPassword ? "text" : "password"}
						label="Password"
						className="form-input"
						variant="outlined"
						value={password}
						onChange={handlePasswordChange}
						onKeyPress={keyPress}
						InputProps={{
							endAdornment: (
								<InputAdornment position="end">
									<IconButton
										aria-label="show password"
										onClick={togglePasswordVisibility}
										edge="end"
									>
										{showPassword ? (
											<Visibility />
										) : (
											<VisibilityOff />
										)}
									</IconButton>
								</InputAdornment>
							),
						}}
					></TextInput>
				</form>
				<div className="forgot-section">
					{type === "owner" ? null : (
						<Link
							to={`/forgotPassword/${type}`}
							className="link forgot-pass"
						>
							Forgot your password?
						</Link>
					)}
				</div>
				<Button className="login-btn" onClick={handleSubmit}>
					Login
				</Button>
				<Link to={`/register/${type}`} className="link register-link">
					Don't have an account? Join the Quizzie now!
				</Link>
			</div>
		</Container>
	);
}
Example #4
Source File: RegisterPage.js    From Quizzie with MIT License 4 votes vote down vote up
function RegisterPage(props) {
	const [name, changeName] = useState("");
	const [nameError, setNameError] = useState("");
	const [nameChanged, setNameChanged] = useState(false);

	const [phoneNumber, setPhoneNumber] = useState("");
	const [phoneNumberError, setPhoneNumberError] = useState("");
	const [phoneNumberChanged, setPhoneNumberChanged] = useState(false);

	const [boardPosition, setBoardPosition] = useState("");
	const [boardPositionError, setBoardPositionError] = useState("");
	const [boardPositionChanged, setBoardPositionChanged] = useState(false);

	const [email, changeEmail] = useState("");
	const [emailError, setEmailError] = useState("");
	const [emailChanged, setEmailChanged] = useState(false);

	const [password, changePassword] = useState("");
	const [passwordError, setPasswordError] = useState("");
	const [passwordChanged, setPasswordChanged] = useState(false);
	const [showPassword, setShowPassword] = useState(false);

	const [code, setCode] = useState("");
	const [codeError, setCodeError] = useState("");
	const [codeChanged, setCodeChanged] = useState(false);

	const [redirect, setRedirect] = useState(false);
	const [redirectMain, setRedirectMain] = useState(false);

	const [signedUp, setSignedUp] = useState(false);
	const [existEmail, setExistEmail] = useState(false);
	const [isLoading, setLoading] = useState(false);
	const [error, setError] = useState(false);
	const [errorText, setErrorText] = useState("");

	const type = props.match.params.type;
	const { executeRecaptcha } = useGoogleReCaptcha();

	const emptyText = (type) => `${type} cannot be empty`;

	const handleNameChange = (event) => {
		setNameChanged(true);
		changeName(event.target.value);
	};

	const handlePhoneChange = (event) => {
		setPhoneNumberChanged(true);
		setPhoneNumber(event.target.value);
	};

	const handleBoardPositionChange = (event) => {
		setBoardPositionChanged(true);
		setBoardPosition(event.target.value);
	};

	const handleEmailChange = (event) => {
		setEmailChanged(true);
		changeEmail(event.target.value);
	};

	const handlePasswordChange = (event) => {
		setPasswordChanged(true);
		changePassword(event.target.value);
	};

	const handleCodeChange = (event) => {
		setCodeChanged(true);
		setCode(event.target.value);
	};

	const togglePasswordVisibility = () => {
		setShowPassword(!showPassword);
	};

	const keyPress = (event) => {
		if (event.key === "Enter") {
			handleSubmit();
		}
	};

	useEffect(() => {
		if (name.length === 0) setNameError(emptyText("Name"));
		else setNameError("");

		if (email.length === 0) setEmailError(emptyText("Email"));
		else setEmailError("");

		if (password.length === 0) setPasswordError(emptyText("Password"));
		else setPasswordError("");

		if (phoneNumber.length === 0)
			setPhoneNumberError(emptyText("Phone Number"));
		else setPhoneNumberError("");

		if (type === "owner") {
			if (boardPosition.length === 0)
				setBoardPositionError(emptyText("Board Position"));
			else setBoardPositionError("");

			if (code.length === 0) setCodeError(emptyText("Secret Code"));
			else setCodeError("");
		}
	}, [name, email, password, phoneNumber, boardPosition, code]);

	const handleSubmit = async (event) => {
		// event.preventDefault();
		setNameChanged(true);
		setPasswordChanged(true);
		setEmailChanged(true);
		setPhoneNumberChanged(true);

		if (type === "owner") {
			setBoardPositionChanged(true);
			setCodeChanged(true);
		}

		let errors = false;

		if (name.trim().length === 0) {
			setEmailError(emptyText("Name"));
			errors = true;
		}

		if (email.trim().length === 0) {
			setEmailError(emptyText("Email"));
			errors = true;
		} else if (!EmailValidator.validate(email)) {
			setEmailError("Invalid email address!");
			errors = true;
		}
		if (password.trim().length === 0) {
			setPasswordError(emptyText("Password"));
			errors = true;
		} else if (password.length < 8) {
			setPasswordError("Minimum length of password must be 8.");
			errors = true;
		}

		if (type === "owner") {
			if (boardPosition.trim().length === 0) {
				setBoardPositionError(emptyText("Board Position"));
				errors = true;
			}

			if (code.trim().length === 0) {
				setCodeError(emptyText("Secret Code"));
				errors = true;
			}
		}

		if (phoneNumber.trim().length === 0) {
			setPhoneNumberError(emptyText("Phone Number"));
			errors = true;
		} else if (phoneNumber.length !== 10) {
			setPhoneNumberError("Invalid phone number");
			errors = true;
		}

		if (!errors && emailError.length === 0 && passwordError.length === 0) {
			setLoading(true);
			let sType = type;

			if (type === "organizer") sType = "admin";

			let url = `https://quizzie-api.herokuapp.com/${sType}/signup`;

			let data = null;

			let token = await executeRecaptcha("signup_page");
			console.log(token);

			if (type === "owner") {
				data = {
					name: name,
					email: email,
					password: password,
					mobileNumber: phoneNumber,
					boardPosition: boardPosition,
					signupCode: code,
					captcha: token,
				};
			} else {
				data = {
					name: name,
					email: email,
					password: password,
					mobileNumber: phoneNumber,
					captcha: token,
				};
			}

			let response = null;
			try {
				await axios.post(url, data).then((res) => {
					response = res;
				});

				if (response.status === 201) {
					setSignedUp(true);
					setRedirect(true);
				}
			} catch (error) {
				if (error.response.status === 409) {
					setErrorText("Account already exists...");
				} else if (type === "owner" && error.response.status === 400) {
					setErrorText("Wrong secret code...");
				} else {
					setErrorText("There was some error!");
				}
				setPasswordChanged(false);
				changePassword("");
				setError(true);
			}
		}
		setLoading(false);
	};

	useEffect(() => {
		if (type !== "user" && type !== "organizer" && type !== "owner") {
			setRedirectMain(true);
		}
	}, [type]);

	if (redirect === true) {
		let to =
			type === "user"
				? "user"
				: type === "organizer"
				? "organizer"
				: "owner";
		return (
			<Redirect
				to={{
					pathname: `/verify/${to}`,
					state: {
						email: email,
					},
				}}
			/>
		);
	} else if (redirectMain) {
		return <Redirect to="/" />;
	}
	return isLoading ? (
		<Loading />
	) : (
		<Container className="login-page">
			<div className="login-form">
				<Typography
					variant="h3"
					color="primary"
					className="login-head signup-text"
				>
					{type === "user"
						? "Join the force!"
						: type === "organizer"
						? "Organizer Sign Up"
						: "Owner Signup"}
				</Typography>
				<br />
				{signedUp === true ? (
					<Alert severity="success" color="warning">
						Succesfully Signed Up! Redirecting...
					</Alert>
				) : null}
				{error === true ? (
					<Alert severity="error" color="error">
						{errorText}
					</Alert>
				) : null}
				{type !== "owner" ? (
					<a
						href={
							type === "user"
								? "https://quizzie-api.herokuapp.com/auth/google"
								: "https://quizzie-api.herokuapp.com/auth/admin/google"
						}
						className="google-link"
					>
						<div className="google-btn">
							<div className="google-icon-wrapper">
								<img
									className="google-icon"
									src="https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg"
								/>
							</div>
							<p className="btn-text">
								<b>Sign up with Google</b>
							</p>
						</div>
					</a>
				) : null}
				<form className="form">
					<TextInput
						error={
							nameChanged
								? nameError.length === 0
									? false
									: true
								: false
						}
						helperText={
							nameChanged
								? nameError.length === 0
									? null
									: nameError
								: null
						}
						id="name"
						label="Name"
						type="text"
						className="form-input"
						variant="outlined"
						value={name}
						onChange={handleNameChange}
						onKeyPress={keyPress}
					></TextInput>
					<TextInput
						error={
							phoneNumberChanged
								? phoneNumberError.length === 0
									? false
									: true
								: false
						}
						helperText={
							phoneNumberChanged
								? phoneNumberError.length === 0
									? null
									: phoneNumberError
								: null
						}
						id="phone-number"
						label="Phone Number"
						type="text"
						className="form-input"
						variant="outlined"
						value={phoneNumber}
						onChange={handlePhoneChange}
						onKeyPress={keyPress}
					></TextInput>
					{type === "owner" ? (
						<TextInput
							error={
								boardPositionChanged
									? boardPositionError.length === 0
										? false
										: true
									: false
							}
							helperText={
								boardPositionChanged
									? boardPositionError.length === 0
										? null
										: boardPositionError
									: null
							}
							id="board-position"
							label="Board Position"
							type="text"
							className="form-input"
							variant="outlined"
							value={boardPosition}
							onChange={handleBoardPositionChange}
							onKeyPress={keyPress}
						></TextInput>
					) : null}
					<TextInput
						error={
							emailChanged
								? emailError.length === 0
									? false
									: true
								: false
						}
						helperText={
							emailChanged
								? emailError.length === 0
									? null
									: emailError
								: null
						}
						id="email"
						label="Email"
						type="email"
						className="form-input"
						variant="outlined"
						value={email}
						onChange={handleEmailChange}
						onKeyPress={keyPress}
					></TextInput>
					<TextInput
						error={
							passwordChanged
								? passwordError.length === 0
									? false
									: true
								: false
						}
						helperText={
							passwordChanged
								? passwordError.length === 0
									? null
									: passwordError
								: null
						}
						id="password"
						type={showPassword ? "text" : "password"}
						label="Password"
						className="form-input"
						variant="outlined"
						value={password}
						onChange={handlePasswordChange}
						onKeyPress={keyPress}
						InputProps={{
							endAdornment: (
								<InputAdornment position="end">
									<IconButton
										aria-label="show password"
										onClick={togglePasswordVisibility}
										edge="end"
									>
										{showPassword ? (
											<Visibility />
										) : (
											<VisibilityOff />
										)}
									</IconButton>
								</InputAdornment>
							),
						}}
					></TextInput>
					{type === "owner" ? (
						<TextInput
							error={
								codeChanged
									? codeError.length === 0
										? false
										: true
									: false
							}
							helperText={
								codeChanged
									? codeError.length === 0
										? null
										: codeError
									: null
							}
							id="owner-code"
							label="Secret Code"
							type="text"
							className="form-input"
							variant="outlined"
							value={code}
							onChange={handleCodeChange}
							onKeyPress={keyPress}
						></TextInput>
					) : null}
				</form>
				<Button className="login-btn signup-btn" onClick={handleSubmit}>
					Sign Up
				</Button>
				{/* <Link to="/registerOrganiser" className="link register-link">Are you an Organiser? Go to the organiser signup!</Link> */}
			</div>
		</Container>
	);
}
Example #5
Source File: ChangePasswordDialog.js    From aws-amplify-identity-broker with MIT License 4 votes vote down vote up
ChangePasswordDialog = (props) => {
	const classes = useStyles();
	const [oldPassword, setOldPassword] = React.useState({
		password: '',
		showPassword: false
	});
	const [newPassword, setNewPassword] = React.useState({
		password: '',
		showPassword: false
	});
	const [snackBarOps, setSnackBarOps] = React.useState({
		type: 'info',
		open: false,
		vertical: 'top',
		horizontal: 'center',
		autoHide: 0,
		message: ''
	});

	const changePassword = (oldPassword, newPassword) => {
		if (!oldPassword || !newPassword) {
			setSnackBarOps({
				type: 'error',
				open: true,
				vertical: 'top',
				horizontal: 'center',
				autoHide: 3000,
				message: I18n.get('CHANGE_PASSWORD_MESSAGE_EROR')
			})
			return;
		}

		Auth.currentAuthenticatedUser()
			.then(CognitoUser => {
				Auth.changePassword(CognitoUser, oldPassword, newPassword)
					.then((data) => {
						handleCancel(data === 'SUCCESS');
					})
					.catch((err) => {
						console.log(err);

						setSnackBarOps({
							type: 'error',
							open: true,
							vertical: 'top',
							horizontal: 'center',
							autoHide: 3000,
							message: I18n.get('CHANGE_PASSWORD_MESSAGE_EROR')
						})
					})
			})
			.catch(err => {
				console.log(err);

				setSnackBarOps({
					type: 'error',
					open: true,
					vertical: 'top',
					horizontal: 'center',
					autoHide: 3000,
					message: I18n.get('CHANGE_PASSWORD_MESSAGE_EROR')
				})
			})
	};

	const handleMouseDownPassword = (event) => {
		event.preventDefault();
	};

	const handleChangeOldPassword = (value) => {
		setOldPassword({ ...oldPassword, password: value })
	};

	const handleChangeNewPassword = (value) => {
		setNewPassword({ ...newPassword, password: value })
	};

	const handleClickSave = () => {
		changePassword(oldPassword.password, newPassword.password)
	};

	const handleCancel = (succesful = false) => {
		setOldPassword({ ...oldPassword, password: '' });
		setNewPassword({ ...newPassword, password: '' });
		props.close(succesful);
	};

	return (
		<div>
			{snackBarOps.open && (
				<AppSnackbar ops={snackBarOps} />
			)}

			<Dialog
				open={props.open}
				onClose={handleCancel}
				disableBackdropClick
				aria-labelledby="change-password-dialog"
			>
				<DialogTitle id="change-password-dialog-title">
					{I18n.get('CHANGE_PASSWORD_TITLE')}
				</DialogTitle>
				<DialogContent className={classes.dialogContent}>
					<DialogContentText>
						{I18n.get('CHANGE_PASSWORD_DESCRIPTION')}
					</DialogContentText>
					<Box className={classes.box}>
						<FormControl>
							<InputLabel htmlFor="inputOldPassword">
								{I18n.get('CHANGE_PASSWORD_OLDPASSWORD_INPUT_LABEL')}
							</InputLabel>
							<Input
								value={oldPassword.password}
								type={oldPassword.showPassword ? 'text' : 'password'}
								onChange={(event) => handleChangeOldPassword(event.target.value)}
								id="inputOldPassword"
								startAdornment={
									<InputAdornment position="start">
										<VpnKey className={classes.textFieldIcon} />
									</InputAdornment>
								}
								endAdornment={
									<InputAdornment position="end">
										<IconButton
											aria-label="toggle password visibility"
											onClick={() => setOldPassword({ ...oldPassword, showPassword: !oldPassword.showPassword })}
											onMouseDown={handleMouseDownPassword}
											edge="end"
										>
											{oldPassword.showPassword ? <Visibility /> : <VisibilityOff />}
										</IconButton>
									</InputAdornment>
								}
								className={classes.input}
								autoFocus
								inputProps={{ style: { left: 0 } }}
							/>
						</FormControl>
					</Box>
					<Box className={classes.box}>
						<FormControl>
							<InputLabel htmlFor="inputNewPassword">
								{I18n.get('CHANGE_PASSWORD_NEWPASSWORD_INPUT_LABEL')}
							</InputLabel>
							<Input
								value={newPassword.password}
								type={newPassword.showPassword ? 'text' : 'password'}
								onChange={(event) => handleChangeNewPassword(event.target.value)}
								id="inputNewPassword"
								startAdornment={
									<InputAdornment position="start">
										<VpnKey className={classes.textFieldIcon} />
									</InputAdornment>
								}
								endAdornment={
									<InputAdornment position="end">
										<IconButton
											aria-label="toggle password visibility"
											onClick={() => setNewPassword({ ...newPassword, showPassword: !newPassword.showPassword })}
											onMouseDown={handleMouseDownPassword}
											edge="end"
										>
											{newPassword.showPassword ? <Visibility /> : <VisibilityOff />}
										</IconButton>
									</InputAdornment>
								}
								className={classes.input}
								inputProps={{ style: { left: 0 } }}
							/>
						</FormControl>
					</Box>
				</DialogContent>
				<DialogActions className={classes.dialogActions}>
					<Button
						variant="outlined"
						onClick={handleClickSave}
						className={classes.buttonSave}
					>
						{I18n.get('CHANGE_PASSWORD_SAVE_BUTTON_LABEL')}
					</Button>
					<Button
						variant="outlined"
						onClick={handleCancel}
						className={classes.buttonCancel}
					>
						{I18n.get('CHANGE_PASSWORD_CANCEL_BUTTON_LABEL')}
					</Button>
				</DialogActions>
			</Dialog>
		</div>
	);
}
Example #6
Source File: index.js    From whaticket with MIT License 4 votes vote down vote up
UserModal = ({ open, onClose, userId }) => {
	const classes = useStyles();

	const initialState = {
		name: "",
		email: "",
		password: "",
		profile: "user"
	};

	const { user: loggedInUser } = useContext(AuthContext);

	const [user, setUser] = useState(initialState);
	const [selectedQueueIds, setSelectedQueueIds] = useState([]);
	const [showPassword, setShowPassword] = useState(false);
	const [whatsappId, setWhatsappId] = useState(false);
	const {loading, whatsApps} = useWhatsApps();

	useEffect(() => {
		const fetchUser = async () => {
			if (!userId) return;
			try {
				const { data } = await api.get(`/users/${userId}`);
				setUser(prevState => {
					return { ...prevState, ...data };
				});
				const userQueueIds = data.queues?.map(queue => queue.id);
				setSelectedQueueIds(userQueueIds);
				setWhatsappId(data.whatsappId ? data.whatsappId : '');
			} catch (err) {
				toastError(err);
			}
		};

		fetchUser();
	}, [userId, open]);

	const handleClose = () => {
		onClose();
		setUser(initialState);
	};

	const handleSaveUser = async values => {
		const userData = { ...values, whatsappId, queueIds: selectedQueueIds };
		try {
			if (userId) {
				await api.put(`/users/${userId}`, userData);
			} else {
				await api.post("/users", userData);
			}
			toast.success(i18n.t("userModal.success"));
		} catch (err) {
			toastError(err);
		}
		handleClose();
	};

	return (
		<div className={classes.root}>
			<Dialog
				open={open}
				onClose={handleClose}
				maxWidth="xs"
				fullWidth
				scroll="paper"
			>
				<DialogTitle id="form-dialog-title">
					{userId
						? `${i18n.t("userModal.title.edit")}`
						: `${i18n.t("userModal.title.add")}`}
				</DialogTitle>
				<Formik
					initialValues={user}
					enableReinitialize={true}
					validationSchema={UserSchema}
					onSubmit={(values, actions) => {
						setTimeout(() => {
							handleSaveUser(values);
							actions.setSubmitting(false);
						}, 400);
					}}
				>
					{({ touched, errors, isSubmitting }) => (
						<Form>
							<DialogContent dividers>
								<div className={classes.multFieldLine}>
									<Field
										as={TextField}
										label={i18n.t("userModal.form.name")}
										autoFocus
										name="name"
										error={touched.name && Boolean(errors.name)}
										helperText={touched.name && errors.name}
										variant="outlined"
										margin="dense"
										fullWidth
									/>
									<Field
										as={TextField}
										name="password"
										variant="outlined"
										margin="dense"
										label={i18n.t("userModal.form.password")}
										error={touched.password && Boolean(errors.password)}
										helperText={touched.password && errors.password}
										type={showPassword ? 'text' : 'password'}
										InputProps={{
										endAdornment: (
											<InputAdornment position="end">
											<IconButton
												aria-label="toggle password visibility"
												onClick={() => setShowPassword((e) => !e)}
											>
												{showPassword ? <VisibilityOff /> : <Visibility />}
											</IconButton>
											</InputAdornment>
										)
										}}
										fullWidth
									/>
								</div>
								<div className={classes.multFieldLine}>
									<Field
										as={TextField}
										label={i18n.t("userModal.form.email")}
										name="email"
										error={touched.email && Boolean(errors.email)}
										helperText={touched.email && errors.email}
										variant="outlined"
										margin="dense"
										fullWidth
									/>
									<FormControl
										variant="outlined"
										className={classes.formControl}
										margin="dense"
									>
										<Can
											role={loggedInUser.profile}
											perform="user-modal:editProfile"
											yes={() => (
												<>
													<InputLabel id="profile-selection-input-label">
														{i18n.t("userModal.form.profile")}
													</InputLabel>

													<Field
														as={Select}
														label={i18n.t("userModal.form.profile")}
														name="profile"
														labelId="profile-selection-label"
														id="profile-selection"
														required
													>
														<MenuItem value="admin">Admin</MenuItem>
														<MenuItem value="user">User</MenuItem>
													</Field>
												</>
											)}
										/>
									</FormControl>
								</div>
								<Can
									role={loggedInUser.profile}
									perform="user-modal:editQueues"
									yes={() => (
										<QueueSelect
											selectedQueueIds={selectedQueueIds}
											onChange={values => setSelectedQueueIds(values)}
										/>
									)}
								/>
								<Can
									role={loggedInUser.profile}
									perform="user-modal:editQueues"
									yes={() => (!loading &&
										<FormControl variant="outlined" margin="dense" className={classes.maxWidth} fullWidth>
											<InputLabel>{i18n.t("userModal.form.whatsapp")}</InputLabel>
											<Field
												as={Select}
												value={whatsappId}
												onChange={(e) => setWhatsappId(e.target.value)}
												label={i18n.t("userModal.form.whatsapp")}
											>
												<MenuItem value={''}>&nbsp;</MenuItem>
												{whatsApps.map((whatsapp) => (
													<MenuItem key={whatsapp.id} value={whatsapp.id}>{whatsapp.name}</MenuItem>
												))}
											</Field>
										</FormControl>
									)}
								/>
							</DialogContent>
							<DialogActions>
								<Button
									onClick={handleClose}
									color="secondary"
									disabled={isSubmitting}
									variant="outlined"
								>
									{i18n.t("userModal.buttons.cancel")}
								</Button>
								<Button
									type="submit"
									color="primary"
									disabled={isSubmitting}
									variant="contained"
									className={classes.btnWrapper}
								>
									{userId
										? `${i18n.t("userModal.buttons.okEdit")}`
										: `${i18n.t("userModal.buttons.okAdd")}`}
									{isSubmitting && (
										<CircularProgress
											size={24}
											className={classes.buttonProgress}
										/>
									)}
								</Button>
							</DialogActions>
						</Form>
					)}
				</Formik>
			</Dialog>
		</div>
	);
}
Example #7
Source File: index.js    From whaticket with MIT License 4 votes vote down vote up
Login = () => {
  const classes = useStyles();

  const [user, setUser] = useState({ email: "", password: "" });
  const [showPassword, setShowPassword] = useState(false);

  const { handleLogin } = useContext(AuthContext);

  const handleChangeInput = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value });
  };

  const handlSubmit = (e) => {
    e.preventDefault();
    handleLogin(user);
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlined />
        </Avatar>
        <Typography component="h1" variant="h5">
          {i18n.t("login.title")}
        </Typography>
        <form className={classes.form} noValidate onSubmit={handlSubmit}>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label={i18n.t("login.form.email")}
            name="email"
            value={user.email}
            onChange={handleChangeInput}
            autoComplete="email"
            autoFocus
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label={i18n.t("login.form.password")}
            id="password"
            value={user.password}
            onChange={handleChangeInput}
            autoComplete="current-password"
            type={showPassword ? 'text' : 'password'}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    aria-label="toggle password visibility"
                    onClick={() => setShowPassword((e) => !e)}
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              )
            }}
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
          >
            {i18n.t("login.buttons.submit")}
          </Button>
          <Grid container>
            <Grid item>
              <Link
                href="#"
                variant="body2"
                component={RouterLink}
                to="/signup"
              >
                {i18n.t("login.buttons.register")}
              </Link>
            </Grid>
          </Grid>
        </form>
      </div>
      <Box mt={8}>{/* <Copyright /> */}</Box>
    </Container>
  );
}
Example #8
Source File: index.js    From whaticket with MIT License 4 votes vote down vote up
SignUp = () => {
	const classes = useStyles();
	const history = useHistory();

	const initialState = { name: "", email: "", password: "" };
	const [showPassword, setShowPassword] = useState(false);
	const [user] = useState(initialState);

	const handleSignUp = async values => {
		try {
			await api.post("/auth/signup", values);
			toast.success(i18n.t("signup.toasts.success"));
			history.push("/login");
		} catch (err) {
			toastError(err);
		}
	};

	return (
		<Container component="main" maxWidth="xs">
			<CssBaseline />
			<div className={classes.paper}>
				<Avatar className={classes.avatar}>
					<LockOutlined />
				</Avatar>
				<Typography component="h1" variant="h5">
					{i18n.t("signup.title")}
				</Typography>
				{/* <form className={classes.form} noValidate onSubmit={handleSignUp}> */}
				<Formik
					initialValues={user}
					enableReinitialize={true}
					validationSchema={UserSchema}
					onSubmit={(values, actions) => {
						setTimeout(() => {
							handleSignUp(values);
							actions.setSubmitting(false);
						}, 400);
					}}
				>
					{({ touched, errors, isSubmitting }) => (
						<Form className={classes.form}>
							<Grid container spacing={2}>
								<Grid item xs={12}>
									<Field
										as={TextField}
										autoComplete="name"
										name="name"
										error={touched.name && Boolean(errors.name)}
										helperText={touched.name && errors.name}
										variant="outlined"
										fullWidth
										id="name"
										label={i18n.t("signup.form.name")}
										autoFocus
									/>
								</Grid>

								<Grid item xs={12}>
									<Field
										as={TextField}
										variant="outlined"
										fullWidth
										id="email"
										label={i18n.t("signup.form.email")}
										name="email"
										error={touched.email && Boolean(errors.email)}
										helperText={touched.email && errors.email}
										autoComplete="email"
									/>
								</Grid>
								<Grid item xs={12}>
									<Field
										as={TextField}
										variant="outlined"
										fullWidth
										name="password"
										id="password"
										autoComplete="current-password"
										error={touched.password && Boolean(errors.password)}
										helperText={touched.password && errors.password}
										label={i18n.t("signup.form.password")}
										type={showPassword ? 'text' : 'password'}
										InputProps={{
											endAdornment: (
												<InputAdornment position="end">
													<IconButton
														aria-label="toggle password visibility"
														onClick={() => setShowPassword((e) => !e)}
													>
														{showPassword ? <VisibilityOff /> : <Visibility />}
													</IconButton>
												</InputAdornment>
											)
										}}
									/>
								</Grid>
							</Grid>
							<Button
								type="submit"
								fullWidth
								variant="contained"
								color="primary"
								className={classes.submit}
							>
								{i18n.t("signup.buttons.submit")}
							</Button>
							<Grid container justifyContent="flex-end">
								<Grid item>
									<Link
										href="#"
										variant="body2"
										component={RouterLink}
										to="/login"
									>
										{i18n.t("signup.buttons.login")}
									</Link>
								</Grid>
							</Grid>
						</Form>
					)}
				</Formik>
			</div>
			<Box mt={5}>{/* <Copyright /> */}</Box>
		</Container>
	);
}
Example #9
Source File: App.js    From covid-vaccine-notification-system with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/*
  *	Author:- Rahul Malhotra
  *	Description:- This method is used to render the UI
  */
  render() {
    const { classes } = this.props;
    const {
      states,
      districts,
      vaccines,
      prices,
      ages,
      centreIdsToSkip,
      searchOptions,
      hasSearched,
      vaccinesData,
      notify,
      selectedSearchBy,
      pincode,
      hasError,
      selectedState,
      selectedDistrict,
      selectedAge,
      selectedVaccine,
      selectedVaccinePrice,
      minDose1,
      minDose2,
      showBookVaccineConfirmationModal
    } = this.state;
    let showHiddenVaccineCentersButton, notifyButton, clearNotifyButton;

    // * Setting up show hidden vaccination centres button
    if (centreIdsToSkip.length) {
      showHiddenVaccineCentersButton = (
        <FormControl className={classes.formControl}>
          <Button
            variant="contained"
            color="secondary"
            onClick={this.clearCentreIdsToSkip.bind(this)}
            startIcon={<Visibility />}
          >
            Show Hidden Vaccination Centres
          </Button>
        </FormControl>
      );
    }

    // * Setting up notifications button
    if (
      hasSearched &&
      vaccinesData.length === 0 &&
      !notify &&
      (
        (
          selectedSearchBy === 'district' &&
          this.stateSelected() &&
          this.districtSelected()
        ) ||
        (
          selectedSearchBy === 'pincode' &&
          this.pincodeEntered()
        )
      )
    ) {
      notifyButton = (
        <FormControl className={classes.formControl}>
          <Button
            variant="contained"
            color="primary"
            onClick={this.notifyVaccineAvailability.bind(this)}
            endIcon={<Notifications />}
          >
            Notify me when vaccines are available
          </Button>
        </FormControl>
      );
    }

    // * Setting up stop notifications button
    if (notify) {
      clearNotifyButton = (
        <FormControl className={classes.formControl}>
          <Button
            variant="contained"
            color="secondary"
            onClick={this.clearNotificationSearch.bind(this)}
            endIcon={<Close />}
          >
            Stop Notifications
          </Button>
        </FormControl>
      )
    }

    // * Setting up the UI
  return (
      <div>
        <Card style={{ margin: '1rem' }}>
          <CardContent>
            <Typography gutterBottom variant="h5" component="h2">
              COVID-19 Vaccine Notification System
            </Typography>
            {/* Form Inputs */}
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="searchBy-label">Search by</InputLabel>
              <Select
                labelId="searchBy-label"
                id="searchBy-input"
                value={selectedSearchBy}
                onChange={this.selectSearchBy}
                label="Search by"
                autoFocus
                >
                {searchOptions.map((searchOption) => (
                  <MenuItem key={searchOption.id} value={searchOption.value}>
                    {searchOption.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            {
              (selectedSearchBy === 'pincode') && (
                <FormControl required variant="outlined" className={classes.formControl} error={pincode && !this.pincodeEntered()}>
                  <TextField
                    required
                    id="outlined-pincode"
                    label="Enter pincode"
                    variant="outlined"
                    value={pincode}
                    type="number"
                    onChange={this.setPincode}
                    error={hasError && !this.pincodeEntered()}
                    helperText={
                      hasError && !this.pincodeEntered() &&
                      (
                        "Please enter pincode"
                      )
                    }
                  />
                </FormControl>
              )
            }
            {
              (selectedSearchBy === 'district') && (
                <span>
                  <FormControl required variant="outlined" className={classes.formControl} error={hasError && !this.stateSelected()}>
                  <InputLabel id="state-label">Select state</InputLabel>
                  <Select
                    labelId="state-label"
                    id="state-input"
                    value={selectedState}
                    onChange={this.selectState}
                    label="Select state"
                    error={hasError && !this.stateSelected()}
                  >
                    {states.map((state) => (
                      <MenuItem key={state.state_id} value={state.state_id}>
                        {state.state_name}
                      </MenuItem>
                    ))}
                  </Select>
                  {
                    hasError && !this.stateSelected() &&
                    (
                      <FormHelperText>Please select a state</FormHelperText>
                    )
                  }
                </FormControl>
                  <FormControl required variant="outlined" className={classes.formControl} error={hasError && !this.districtSelected()}>
                    <InputLabel id="district-label">Select district</InputLabel>
                    <Select
                      labelId="district-label"
                      id="district-input"
                      value={selectedDistrict}
                      onChange={this.selectDistrict}
                      label="Select district"
                      error={hasError && !this.districtSelected()}
                    >
                      {districts.map((district) => (
                        <MenuItem
                          key={district.district_id}
                          value={district.district_id}
                        >
                          {district.district_name}
                        </MenuItem>
                      ))}
                    </Select>
                    {
                      hasError && !this.districtSelected() &&
                      (
                        <FormHelperText>Please select a district</FormHelperText>
                      )
                    }
                  </FormControl>
                </span>
              )
            }
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="vaccine-label">Select vaccine</InputLabel>
              <Select
                labelId="vaccine-label"
                id="vaccine-input"
                value={selectedVaccine}
                onChange={this.selectVaccine}
                label="Select vaccine"
              >
                {vaccines.map((vaccine) => (
                  <MenuItem key={vaccine.id} value={vaccine.value}>
                    {vaccine.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="price-label">Select price</InputLabel>
              <Select
                labelId="price-label"
                id="price-input"
                value={selectedVaccinePrice}
                onChange={this.selectVaccinePrice}
                label="Select price"
              >
                {prices.map((price) => (
                  <MenuItem key={price.id} value={price.value}>
                    {price.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <InputLabel id="age-label">Minimum age</InputLabel>
              <Select
                labelId="age-label"
                id="age-input"
                value={selectedAge}
                onChange={this.selectAge}
                label="Minimum age"
              >
                {ages.map((age) => (
                  <MenuItem key={age.id} value={age.value}>
                    {age.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <TextField
                id="outlined-min-vaccine-dose-1"
                label="Quantity required - 1st dose"
                variant="outlined"
                value={minDose1}
                type="number"
                onChange={this.setMinimumDose1}
                onFocus={this.focusMinimumDose1}
              />
            </FormControl>
            <FormControl variant="outlined" className={classes.formControl}>
              <TextField
                id="outlined-min-vaccine-dose-2"
                label="Quantity required - 2nd dose"
                variant="outlined"
                value={minDose2}
                type="number"
                onChange={this.setMinimumDose2}
                onFocus={this.focusMinimumDose2}
              />
            </FormControl>
            <br />
            <FormControl className={classes.formControl}>
              <Button
                variant="contained"
                color="primary"
                onClick={this.fetchVaccineCentres.bind(this)}
                startIcon={<Search />}
              >
                Search Vaccination Centres
              </Button>
            </FormControl>
            {showHiddenVaccineCentersButton}
            {notifyButton}
            {clearNotifyButton}
            <FormControl className={classes.formControl}>
              <Button
                variant="contained"
                color="primary"
                onClick={this.displayBookVaccineModal.bind(this)}
                endIcon={<ArrowForward />}
              >
                Book Vaccination Slot
              </Button>
              <ConfirmModal open={showBookVaccineConfirmationModal} onConfirm={this.bookVaccineSlot.bind(this)} onReject={this.closeBookVaccineModal.bind(this)} onClose={this.closeBookVaccineModal.bind(this)} heading="Book Vaccination Slot?" description="Please make sure that you take a note of the center details before proceeding" confirmButtonText="Yes" rejectButtonText="No" />
            </FormControl>
          </CardContent>
        </Card>
        {/* Data Table */}
        <div style={{ maxWidth: "100%", margin: '1rem' }}>
          <MaterialTable
            icons={tableIcons}
            columns={[
              { title: "Date", field: "date" },
              { title: "Center Name", field: "name" },
              { title: "Center Address", field: "address" },
              { title: "Vaccine Name", field: "vaccineName" },
              { title: "Minimum Age Required", field: "minAge" },
              { title: "Price", field: "price" },
              { title: "1st Dose Availability", field: "dose1Availability", type: "numeric" },
              { title: "2nd Dose Availability", field: "dose2Availability", type: "numeric" }
            ]}
            data={vaccinesData}
            title="Vaccination Centres"
            options={{ selection: true }}
            actions={[
              {
                tooltip: "Remove centres from search results",
                icon: () => {
                  return <VisibilityOff />;
                },
                onClick: (event, centres) => {
                  // * Removing selected centres from search results
                  let currentCentreIdsToSkip = [...centreIdsToSkip];
                  centres.forEach((centre) =>
                    currentCentreIdsToSkip.push(centre.center_id)
                  );
                  // * Setting up unique centre ids to skip
                  this.setState({
                    centreIdsToSkip: currentCentreIdsToSkip.filter(this.getUnique),
                  });
                  // * Removing centres from search results
                  this.setState({
                    vaccinesData: vaccinesData.filter((vaccine) => !currentCentreIdsToSkip.includes(vaccine.center_id))
                  });
                },
              },
            ]}
          />
        </div>
        {/* Hit Counter */}
        <br />
        <center><b>Total Views Worldwide</b></center>
        <br />
        <center>
          <a href="https://www.hitwebcounter.com" target="_blank" rel="noreferrer">
            <img src="https://hitwebcounter.com/counter/counter.php?page=7816923&style=0005&nbdigits=9&type=page&initCount=0" title="Free Counter" Alt="web counter" border="0" />
        </a>
        </center>
        <br />
    </div>
  );
}
Example #10
Source File: ChangePassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ChangePassword = props => {
  const classes = useStyles();
  const [open, setOpen] = React.useState(true);
  const changePasswordClasses = ChangePasswordStyles();
  const { setLoaderStatus } = useContext(LoaderContext);
  const { setIndex } = useContext(SetIndexContext);
  setIndex(null);
  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    showNewPassword: false,
    showOldPassword: false,
    isSuccessChangingPassword: false,
    isErrorChangingPassword: false
  });

  const handleChange = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]: e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  const handleClickShowOldPassword = () => {
    setFormState({
      ...formState,
      showOldPassword: !formState.showOldPassword
    });
  };

  const handleClickShowNewPassword = () => {
    setFormState({
      ...formState,
      showNewPassword: !formState.showNewPassword
    });
  };
  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  const setLoader = () => {
    setLoaderStatus(true);
  };

  const handleSubmit = event => {
    event.preventDefault();
    setOpen(true);
    setLoader();
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      ChangePasswordSchema
    );
    if (checkAllFieldsValid) {
      formState.errors = formUtilities.setErrors(
        formState.values,
        ChangePasswordSchema
      );
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        ChangePasswordSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        ChangePasswordSchema
      );
    }
    if (isValid) {
      postStateData();
      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true,
        isErrorChangingPassword: false,
        isSuccessChangingPassword: false
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false,
        isErrorChangingPassword: false,
        isSuccessChangingPassword: false
      }));
      setLoaderStatus(false);
    }
  };
  const postStateData = () => {
    let postData = {
      username: auth.getUserInfo().username,
      oldPassword: formState.values[OLDPASSWORD],
      password: formState.values[NEWPASSWORD],
      passwordConfirmation: formState.values[NEWPASSWORD]
    };
    let headers = {
      "content-type": "application/json"
    };
    serviceProviders
      .serviceProviderForPostRequest(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_CHANGE_PASSWORD,
        postData,
        headers
      )
      .then(res => {
        setLoaderStatus(false);
        setFormState(formState => ({
          ...formState,
          isSuccessChangingPassword: true,
          isErrorChangingPassword: false,
          values: {}
        }));
      })
      .catch(error => {
        setLoaderStatus(false);
        setFormState(formState => ({
          ...formState,
          isSuccessChangingPassword: false,
          isErrorChangingPassword: true,
          values: {}
        }));
      });
    /** Set state to reload form */
    setFormState(formState => ({
      ...formState,
      isValid: true
    }));
  };

  const hasError = field => (formState.errors[field] ? true : false);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {genericConstants.CHANGE_PASSWORD}
        </Typography>
      </Grid>

      <Grid item xs={12} className={classes.formgrid}>
        {/** Error/Success messages to be shown for edit */}
        {formState.isSuccessChangingPassword &&
        !formState.isErrorChangingPassword ? (
          <Collapse in={open}>
            <Alert
              severity="success"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              Password Changed Successfully.
            </Alert>
          </Collapse>
        ) : null}
        {formState.isErrorChangingPassword &&
        !formState.isSuccessChangingPassword ? (
          <Collapse in={open}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              Error Changing Password.
            </Alert>
          </Collapse>
        ) : null}
      </Grid>

      <Grid item xs={12} className={classes.formgrid}>
        <Card className={classes.root} variant="outlined">
          <form autoComplete="off" noValidate onSubmit={handleSubmit}>
            <CardContent>
              <Grid container spacing={2}>
                <Grid item md={12} xs={12}>
                  <FormControl
                    fullWidth
                    className={clsx(
                      changePasswordClasses.margin,
                      classes.elementroot
                    )}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(OLDPASSWORD)}
                    >
                      Old Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(ChangePasswordSchema[OLDPASSWORD], "id")}
                      name={OLDPASSWORD}
                      type={formState.showOldPassword ? "text" : "password"}
                      value={formState.values[OLDPASSWORD] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(OLDPASSWORD)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(OLDPASSWORD)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowOldPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showOldPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={90}
                      InputLabelProps={{
                        classes: {
                          root: changePasswordClasses.cssLabel,
                          focused: changePasswordClasses.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: changePasswordClasses.cssOutlinedInput,
                          focused: changePasswordClasses.cssFocused,
                          notchedOutline: changePasswordClasses.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(OLDPASSWORD)}>
                      {hasError(OLDPASSWORD)
                        ? formState.errors[OLDPASSWORD].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                  </FormControl>
                </Grid>
                <Grid item md={12} xs={12}>
                  <FormControl
                    fullWidth
                    className={clsx(
                      changePasswordClasses.margin,
                      classes.elementroot
                    )}
                    variant="outlined"
                  >
                    <InputLabel
                      htmlFor="outlined-adornment-password"
                      fullWidth
                      error={hasError(NEWPASSWORD)}
                    >
                      New Password
                    </InputLabel>
                    <OutlinedInput
                      id={get(ChangePasswordSchema[NEWPASSWORD], "id")}
                      name={NEWPASSWORD}
                      type={formState.showNewPassword ? "text" : "password"}
                      value={formState.values[NEWPASSWORD] || ""}
                      onChange={handleChange}
                      fullWidth
                      error={hasError(NEWPASSWORD)}
                      endAdornment={
                        <InputAdornment
                          position="end"
                          error={hasError(NEWPASSWORD)}
                        >
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowNewPassword}
                            onMouseDown={handleMouseDownPassword}
                            edge="end"
                          >
                            {formState.showNewPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      }
                      labelWidth={90}
                      InputLabelProps={{
                        classes: {
                          root: changePasswordClasses.cssLabel,
                          focused: changePasswordClasses.cssFocused
                        }
                      }}
                      InputProps={{
                        classes: {
                          root: changePasswordClasses.cssOutlinedInput,
                          focused: changePasswordClasses.cssFocused,
                          notchedOutline: changePasswordClasses.notchedOutline
                        }
                      }}
                    ></OutlinedInput>
                    <FormHelperText error={hasError(NEWPASSWORD)}>
                      {hasError(NEWPASSWORD)
                        ? formState.errors[NEWPASSWORD].map(error => {
                            return error + " ";
                          })
                        : null}
                    </FormHelperText>
                  </FormControl>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    <Grid container spacing={3}>
                      <Grid item md={2} xs={12}>
                        <YellowButton
                          type="submit"
                          color="primary"
                          variant="contained"
                        >
                          {genericConstants.SAVE_BUTTON_TEXT}
                        </YellowButton>
                      </Grid>

                      <Grid item md={2} xs={12}>
                        <GrayButton
                          type="submit"
                          color="primary"
                          variant="contained"
                          to={
                            auth.getUserInfo().role.name ===
                            roleConstants.STUDENT
                              ? routeConstants.VIEW_PROFILE
                              : routeConstants.DASHBOARD_URL
                          }
                        >
                          {genericConstants.CANCEL_BUTTON_TEXT}
                        </GrayButton>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
    </Grid>
  );
}
Example #11
Source File: ForgotPassword.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
ForgotPassword = props => {
  const [openBackdrop, setOpenBackdrop] = React.useState(false);
  const [open, setOpen] = React.useState(true);
  const theme = useTheme();
  const history = useHistory();
  const classes = useStyles();
  const [isOtpVerificationFailed, setIsOtpVerificationFailed] = React.useState(
    false
  );

  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    otpResent: false,
    otpSent: false,
    otpVerify: false,
    passChangeSuccess: false,
    passChangeFailure: false,
    resetPasswordToken: "",
    errorsToShow: "",
    isChangePassFailed: false,
    showPassword: false,
    otpSendingFailed: false,
    formType: authPageConstants.FORM_TYPE_ENTER_MOBILE
  });

  const handleClickShowPassword = () => {
    setFormState({
      ...formState,
      showPassword: !formState.showPassword
    });
  };

  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  const handleSubmit = async evt => {
    evt.preventDefault();
    evt.persist();
    if (formState.otpSent === false) {
      sendOtp();
    } else if (
      (formState.otpSent === true || formState.otpResent === true) &&
      formState.otpVerify === false
    ) {
      await verifyOtp();
    } else if (formState.otpVerify === true) {
      await changePassword();
    }
  };

  const changePassword = async () => {
    setOpenBackdrop(true);
    setFormState(formState => ({
      ...formState,
      isChangePassFailed: false
    }));
    let postData = {
      code: formState.resetPasswordToken,
      password: formState.values[newPassword],
      passwordConfirmation: formState.values[newPassword]
    };
    let headers = {
      "Content-Type": "application/json"
    };
    await serviceProvider
      .serviceProviderForPostRequest(CHANGE_PASSWORD_URL, postData, headers)
      .then(res => {
        setOpenBackdrop(false);
        history.push({
          pathname: routeConstants.SIGN_IN_URL,
          fromPasswordChangedPage: true,
          dataToShow: "Password Changed Successfully"
        });
      })
      .catch(error => {
        setOpen(true);
        setFormState(formState => ({
          ...formState,
          isChangePassFailed: true,
          errorsToShow: "Error Changing Password"
        }));
        setOpenBackdrop(false);
      });
  };

  function checkAllKeysPresent(obj) {
    let areFieldsValid = false;

    Object.keys(form).map(field => {
      if (field === newPassword) {
        if (form[field]["required"] === true && obj.hasOwnProperty(field)) {
          areFieldsValid = true;
        } else {
          areFieldsValid = false;
        }
      }
    });
    return areFieldsValid;
  }

  function count(obj) {
    return !Object.keys(obj).length ? true : false;
  }

  useEffect(() => {
    Object.keys(formState.values).map(field => {
      const errors = validateInput(
        formState.values[field],
        form[field]["validations"]
      );
      formState.formType === authPageConstants.FORM_TYPE_CHANGE_PASS
        ? setFormState(formState => ({
            ...formState,
            isValid:
              !errors.length &&
              count(formState.errors) &&
              checkAllKeysPresent(formState.values)
                ? true
                : false,
            errors:
              errors.length && form
                ? {
                    ...formState.errors,
                    [field]: errors
                  }
                : formState.errors
          }))
        : setFormState(formState => ({
            ...formState,
            isValid: errors.length ? false : true,
            errors:
              errors.length && form
                ? {
                    ...formState.errors,
                    [field]: errors
                  }
                : formState.errors
          }));
      if (!errors.length && formState.errors.hasOwnProperty(field)) {
        delete formState.errors[field];
      }
    });
  }, [formState.values]);

  const handleChange = e => {
    e.persist();
    setIsOtpVerificationFailed(false);
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [e.target.name]: e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      isChangePassFailed: false
    }));
  };

  const sendOtp = async () => {
    await generateOtp(true, false);
  };

  const resendOtp = async () => {
    await generateOtp(false, true);
    return false;
  };

  /** Function used to generate otp */
  const generateOtp = async (sendOtp, resendOtp) => {
    /** Reset error message */
    setOpenBackdrop(true);
    setIsOtpVerificationFailed(false);
    setFormState(formState => ({
      ...formState,
      otpSendingFailed: false
    }));
    let postData = { contact_number: formState.values[mobileNumber] };
    let headers = {
      "Content-Type": "application/json"
    };
    await serviceProvider
      .serviceProviderForPostRequest(REQUEST_OTP_URL, postData, headers)
      .then(res => {
        if (res.data.result.status === "Ok") {
          if (sendOtp) {
            setFormState(formState => ({
              ...formState,
              otpSent: true,
              isValid: false,
              otpSendingFailed: false,
              errorsToShow: "",
              formType: authPageConstants.FORM_TYPE_VERIFY_OTP
            }));
          } else if (resendOtp) {
            setOpen(true);
            setFormState(formState => ({
              ...formState,
              otpSendingFailed: false,
              otpResent: true,
              isValid: false,
              errorsToShow: "OTP sent successfully"
            }));
          }
        }
        setOpenBackdrop(false);
      })
      .catch(error => {
        setOpen(true);
        setFormState(formState => ({
          ...formState,
          otpSendingFailed: true,
          errorsToShow: "Error Generating OTP"
        }));
        setOpenBackdrop(false);
      });
  };

  const verifyOtp = async () => {
    setOpenBackdrop(true);
    setIsOtpVerificationFailed(false);
    let postData = {
      contact_number: formState.values[mobileNumber],
      otp: formState.values[otp]
    };
    let headers = {
      "Content-Type": "application/json"
    };
    await serviceProvider
      .serviceProviderForPostRequest(CHECK_USER, postData, headers)
      .then(res => {
        setIsOtpVerificationFailed(true);
        setOpen(true);
        setFormState(formState => ({
          ...formState,
          errorsToShow: "User not registered"
        }));
        setOpenBackdrop(false);
      })
      .catch(async function (error) {
        let verificationError = false;
        let invalidOtp = false;
        if (error.response) {
          if (error.response.data.message === "User already registered") {
            await serviceProvider
              .serviceProviderForPostRequest(
                VALIDATE_OTP_URL,
                postData,
                headers
              )
              .then(res => {
                if (
                  res.data.statusCode === 400 &&
                  res.data.message === "OTP has expired"
                ) {
                  setOpen(true);
                  setIsOtpVerificationFailed(true);
                  setFormState(formState => ({
                    ...formState,
                    errorsToShow: "OTP has expired"
                  }));
                } else if (res.data.message === "EmptyResponse") {
                  invalidOtp = true;
                } else if (formUtilities.checkEmpty(res.data)) {
                  invalidOtp = true;
                } else if (res.data.result) {
                  /** Otp verified and reset password token genarated */
                  formState.resetPasswordToken = res.data.result;
                  setFormState(formState => ({
                    ...formState,
                    otpVerify: true,
                    isValid: false,
                    resetPasswordToken: res.data.result,
                    errorsToShow: "",
                    formType: authPageConstants.FORM_TYPE_CHANGE_PASS
                  }));
                }
                setOpenBackdrop(false);
              })
              .catch(error => {
                verificationError = true;
              });
          } else if (error.response.data.message === "Invalid OTP") {
            invalidOtp = true;
          } else {
            verificationError = true;
          }
        } else {
          verificationError = true;
        }

        if (verificationError) {
          /** Error verifying otp */
          setOpen(true);
          setIsOtpVerificationFailed(true);
          setFormState(formState => ({
            ...formState,
            errorsToShow: "Error verifying OTP"
          }));
          setOpenBackdrop(false);
        } else if (invalidOtp) {
          /** Invalid Otp message */
          setOpen(true);
          setIsOtpVerificationFailed(true);
          setFormState(formState => ({
            ...formState,
            errorsToShow: "Invalid OTP"
          }));
          setOpenBackdrop(false);
        }
        setOpenBackdrop(false);
      });
  };

  const hasError = field =>
    formState.touched[field] && formState.errors[field] ? true : false;

  const isDesktop = useMediaQuery(theme.breakpoints.up("lg"), {
    defaultMatches: true
  });

  return (
    <div className={classes.masterlogin2}>
      <div className={classes.masterlogin1}>
        <div className={classes.masterlogin}>
          <Paper className={isDesktop ? classes.rootDesktop : classes.root}>
            <CardContent>
              <CssBaseline />
              <div className={classes.paper}>
                <div className={classes.signin_header}>
                  <div className={classes.loginlock}>
                    <CardIcon>
                      <Icon>lock</Icon>
                    </CardIcon>
                  </div>
                  <Typography
                    className={classes.signin}
                    component="h1"
                    variant="h5"
                    style={{ fontWeight: "700" }}
                  >
                    {authPageConstants.FORGOT_PASSWORD_HEADER}
                  </Typography>
                </div>
                {isOtpVerificationFailed ||
                formState.isChangePassFailed ||
                formState.otpSendingFailed ? (
                  <Collapse in={open}>
                    <Alert
                      severity="error"
                      action={
                        <IconButton
                          aria-label="close"
                          color="inherit"
                          size="small"
                          onClick={() => {
                            setOpen(false);
                          }}
                        >
                          <CloseIcon fontSize="inherit" />
                        </IconButton>
                      }
                    >
                      {formState.errorsToShow}
                    </Alert>
                  </Collapse>
                ) : formState.otpResent &&
                  formState.errorsToShow === "OTP sent successfully" ? (
                  <Collapse in={open}>
                    <Alert
                      severity="success"
                      action={
                        <IconButton
                          aria-label="close"
                          color="inherit"
                          size="small"
                          onClick={() => {
                            setOpen(false);
                          }}
                        >
                          <CloseIcon fontSize="inherit" />
                        </IconButton>
                      }
                    >
                      {formState.errorsToShow}
                    </Alert>
                  </Collapse>
                ) : null}
                <form
                  className={classes.form}
                  noValidate
                  onSubmit={handleSubmit}
                >
                  {formState.otpVerify === true ? (
                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.CONFIRM_NEW_PASS_ALERT}
                      </Typography>
                      <FormControl
                        fullWidth
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                      >
                        <InputLabel
                          htmlFor="outlined-adornment-password"
                          fullWidth
                          error={hasError(newPassword)}
                        >
                          New Password
                        </InputLabel>
                        <OutlinedInput
                          id={get(form[newPassword], "id")}
                          name={newPassword}
                          type={formState.showPassword ? "text" : "password"}
                          value={formState.values[newPassword] || ""}
                          onChange={handleChange}
                          fullWidth
                          error={hasError(newPassword)}
                          endAdornment={
                            <InputAdornment
                              position="end"
                              error={hasError(newPassword)}
                            >
                              <IconButton
                                aria-label="toggle password visibility"
                                onClick={handleClickShowPassword}
                                onMouseDown={handleMouseDownPassword}
                                edge="end"
                              >
                                {formState.showPassword ? (
                                  <Visibility />
                                ) : (
                                  <VisibilityOff />
                                )}
                              </IconButton>
                            </InputAdornment>
                          }
                          labelWidth={70}
                          InputLabelProps={{
                            classes: {
                              root: classes.cssLabel,
                              focused: classes.cssFocused
                            }
                          }}
                          InputProps={{
                            classes: {
                              root: classes.cssOutlinedInput,
                              focused: classes.cssFocused,
                              notchedOutline: classes.notchedOutline
                            }
                          }}
                        ></OutlinedInput>
                        <FormHelperText error={hasError(newPassword)}>
                          {hasError(newPassword)
                            ? formState.errors[newPassword].map(error => {
                                return "\n" + error;
                              })
                            : null}
                        </FormHelperText>
                      </FormControl>
                      <Button
                        color="primary"
                        disabled={!formState.isValid}
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                      >
                        {authPageConstants.RESET_PASS_BUTTON}
                      </Button>
                      <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop>
                    </React.Fragment>
                  ) : formState.otpSent === true ? (
                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.OTP_ALERT}{" "}
                        {formState.values.mobileNumber}
                      </Typography>
                      <FormControl
                        fullWidth
                        className={clsx(classes.margin, classes.textField)}
                        variant="outlined"
                      >
                        <InputLabel
                          htmlFor="outlined-adornment-password"
                          fullWidth
                          error={hasError(otp)}
                        >
                          OTP
                        </InputLabel>
                        <OutlinedInput
                          id={get(form[otp], "id")}
                          name={otp}
                          type={formState.showPassword ? "text" : "password"}
                          value={formState.values[otp] || ""}
                          onChange={handleChange}
                          fullWidth
                          error={hasError(otp)}
                          endAdornment={
                            <InputAdornment
                              position="end"
                              error={hasError(otp)}
                            >
                              <IconButton
                                aria-label="toggle password visibility"
                                onClick={handleClickShowPassword}
                                onMouseDown={handleMouseDownPassword}
                                edge="end"
                              >
                                {formState.showPassword ? (
                                  <Visibility />
                                ) : (
                                  <VisibilityOff />
                                )}
                              </IconButton>
                            </InputAdornment>
                          }
                          labelWidth={70}
                          InputLabelProps={{
                            classes: {
                              root: classes.cssLabel,
                              focused: classes.cssFocused
                            }
                          }}
                          InputProps={{
                            classes: {
                              root: classes.cssOutlinedInput,
                              focused: classes.cssFocused,
                              notchedOutline: classes.notchedOutline
                            }
                          }}
                        ></OutlinedInput>
                        <FormHelperText error={hasError(otp)}>
                          {hasError(otp)
                            ? formState.errors[otp].map(error => {
                                return "\n" + error;
                              })
                            : null}
                        </FormHelperText>
                        <Link
                          href="javascript:void(0);"
                          variant="body2"
                          className={classes.linkColor}
                          onClick={resendOtp}
                        >
                          {authPageConstants.RESEND_OTP_BUTTON}
                        </Link>
                      </FormControl>
                      <Button
                        color="primary"
                        disabled={!formState.isValid}
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                      >
                        {authPageConstants.VERIFY_OTP_BUTTON}
                      </Button>
                      <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop>
                    </React.Fragment>
                  ) : (
                    <React.Fragment>
                      <Typography
                        component="h5"
                        variant="subtitle2"
                        style={{ marginTop: ".9rem", marginBottom: ".9rem" }}
                      >
                        {authPageConstants.MOBILE_NUMBER_ALERT}
                      </Typography>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        type={get(form[mobileNumber], "type")}
                        id={get(form[mobileNumber], "id")}
                        label={get(form[mobileNumber], "label")}
                        name={mobileNumber}
                        error={hasError(mobileNumber)}
                        helperText={
                          hasError(mobileNumber)
                            ? formState.errors[mobileNumber].map(error => {
                                return "\n" + error;
                              })
                            : null
                        }
                        autoFocus
                        value={formState.values[mobileNumber] || ""}
                        onChange={handleChange}
                      />
                      <Button
                        color="primary"
                        disabled={!formState.isValid}
                        type="submit"
                        fullWidth
                        variant="contained"
                        className={classes.submit}
                      >
                        {authPageConstants.SEND_OTP_BUTTON}
                      </Button>
                      <Backdrop
                        className={classes.backdrop}
                        open={openBackdrop}
                      >
                        <CircularProgress color="inherit" />
                      </Backdrop>
                    </React.Fragment>
                  )}
                  <Grid container>
                    <Grid item xs={12} style={{ textAlign: "center" }}>
                      <Link
                        href={routeConstants.SIGN_IN_URL}
                        variant="body2"
                        className={classes.linkColor}
                      >
                        {authPageConstants.BACK_TO_LOGIN_TEXT}
                      </Link>
                    </Grid>
                  </Grid>
                </form>
              </div>
            </CardContent>

            <Hidden mdDown>
              <CardMedia
                className={classes.cover}
                image={image}
                title="Live from space album cover"
              />
            </Hidden>
          </Paper>
        </div>
      </div>
    </div>
  );
}