TODO: config load

This commit is contained in:
huangsimin 2020-01-06 18:09:49 +08:00
parent 6617b483cf
commit 250a40f83e
6 changed files with 91 additions and 35 deletions

51
main.go
View File

@ -10,50 +10,77 @@ import (
) )
const ( const (
// SessionKey Session主Key
SessionKey = "token"
// SessionUser 用户登录的Session标签 // SessionUser 用户登录的Session标签
SessionUser = "token" SessionUser = "user"
) )
func auth(ctx *gin.Context) { func auth(ctx *gin.Context) {
if ctx.Request.RequestURI != "/api/login" { if ctx.Request.RequestURI != "/api/login" {
session := sessions.Default(ctx) session := sessions.Default(ctx)
if token := session.Get(SessionUser); token == nil { if token := session.Get(SessionUser); token == nil {
ctx.Redirect(http.StatusNotModified, "/api/login") session.Clear()
session.Save()
ctx.JSON(http.StatusUnauthorized, gin.H{"message": "需要登录"})
return return
} }
} }
ctx.Next() ctx.Next()
} }
func login(ctx *gin.Context) { func login(ctx *gin.Context) {
ctx.Request.ParseForm()
user := ctx.PostForm("user") user := ctx.PostForm("user")
session := sessions.Default(ctx)
if user == "" {
if tokenUser := session.Get(SessionUser); tokenUser != nil {
ctx.JSON(http.StatusOK, gin.H{"user": tokenUser})
return
}
}
if realPassword, ok := GlobalConfig.GetUser(user); ok { if realPassword, ok := GlobalConfig.GetUser(user); ok {
pwd := ctx.PostForm("pwd") pwd := ctx.PostForm("pwd")
if realPassword == pwd { if realPassword == pwd {
session := sessions.Default(ctx)
session.Set(SessionUser, user) session.Set(SessionUser, user)
session.Save() session.Save()
} else { ctx.JSON(http.StatusOK, gin.H{"message": "登录成功"})
return
}
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"}) ctx.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
return return
} }
} else {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "不存在该用户"}) ctx.JSON(http.StatusUnauthorized, gin.H{"error": "不存在该用户"})
return return
}
ctx.JSON(http.StatusOK, gin.H{"message": "登录成功"})
// ctx.Redirect(http.StatusOK, "/worker") // ctx.Redirect(http.StatusOK, "/worker")
// ctx.Next()
}
func logout(ctx *gin.Context) {
session := sessions.Default(ctx)
session.Clear()
session.Save()
} }
func userConfig(ctx *gin.Context) { func userConfig(ctx *gin.Context) {
ctx.Request.ParseForm()
session := sessions.Default(ctx) session := sessions.Default(ctx)
if session.Get(SessionUser) == nil { user := session.Get(SessionUser)
// log.Println(user)
if user == nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "权限错误"}) ctx.JSON(http.StatusUnauthorized, gin.H{"error": "权限错误"})
return return
} }
@ -64,10 +91,12 @@ func main() {
eg := gin.New() eg := gin.New()
eg.Use(sessions.Sessions(SessionUser, cookie.NewStore([]byte("yame")))) eg.Use(sessions.Sessions(SessionKey, cookie.NewStore([]byte("yame"))))
eg.Use(auth) eg.Use(auth)
eg.POST("/api/login", login) eg.POST("/api/login", login)
eg.POST("/api/user/config", userConfig) eg.POST("/api/user/config", userConfig)
eg.POST("/api/user/logout", logout)
log.Fatal(eg.Run(":3001")) log.Fatal(eg.Run(":3001"))
} }

View File

@ -1,20 +1,9 @@
package main package main
import ( import (
"log"
"testing" "testing"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
) )
func TestMain(t *testing.T) { func TestMain(t *testing.T) {
eg := gin.New() main()
eg.Use(sessions.Sessions(SessionUser, cookie.NewStore([]byte("yame"))))
eg.Use(auth)
eg.POST("/api/login", login)
log.Fatal(eg.Run(":3001"))
} }

View File

@ -1,4 +1,5 @@
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'; import axios from 'axios';
import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button } from 'antd'; import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button } from 'antd';
import './App.css'; import './App.css';
@ -9,9 +10,21 @@ import Login from './login';
const { Option } = Select; const { Option } = Select;
// 响应拦截
axios.interceptors.response.use((response) => {
return response
}, (err) => {
if(err.response.status === 401){
ReactDOM.render(<App></App>, document.getElementById('root'));
}
return Promise.reject(err)
})
const App = () => ( const App = () => (
<SiderConfig></SiderConfig> <Login isAutoLogin={true}></Login>
// <SiderConfig></SiderConfig>
); );

