Commit cbb48655 by zhanghaozhe

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

parent bc6030d8
import React, {Component} from 'react'
import React, { Component } from 'react'
import Routes from './router'
import cookie from 'js-cookie'
import { http, api } from '@/utils';
import { connect } from 'react-redux';
import { setCurrentUser } from '@/store/userAction';
//拦截ajax请求,返回mock数据
/*import mock from '@/utils/mock'
......@@ -13,15 +17,57 @@ import './assets/css/index.scss';
// iconfont
import './assets/font/iconfont.css';
class App extends Component {
componentDidMount() {
export default class App extends Component{
componentDidMount(){
//平台信息
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
}
}
render(){
} else {
payload = {
hasError: true,
msg: res.data.msg
}
}
return payload
}
render() {
return <Routes/>
}
}
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 { Link } from "react-router-dom";
import { withFormik, FastField, Form } from "formik";
import { compose } from 'redux';
import { accountLogin } from '@/store/userAction';
import { connect } from "react-redux";
import Header from "../common/Header";
......@@ -12,7 +14,8 @@ import PasswordInput from '../common/passwordInput'
// import VeriCodeButton from '../common/veriCodeInput'
// import LoginWays from '../common/LoginWays'
class AccountLogin extends Component {
class AccountLogin extends PureComponent {
render() {
return (
......@@ -40,6 +43,7 @@ class AccountLogin extends Component {
render={({field}) => (
<PasswordInput
{...field}
autoComplete={'on'}
placeholder={'密码'}
/>
)}
......@@ -58,10 +62,32 @@ const formikConfig = {
account: '',
password: ''
}),
handleSubmit(values) {
console.log(values)
handleSubmit(values, formikBag) {
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(
connect(
mapStateToProps,
mapDispatchToProps
),
withFormik(formikConfig)
)(AccountLogin)
......@@ -17,12 +17,10 @@ class ForgotPassword extends Component {
}
setTel = (val) => {
console.log(val)
this.setState({tel: val})
}
setVerificationCode = (val) => {
console.log(val)
this.setState({verificationCode: val});
}
......
......@@ -18,7 +18,6 @@ class SetPassword extends Component {
handleChange = (val) => {
console.log(val)
this.setState({password: val});
}
......
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux'
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import logger from 'redux-logger'
import rootReducers from './store'
import App from './App'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(
rootReducers,
composeEnhancers(
applyMiddleware(thunk, logger)
)
)
......
import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import RouterConfig from './router-config'
import PrivateRoute from './privateRoute'
export default function () {
......@@ -8,9 +9,9 @@ export default function () {
<Router>
<Switch>
{RouterConfig.map((item, index) => {
let {CustomRoute, ...rest} = item
if (CustomRoute) {
return <CustomRoute {...rest}/>
let {isPrivate, ...rest} = item
if (isPrivate) {
return <PrivateRoute {...rest} key={index}/>
} else {
return (
<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 [
},
{
path: '/coupons',
component: Coupons
component: Coupons,
isPrivate: true
},
{
path: '/shopcart',
......
......@@ -12,6 +12,7 @@ module.exports = function (app) {
pathRewrite: {
[`^${config[item]['development']}`]: ''
},
cookieDomainRewrite: 'localhost',
...config[item]['proxy']
}
))
......
import { combineReducers } from 'redux';
import myCourses from '@/components/study/myCourses/reducers'
import user from './userReducer'
const reducer = combineReducers({
myCourses
myCourses,
user
});
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 api } from './api'
// 计算时间相差fn(过去距离当前时间)
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 { html }
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) => {
const _s = str ? str : location.href;
......@@ -58,3 +11,13 @@ export const getParam = (key, str) => {
let found;
return (found = re.exec(_s)) ? found[2] : null;
}
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