1. 程式人生 > >前端記住密碼功能

前端記住密碼功能

功能需求:登入時增加記住密碼功能,如果勾選了記住密碼選項,在登出登入後再次登入時賬號密碼直接填入登陸框。

基本思路:

  • 頁面渲染之前,判斷cookie中是否有使用者賬號密碼資訊,如果有,則設定賬號密碼為cookie中的賬號密碼,預先填寫登入框中的賬號密碼
  • 勾選和取消勾選記住密碼選項時,設定記住密碼狀態
  • 按下登入按鈕時,根據記住密碼狀態,如果狀態為true,則儲存使用者賬號資訊cookie,如果為false,則刪除cookie中的賬號密碼資訊

登入框 取消記住密碼

React+material-ui 寫出的登入頁面和邏輯如下

Applogin.js

/**
 * Created by
lenovo on 2017/7/31. */ import React, {Component} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {browserHistory} from 'react-router'; import compose from 'recompose/compose'; import {withStyles} from 'material-ui/styles'; import { FormGroup, FormControlLabel } from 'material-ui/Form'
; import Dialog, { DialogActions, DialogContent, DialogContentText, DialogTitle, } from 'material-ui/Dialog'; import TextField from 'material-ui/TextField'; import Button from 'material-ui/Button'; import Input, {InputLabel} from 'material-ui/Input'; import {FormControl, FormHelperText} from 'material-ui/Form'
; import user from '../engine/user'; import {userLogin} from '../redux/actions/user' import {setCookie,getCookie,delCookie} from '../utils/cookie' import Checkbox from 'material-ui/Checkbox'; const styleSheet = theme => ({ textField: { margin: theme.spacing.unit, display: "block", width: 200, }, }); class AppLogin extends Component { constructor() { super(); this.state = { //先宣告變數並初始化 name: '', password: '', error: null, rememberPassword: false } } //根據rememberPassword狀態,如果為true,證明使用者勾選了記住密碼,則登入時將使用者登入資訊設為cookie,如果為false,則刪除使用者登入資訊cookie login = () => { const {onRequestClose} = this.props; user.login({ username: this.state.name, password: this.state.password }, (err, data) => { if (err)return alert("login failed"); if (data.status == "success") { if(this.state.rememberPassword){ let accountInfo = this.state.name+ '&' +this.state.password; setCookie('accountInfo',accountInfo); }else { delCookie('accountInfo'); this.state.name = ''; this.state.password = ''; } this.props.actions.userLogin(data.user); onRequestClose(); browserHistory.push('/task/myNode'); this.setState({ error: null }) } else { this.setState({ error: data.msg }) } }) }; handleKeyDown = (event) => { //按下enter鍵,觸發login事件 switch (event.keyCode) { case 13: this.login(); break; } }; handleChange = name => (event) => { this.setState({[name]: event.target.value}) }; handleChecked = name => (event) => { this.setState({ [name]: event.target.checked }); }; //判斷cookie中是否有賬號資訊,有就可以進行預填寫,沒有則直接返回 loadAccountInfo = () => { let accountInfo = getCookie('accountInfo'); if(Boolean(accountInfo) == false){ return false; }else{ let userName = ""; let passWord = ""; let index = accountInfo.indexOf("&"); userName = accountInfo.substring(0,index); passWord = accountInfo.substring(index+1); this.state.name = userName; this.state.password = passWord; this.state.rememberPassword = true; } }; componentDidMount() {//元件渲染完成之後觸發此函式 this.loadAccountInfo(); window.addEventListener('keydown', this.handleKeyDown) } render() { const {classes, open, onRequestClose} = this.props; return ( <Dialog open={open} onRequestClose={onRequestClose}> <DialogTitle> {"Login"} </DialogTitle> <DialogContent> <TextField id="name" label="Name" className={classes.textField} value={this.state.name} onChange={this.handleChange("name")} /> <FormControl className={classes.textField}> <InputLabel htmlFor="Password">Password</InputLabel> <Input id="password" type="password" value={this.state.password} onChange={this.handleChange("password")}/> { this.state.error ? <FormHelperText error>{this.state.error}</FormHelperText> : null } </FormControl> <FormControlLabel control={ <Checkbox checked={this.state.rememberPassword} onChange={this.handleChecked('rememberPassword')} value="this.state.rememberPassword" /> } label="Remember Password" /> </DialogContent> <DialogActions> <Button onClick={this.login} color="primary"> OK </Button> <Button onClick={onRequestClose} color="default"> CANCEL </Button> </DialogActions> </Dialog> ); } } const mapStateToProps = (state) => { return state; }; const mapDispatchToProps = (dispatch) => { return {actions: bindActionCreators({userLogin}, dispatch)}; }; export default compose(withStyles(styleSheet), connect(mapStateToProps, mapDispatchToProps))(AppLogin);

cookie增刪存邏輯:
cookie的expire/Max-Age是cookie的過期時間

cookie.js

/**
 * Created by lenovo on 2017/7/31.
 */

export function setCookie(name,value)
{
    let Days = 10;
    let exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

export function getCookie(name)
{
    let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

export function delCookie(name)
{
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}