Commit cbb48655 by zhanghaozhe

添加本地代理服务器cookie设置,privateRoute,登录相关redux逻辑

parent bc6030d8
import React, {Component} from 'react' import React, { Component } from 'react'
import Routes from './router' import Routes from './router'
import cookie from 'js-cookie' import cookie from 'js-cookie'
import { http, api } from '@/utils';
import { connect } from 'react-redux';
import { setCurrentUser } from '@/store/userAction';
//拦截ajax请求,返回mock数据 //拦截ajax请求,返回mock数据
/*import mock from '@/utils/mock' /*import mock from '@/utils/mock'
...@@ -13,15 +17,57 @@ import './assets/css/index.scss'; ...@@ -13,15 +17,57 @@ import './assets/css/index.scss';
// iconfont // iconfont
import './assets/font/iconfont.css'; import './assets/font/iconfont.css';
class App extends Component {
componentDidMount() {
export default class App extends Component{
componentDidMount(){
//平台信息 //平台信息
cookie.set('plat', '5') cookie.set('plat', '5')
http.get(`${api.home}/m/user_info`).then(res => {
this.props.setCurrentUser(this.storeUser(res))
})
}
storeUser = res => {
let payload
if (res.data.code === 200) {
const {
msg, data: {
avatar_file: avatar,
user_name: username,
is_vip: isVIP,
uid
}
} = res.data
payload = {
hasError: false,
msg,
data: {
username,
isVIP,
avatar,
uid
}
}
} else {
payload = {
hasError: true,
msg: res.data.msg
}
}
return payload
} }
render(){
render() {
return <Routes/> return <Routes/>
} }
} }
\ No newline at end of file
export default connect(
null,
{setCurrentUser}
)(App)
\ No newline at end of file
import React, { Component } from "react" import React, { PureComponent } from "react"
import './accountLogin.scss' import './accountLogin.scss'
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { withFormik, FastField, Form } from "formik"; import { withFormik, FastField, Form } from "formik";
import { compose } from 'redux'; import { compose } from 'redux';
import { accountLogin } from '@/store/userAction';
import { connect } from "react-redux";
import Header from "../common/Header"; import Header from "../common/Header";
...@@ -12,7 +14,8 @@ import PasswordInput from '../common/passwordInput' ...@@ -12,7 +14,8 @@ import PasswordInput from '../common/passwordInput'
// import VeriCodeButton from '../common/veriCodeInput' // import VeriCodeButton from '../common/veriCodeInput'
// import LoginWays from '../common/LoginWays' // import LoginWays from '../common/LoginWays'
class AccountLogin extends Component { class AccountLogin extends PureComponent {
render() { render() {
return ( return (
...@@ -40,6 +43,7 @@ class AccountLogin extends Component { ...@@ -40,6 +43,7 @@ class AccountLogin extends Component {
render={({field}) => ( render={({field}) => (
<PasswordInput <PasswordInput
{...field} {...field}
autoComplete={'on'}
placeholder={'密码'} placeholder={'密码'}
/> />
)} )}
...@@ -58,10 +62,32 @@ const formikConfig = { ...@@ -58,10 +62,32 @@ const formikConfig = {
account: '', account: '',
password: '' password: ''
}), }),
handleSubmit(values) { handleSubmit(values, formikBag) {
console.log(values) const {account: username, password} = values
const {props, props: {history}} = formikBag
props.accountLogin({
username, password
}).then(res => {
if (!res.hasError) {
let {from} = props.location.state || {from: {pathname: '/'}}
history.push(from.pathname)
}
})
} }
} }
const mapStateToProps = state => ({
user: state.user
})
const mapDispatchToProps = {
accountLogin
}
export default compose( export default compose(
connect(
mapStateToProps,
mapDispatchToProps
),
withFormik(formikConfig) withFormik(formikConfig)
)(AccountLogin) )(AccountLogin)
...@@ -17,12 +17,10 @@ class ForgotPassword extends Component { ...@@ -17,12 +17,10 @@ class ForgotPassword extends Component {
} }
setTel = (val) => { setTel = (val) => {
console.log(val)
this.setState({tel: val}) this.setState({tel: val})
} }
setVerificationCode = (val) => { setVerificationCode = (val) => {
console.log(val)
this.setState({verificationCode: val}); this.setState({verificationCode: val});
} }
......
...@@ -18,7 +18,6 @@ class SetPassword extends Component { ...@@ -18,7 +18,6 @@ class SetPassword extends Component {
handleChange = (val) => { handleChange = (val) => {
console.log(val)
this.setState({password: val}); this.setState({password: val});
} }
......
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux' import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux' import { Provider } from 'react-redux'
import thunk from 'redux-thunk' import thunk from 'redux-thunk'
import logger from 'redux-logger' import logger from 'redux-logger'
import rootReducers from './store' import rootReducers from './store'
import App from './App' import App from './App'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore( const store = createStore(
rootReducers, rootReducers,
applyMiddleware(thunk, logger) composeEnhancers(
applyMiddleware(thunk, logger)
)
) )
......
import React from 'react' import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom' import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import RouterConfig from './router-config' import RouterConfig from './router-config'
import PrivateRoute from './privateRoute'
export default function () { export default function () {
...@@ -8,9 +9,9 @@ export default function () { ...@@ -8,9 +9,9 @@ export default function () {
<Router> <Router>
<Switch> <Switch>
{RouterConfig.map((item, index) => { {RouterConfig.map((item, index) => {
let {CustomRoute, ...rest} = item let {isPrivate, ...rest} = item
if (CustomRoute) { if (isPrivate) {
return <CustomRoute {...rest}/> return <PrivateRoute {...rest} key={index}/>
} else { } else {
return ( return (
<Route {...rest} key={index}/> <Route {...rest} key={index}/>
......
import React from 'react';
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
const PrivateRoute = ({component: Component, path, user, ...rest}) => {
let authenticated = Object.keys(user.data).some(item => !!user.data[item])
return (
<Route {...rest} render={props => {
return authenticated
? <Component {...props}/>
: <Redirect to={{
pathname: '/passport/account-login',
state: {from: props.location}
}}/>
}}/>
);
};
export default connect(
state => ({user: state.user}),
null
)(PrivateRoute);
\ No newline at end of file
...@@ -68,7 +68,8 @@ export default [ ...@@ -68,7 +68,8 @@ export default [
}, },
{ {
path: '/coupons', path: '/coupons',
component: Coupons component: Coupons,
isPrivate: true
}, },
{ {
path: '/shopcart', path: '/shopcart',
......
...@@ -12,6 +12,7 @@ module.exports = function (app) { ...@@ -12,6 +12,7 @@ module.exports = function (app) {
pathRewrite: { pathRewrite: {
[`^${config[item]['development']}`]: '' [`^${config[item]['development']}`]: ''
}, },
cookieDomainRewrite: 'localhost',
...config[item]['proxy'] ...config[item]['proxy']
} }
)) ))
......
import { combineReducers } from 'redux'; import { combineReducers } from 'redux';
import myCourses from '@/components/study/myCourses/reducers' import myCourses from '@/components/study/myCourses/reducers'
import user from './userReducer'
const reducer = combineReducers({ const reducer = combineReducers({
myCourses myCourses,
user
}); });
export default reducer; export default reducer;
\ No newline at end of file
import { http, api } from '@/utils';
import { encrypt } from '@/components/passport/encryption';
import jsCookie from 'js-cookie'
const accountLogin = user => dispatch => {
return http.post(`${api['passport-api']}/user_login`, {
user_name: user.username,
password: encrypt(user.password),
is_encrypt: 1
}).then(res => {
const data = res.data
let payload
if (data.errno === 0) {
const {user_name: username, avatar_file: avatar, ...rest} = data.data.user_info
payload = {
hasError: false,
msg: data.msg,
data: {username, avatar, ...rest}
}
} else {
payload = {
hasError: true,
msg: data.msg
}
}
dispatch(setCurrentUser(payload))
return payload
})
}
/*
const CAPTCHA_LOGIN = 'CAPTCHA_LOGIN'
const captchaLogin = payload => dispatch => {
return http.post(`${api['passport-api']}/`)
}
*/
const SET_CURRENT_USER = 'SET_CURRENT_USER'
const setCurrentUser = payload => ({
type: SET_CURRENT_USER,
payload
})
const LOGOUT = 'LOGOUT'
const logout = () => dispatch => {
jsCookie.remove('token')
jsCookie.remove('uid')
dispatch(setCurrentUser({}))
}
export {
accountLogin,
SET_CURRENT_USER,
setCurrentUser
}
\ No newline at end of file
import { SET_CURRENT_USER } from '@/store/userAction';
const initialState = {
hasError: false,
msg: '',
data: {
username: '',
avatar: '',
isVip: false,
token: '',
email: '',
uid: ''
}
}
export default function (state = initialState, action) {
switch (action.type) {
case SET_CURRENT_USER:
return action.payload
default:
return state
}
}
\ No newline at end of file
export { default as http } from './http' export { default as http } from './http'
export { default as api } from './api' export { default as api } from './api'
// 计算时间相差fn(过去距离当前时间) export { html }
export const computingTime = (pastTime) => {
var currentTime = (new Date()).getTime(),
distanceTime = currentTime - pastTime,
// 计算相差天数
days = Math.floor(distanceTime / (24 * 3600 * 1000)),
// 计算相差小时数
leave1 = distanceTime % (24 * 3600 * 1000),
hours = Math.floor(leave1 / (3600 * 1000)),
// 计算相差分钟数
leave2 = leave1 % (3600 * 1000),
minutes = Math.floor(leave2 / (60 * 1000)),
// 计算相差毫秒数
leave3 = leave2 % (60 * 1000),
seconds = Math.round(leave3 / 1000),
// 处理返回格式
dayStr = days <= 0 ? "" : days + "天",
hourStr = hours <= 0 ? "" : hours + "小时",
minuteStr = minutes <= 0 ? "" : minutes + "分钟",
secondStr = (days <= 0 && hours <= 0 && minutes <= 0) ? "刚刚" : "前";
// secondStr=seconds==0?"":seconds+"秒";
if (days >= 1) {
return dayStr + '前';
} else {
return dayStr + hourStr + minuteStr + secondStr;
}
}
// 时间倒计时 (未来距离现在)
export const timeDown = (endDate) => {
var now = new Date();
var leftTime = endDate - now.getTime();
var leftsecond = parseInt(leftTime / 1000);
var day1 = Math.floor(leftsecond / (60 * 60 * 24));
var hour = Math.floor((leftsecond - day1 * 24 * 60 * 60) / 3600);
var minute = Math.floor((leftsecond - day1 * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftsecond - day1 * 24 * 60 * 60 - hour * 3600 - minute * 60);
hour = hour >= 10 ? hour : '0' + hour;
minute = minute >= 10 ? minute : '0' + minute;
second = second >= 10 ? second : '0' + second;
return day1 + '天' + hour + ':' + minute + ':' + second;
return leftTime;
}
export const isPhone = ($poneInput) => {
var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
if (!myreg.test($poneInput)) {
return true;
} else {
return false;
}
}
export const getParam = (key, str) => { export const getParam = (key, str) => {
const _s = str ? str : location.href; const _s = str ? str : location.href;
const re = new RegExp(`(?:\\?|#|&)(${key})=([^=&#\\?]+)`, 'ig'); const re = new RegExp(`(?:\\?|#|&)(${key})=([^=&#\\?]+)`, 'ig');
let found; let found;
return (found = re.exec(_s)) ? found[2] : null; return (found = re.exec(_s)) ? found[2] : null;
} }
\ No newline at end of file
const html = content => ({__html: htmlDecode(content)})
const htmlDecode = content => {
let e = document.createElement('div');
e.innerHTML = content;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment