Skip to content

Commit

Permalink
Merge pull request #78 from suvarnakale/shiksha-2.0
Browse files Browse the repository at this point in the history
Issue #PS-318 feat: Login using password and username
  • Loading branch information
itsvick authored May 7, 2024
2 parents 1c032c7 + 0549e99 commit c47250f
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 54 deletions.
106 changes: 64 additions & 42 deletions src/pages/LoginPage.tsx → src/pages/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
'use client';
import React, { useEffect, useMemo } from 'react';
import {
Box,
Expand All @@ -12,19 +13,20 @@ import Image from 'next/image';
import appLogo2 from '../../public/appLogo.png';
import { Visibility, VisibilityOff } from '@mui/icons-material';
// import { useLocation } from 'react-router-dom';
import { useRouter } from 'next/router';
// import { useRouter } from 'next/router';
import CloseIcon from '@mui/icons-material/Close';
import { useState } from 'react';
// import '../App.css';
import { login } from '../services/LoginService';
import { useTranslation } from 'react-i18next';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import { useTheme } from '@mui/material/styles';
import MenuItem from '@mui/material/MenuItem';
import config from '../../config.json';
import { getUserId } from '../services/ProfileService';
// import { getUserId } from '../services/ProfileService';
import Loader from '../components/Loader';
import Snackbar, { SnackbarOrigin } from '@mui/material/Snackbar';
import Link from '@mui/material/Link';
import Checkbox from '@mui/material/Checkbox';

interface State extends SnackbarOrigin {
openModal: boolean;
Expand All @@ -35,41 +37,41 @@ const LoginPage = () => {
const [showPassword, setShowPassword] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [showToastMessage, setShowToastMessage] = useState(false);
const [usernameError, setUsernameError] = useState(false);
const [passwordError, setPasswordError] = useState(false);
const [loading, setLoading] = useState(false);

// const [selectedLanguage, setSelectedLanguage] = useState(
// localStorage.getItem('preferredLanguage') || 'en'
// );
const [selectedLanguage, setSelectedLanguage] = useState('en');
const [selectedLanguage, setSelectedLanguage] = useState(
localStorage.getItem('preferredLanguage') || 'en'
);
const [language, setLanguage] = useState(selectedLanguage);
const router = useRouter();
// const location = useLocation();
const theme = useTheme<any>();
const [state, setState] = React.useState<State>({
openModal: false,
// const router = useRouter();
// const location = useLocation();

const DEFAULT_POSITION: Pick<State, 'vertical' | 'horizontal'> = {
vertical: 'top',
horizontal: 'center',
};
const [state, setState] = React.useState<State>({
openModal: false,
...DEFAULT_POSITION,
});
const { vertical, horizontal, openModal } = state;

useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
router.push('/dashboard');
// router.push('/dashboard');
}
}, []);

const handleUsernameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
const trimmedValue = value.trim();
setUsername(trimmedValue);
if (trimmedValue.includes(' ')) {
setUsernameError(true);
} else {
setUsernameError(false);
}
const containsSpace = /\s/.test(trimmedValue);
setUsernameError(containsSpace);
};

const handlePasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
Expand All @@ -88,7 +90,6 @@ const LoginPage = () => {
const handleFormSubmit = async (event: React.FormEvent) => {
event.preventDefault();
if (!usernameError && !passwordError) {
// loginButtonClick(event);
setLoading(true);
event.preventDefault();
try {
Expand All @@ -98,20 +99,29 @@ const LoginPage = () => {
});
console.log(response);
if (response) {
setTimeout(() => {
setState({
openModal: false,
...DEFAULT_POSITION,
});
setShowToastMessage(false);
});

const token = response?.access_token;
const refreshToken = response?.refresh_token;

localStorage.setItem('token', token);
localStorage.setItem('refreshToken', refreshToken);
const userResponse = await getUserId();
localStorage.setItem('userId', userResponse?.userId);

// const userResponse = await getUserId();
// localStorage.setItem('userId', userResponse?.userId);
}
setLoading(false);
router.push('/dashboard');
// router.push('/dashboard');
} catch (error: any) {
setLoading(false);
if (error.response && error.response.status === 401) {
handleClick({ vertical: 'top', horizontal: 'center' })();
if (error.response && error.response.status === 404) {
handleClick({ ...DEFAULT_POSITION })();
setShowToastMessage(true);
} else {
console.error('Error:', error);
}
Expand All @@ -122,7 +132,6 @@ const LoginPage = () => {
const isButtonDisabled =
!username || !password || usernameError || passwordError;

// const loginButtonClick = async (event: React.FormEvent) => {};
const handleChange = (event: SelectChangeEvent) => {
setLanguage(event.target.value);
i18n.changeLanguage(event.target.value);
Expand All @@ -138,8 +147,6 @@ const LoginPage = () => {
const action = useMemo(
() => (
<React.Fragment>
{/* <Typography>{t('LOGIN_PAGE.USERNAME_PASSWORD_NOT_CORRECT')}</Typography> */}

<IconButton
size="small"
aria-label="close"
Expand Down Expand Up @@ -214,7 +221,10 @@ const LoginPage = () => {
fullWidth={true}
className="CssTextField"
>
<InputLabel htmlFor="outlined-adornment-username">
<InputLabel
htmlFor="outlined-adornment-username"
error={usernameError}
>
{t('LOGIN_PAGE.USERNAME')}
</InputLabel>
<OutlinedInput
Expand All @@ -229,7 +239,10 @@ const LoginPage = () => {
</Box>
<Box marginY={'1rem'}>
<FormControl variant="outlined" className="CssTextField">
<InputLabel htmlFor="outlined-adornment-password">
<InputLabel
htmlFor="outlined-adornment-password"
error={passwordError}
>
{t('LOGIN_PAGE.PASSWORD')}
</InputLabel>
<OutlinedInput
Expand All @@ -255,6 +268,15 @@ const LoginPage = () => {
</FormControl>
</Box>

<Box marginTop={'-1rem'} marginLeft={'0.5rem'}>
<Link sx={{ color: 'blue' }} href="#" underline="none">
{t('LOGIN_PAGE.FORGOT_PASSWORD')}
</Link>
</Box>
<Box marginTop={'1rem'} className="RememberMecheckbox">
<Checkbox defaultChecked />
{t('LOGIN_PAGE.REMEMBER_ME')}
</Box>
<Box
alignContent={'center'}
textAlign={'center'}
Expand All @@ -266,25 +288,25 @@ const LoginPage = () => {
variant="contained"
type="submit"
fullWidth={true}
// onClick={(event) => loginButtonClick(event)}
disabled={isButtonDisabled}
>
{t('LOGIN_PAGE.LOGIN')}
</Button>
</Box>
</Box>
</Box>

<Snackbar
anchorOrigin={{ vertical, horizontal }}
open={openModal}
onClose={handleClose}
className="alert"
autoHideDuration={5000}
key={vertical + horizontal}
message={t('LOGIN_PAGE.USERNAME_PASSWORD_NOT_CORRECT')}
action={action}
/>
{showToastMessage && (
<Snackbar
anchorOrigin={{ vertical, horizontal }}
open={openModal}
onClose={handleClose}
className="alert"
autoHideDuration={5000}
key={vertical + horizontal}
message={t('LOGIN_PAGE.USERNAME_PASSWORD_NOT_CORRECT')}
action={action}
/>
)}
</Box>
</form>
);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default function App({ Component, pageProps }: AppProps) {
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={mode === 'light' ? customTheme : darkTheme}>
{/* <DarkTheme /> */}
<Component {...pageProps} />;
<Component {...pageProps} />
</ThemeProvider>
</ColorModeContext.Provider>
);
Expand Down
7 changes: 4 additions & 3 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@
// import Image from 'next/image';
// import { Inter } from 'next/font/google';
// import styles from '@/styles/Home.module.css';
const LoginPage = dynamic(() => import('./LoginPage'), { ssr: false });
const Login = dynamic(() => import('./Login'), { ssr: false });
import dynamic from 'next/dynamic';
import i18n from '../i18n';
import { I18nextProvider } from 'react-i18next';
// import Login from './Login';

// const inter = Inter({ subsets: ['latin'] });

export default function Home() {

console.log('hi');
return (
<>
<I18nextProvider i18n={i18n}>
<LoginPage />
<Login />
</I18nextProvider>
</>
);
Expand Down
12 changes: 12 additions & 0 deletions src/styles/globals.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
.alert .MuiSnackbarContent-root {
background-color: #ffdad6 !important;
color: #ba1a1a;
font-size: 0.75rem;
margin-top: 35%;
}
.RememberMecheckbox span svg {
fill: black !important;
}
.RememberMecheckbox span {
padding: 6px 7px 6px 0 !important;
}
body {
margin: 0;
padding: 0;
Expand Down
14 changes: 8 additions & 6 deletions src/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,21 @@
"MARITAL_STATUS": "Marital Status",
"DROPOUT_YEAR": "Dropout Year",
"EMPLOYMENT_STATUS": "Employment Status",
"ENROLLMENT_DATE":"Enrollment Date",
"AS_OF_TODAY":"As of today",
"AS_OF_LAST_WEEK":"As of last week",
"AS_OF_LAST_SIX_MONTH":"As of last six month",
"NONE":"None"
"ENROLLMENT_DATE": "Enrollment Date",
"AS_OF_TODAY": "As of today",
"AS_OF_LAST_WEEK": "As of last week",
"AS_OF_LAST_SIX_MONTH": "As of last six month",
"NONE": "None"
},
"LOGIN_PAGE": {
"USERNAME": "Username",
"PASSWORD": "Password",
"LOGIN": "Login",
"USERNAME_PLACEHOLDER": "Enter username",
"PASSWORD_PLACEHOLDER": "Enter password",
"USERNAME_PASSWORD_NOT_CORRECT": "The username or password you entered is incorrect"
"USERNAME_PASSWORD_NOT_CORRECT": "The username or password you entered is incorrect",
"FORGOT_PASSWORD": "Forgot Password?",
"REMEMBER_ME": "Remember Me"
},
"DASHBOARD": {
"DASHBOARD": "Dashboard",
Expand Down
4 changes: 3 additions & 1 deletion src/translations/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@
"LOGIN": "लॉग इन करें",
"USERNAME_PLACEHOLDER": "उपयोगकर्ता नाम दर्ज करें",
"PASSWORD_PLACEHOLDER": "पासवर्ड दर्ज करें",
"USERNAME_PASSWORD_NOT_CORRECT": "आपका यूजरनेम या पासवर्ड गलत है"
"USERNAME_PASSWORD_NOT_CORRECT": "आपका यूजरनेम या पासवर्ड गलत है",
"FORGOT_PASSWORD": "पासवर्ड भूल गए?",
"REMEMBER_ME": "मुझे याद रखें"
},
"DASHBOARD": {
"DASHBOARD": "डैशबोर्ड",
Expand Down
4 changes: 3 additions & 1 deletion src/translations/mr.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@
"LOGIN": "लॉग इन करा",
"USERNAME_PLACEHOLDER": "वापरकर्तानाव प्रविष्ट करा",
"PASSWORD_PLACEHOLDER": "पासवर्ड टाका",
"USERNAME_PASSWORD_NOT_CORRECT": "आपलं वापरकर्तानाव किंवा संकेतशब्द चुकीचं आहे"
"USERNAME_PASSWORD_NOT_CORRECT": "आपलं वापरकर्तानाव किंवा संकेतशब्द चुकीचं आहे",
"FORGOT_PASSWORD": "पासवर्ड विसरलात?",
"REMEMBER_ME": "मला लक्षात ठेवा"
},
"DASHBOARD": {
"DASHBOARD": "डॅशबोर्ड",
Expand Down

0 comments on commit c47250f

Please sign in to comment.