{"size": 6271, "ext": "js", "max_stars_repo_path": "fe/src/views/Login.js", "max_stars_repo_name": "rakenduste-programmeerimine-2021/prediction-hero", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fe/src/views/Login.js", "max_issues_repo_name": "rakenduste-programmeerimine-2021/prediction-hero", "max_issues_repo_issues_event_min_datetime": "2021-11-12T17:18:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T19:31:05.000Z", "max_forks_repo_path": "fe/src/views/Login.js", "max_forks_repo_name": "rakenduste-programmeerimine-2021/prediction-hero", "max_forks_repo_forks_event_min_datetime": "2021-11-14T07:40:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-14T07:40:44.000Z"}
{"max_stars_count": null, "max_issues_count": 65, "max_forks_count": 1, "avg_line_length": 34.6464088398, "max_line_length": 170, "alphanum_fraction": 0.5491947058}
import React, { useState, useContext, useEffect } from 'react';
import { Context } from "../store";
import FacebookLogin from 'react-facebook-login';
import { useNavigate } from "react-router-dom";
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { loginUser } from "../store/actions";
import { Snackbar, Alert, Typography } from '@mui/material';
import FBLoginButton from '../components/loginBtn'


export const fbLoginFail = () => {
    console.log("FB login failed");
}

export default function Login() {
    const [loggedIn, setLoggedIn] = useState(false)
    const [logInData, setLogInData] = useState({message:""})
    const [loading, setLoading] = useState(false)
    const [username, setUsername] = useState('admin')
    const [password, setPassword] = useState('admin')
    const [state, dispatch] = useContext(Context)

    const navigate = useNavigate();
    const [open, setOpen] = useState(false);

    useEffect(()=>{
        if(state?.auth.username) navigate('/settings', {state: state.auth})
        console.log(state?.auth)
    },[])

    const openSnacbar = () => {
        setOpen(true);
    };

    const closeSnacbar = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }

        setOpen(false);
    };

    const submit = () => {  
        closeSnacbar()
        setLoading(true)
        const data = JSON.stringify({ 
            "username": username,
            "pwhash": password 
        })
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: data
        };
        fetch('http://localhost:3001/login', requestOptions)
        .then(response => response.json())
        .then(data => {
            console.log(JSON.stringify(data))
            setLogInData(data)
            setLoading(false)

            if(data.status == "NOK"){
                openSnacbar()
            }else{
                console.log("LOGGING IN.... data:")
                console.log(data)
                finishLogin(data)
            }
        })
    }

    const responseFacebook = (response) => {
        console.log(response);
        setLogInData(response);

        closeSnacbar()
        setLoading(true)
        const data = JSON.stringify({ 
            "username": response.first_name+"_"+response.last_name,
            "pwhash": response.userID,
            "email": response.email,
            "firstname": response.first_name,
            "lastname": response.last_name,
            "social_id": response.userID,
            "social_platform": "FB",
            "profile_pic": response.picture.data.url
        })
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: data
        };
        fetch('http://localhost:3001/loginFB', requestOptions)
        .then(response => response.json())
        .then(data => {
            console.log(data)
            setLogInData(data)
            setLoading(false)
            console.log("Now dispatching user")

            finishLogin(data)
        })
        
    }
    const finishLogin = (data) => {
        window.localStorage.setItem("PHsess",JSON.stringify({"chk":(new Date()).getTime(),"data": state.auth}))
        let user = {
            token: data, 
            user: data.data.rows[0].username,
            firstname: data.data.rows[0].firstname, 
            lastname: data.data.rows[0].lastname,
            email: data.data.rows[0].email,
            profilePic: data.data.rows[0].profile_pic,
            id: data.data.rows[0].id,
            user_points: data.data.rows[0].user_points,
            is_admin: data?.data.rows[0].is_admin,
            blocked: data?.data.rows[0].blocked
        }
        dispatch(loginUser(user));
        window.localStorage.setItem("PHsess",JSON.stringify({"chk":(new Date()).getTime(),"data": user}))
        let navigateTo = (window.localStorage.getItem("PHlwp") !== '/blocked' && window.localStorage.getItem("PHlwp")) || '/settings'

        user.blocked && (navigateTo = '/blocked')
        navigate(navigateTo, {state: data}) 
    }

    const handleFormKeypress = (e) => {
        if (e.charCode == 13) {
            submit()
        }
    }

    return (
        <div style={styles.root} id="loginCont">
            <form onKeyPress={handleFormKeypress} style={{textAlign: "center"}} name="loginForm">
            <Typography variant="h2"gutterBottom={true}>Logi sisse</Typography>
                <div style={styles.row}>
                    <TextField id="outlined-basic" label="Kasutajanimi" variant="outlined" value={username} onChange={(v) => {setUsername(v.target.value)}}/>   
                </div>
                <div style={styles.row}>
                    <TextField id="outlined-basic" label="Parool" variant="outlined" type="password" value={password} onChange={(v) => {setPassword(v.target.value)}}/>   
                </div>
                <div style={styles.buttonRow}>
                    <Button onClick={()=>{navigate('/settings')}} disabled={loading ? true : false} variant="contained" color="info">Registreeru</Button>
                    <Button onClick={submit} disabled={loading ? true : false} variant="contained" color="success" id="login">Logi sisse</Button>
                </div>
                <div style={styles.row}>
                    <FBLoginButton responseFacebook={responseFacebook} fbLoginFail={fbLoginFail}/>
                </div>
            </form>
            
            <Snackbar open={open} autoHideDuration={10000} onClose={closeSnacbar} anchorOrigin={{ vertical: "top", horizontal:"center" }}>
                <Alert onClose={closeSnacbar} severity="error" sx={{ width: '100%' }}>
                    {logInData?.message}
                </Alert>
            </Snackbar>
            
        </div>
    )
}
const styles = {
    root: {
        display: "flex",
        justifyContent: "center",
        padding: 50,
        overFlow: "hidden"
    },
    row: {
        marginTop: 10
    }
    ,
    buttonRow: {
        marginTop: 30,
        marginBottom: 30,
        display: "flex",
        justifyContent: "space-between"
    }
}