View File

@ -10,6 +10,21 @@ import SiderConfig from './siderConfig';
class Login extends React.Component { class Login extends React.Component {
componentWillMount() {
if(this.props.isAutoLogin) {
axios.post("/api/login", new FormData()).then(loginInfo => {
axios.post("/api/user/config", new FormData()).then( value => {
console.log(value);
ReactDom.render(<SiderConfig userName={loginInfo.data["user"]}></SiderConfig>, document.getElementById('root'))
} )
return
});
}
}
onClick = (e) => { onClick = (e) => {
var user = this.refs["login-user"].input.value var user = this.refs["login-user"].input.value
var pwd = this.refs["login-passwd"].input.value var pwd = this.refs["login-passwd"].input.value
@ -22,13 +37,12 @@ class Login extends React.Component {
console.log("Cookies are ", document.cookie) console.log("Cookies are ", document.cookie)
ReactDom.render(<SiderConfig userName={user}></SiderConfig>, document.getElementById('root')) ReactDom.render(<SiderConfig userName={user}></SiderConfig>, document.getElementById('root'))
return return
}); });
} }
render() { render() {
return ( return (
<Layout style={{ minHeight: "100vh" }}> <Layout onPlay={this.onLoad} style={{ minHeight: "100vh" }}>
<div style={{ marginTop: "30vh" }}> <div style={{ marginTop: "30vh" }}>
<Row className="login-input" type="flex" justify="center"><Title>Apollo Local</Title></Row> <Row className="login-input" type="flex" justify="center"><Title>Apollo Local</Title></Row>

View File

@ -21,8 +21,8 @@ class NamespaceSelect extends React.Component {
onDropdownVisibleChange = (open) => { onDropdownVisibleChange = (open) => {
if(open) { if(open) {
var resp = axios.post("/api/user/config") var resp = axios.post("/api/user/config")
console.log(resp)
console.log(resp)
} }
} }

View File

@ -1,8 +1,12 @@
import React from 'react'; import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import { Layout, Menu, Breadcrumb, Icon, Button, Row, Col, Tag } from 'antd'; import { Layout, Menu, Breadcrumb, Icon, Button, Row, Col, Tag } from 'antd';
import { Input } from 'antd'; import { Input } from 'antd';
import NamespaceSelect from './namespaceSelect'; import NamespaceSelect from './namespaceSelect';
import Text from 'antd/lib/typography/Text'; import Text from 'antd/lib/typography/Text';
import Login from './login';
import App from './App';
const { TextArea } = Input; const { TextArea } = Input;
const { Header, Content, Footer, Sider } = Layout; const { Header, Content, Footer, Sider } = Layout;
@ -18,6 +22,15 @@ class SiderConfig extends React.Component {
this.setState({ collapsed }); this.setState({ collapsed });
}; };
onClickLogout = e => {
axios.post("/api/user/logout", new FormData()).then(loginInfo => {
ReactDom.render(<Login isAutoLogin={false} ></Login>, document.getElementById('root'));
return;
});
};
render() { render() {
return ( return (
<Layout style={{ minHeight: '100vh' }}> <Layout style={{ minHeight: '100vh' }}>
@ -34,9 +47,7 @@ class SiderConfig extends React.Component {
Namespace Namespace
</span> </span>
}> }>
<NamespaceSelect> <NamespaceSelect/>
</NamespaceSelect>
</SubMenu> </SubMenu>
@ -49,7 +60,7 @@ class SiderConfig extends React.Component {
<Col> <Col>
<Text style={{ alignSelf: "flex-end", fontSize: 16, color: "#f37b1d" }}>用户:</Text> <Text style={{ alignSelf: "flex-end", fontSize: 16, color: "#f37b1d" }}>用户:</Text>
<Text style={{ fontSize: 16 }}>{this.props.userName}</Text> <Text style={{ fontSize: 16 }}>{this.props.userName}</Text>
<Button type="primary" style={{ margin: "0px 10px 0 20px", width: '100px', }}>退出</Button> <Button onClick={this.onClickLogout} type="primary" style={{ margin: "0px 10px 0 20px", width: '100px', }}>退出</Button>
</Col> </Col>
</Row> </Row>