TODO: 权限完成

This commit is contained in:
eson 2020-01-07 04:25:45 +08:00
parent 250a40f83e
commit d8f261382d
4 changed files with 38 additions and 7 deletions

26
main.go
View File

@ -3,6 +3,7 @@ package main
import (
"log"
"net/http"
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
@ -22,12 +23,19 @@ func auth(ctx *gin.Context) {
session := sessions.Default(ctx)
if token := session.Get(SessionUser); token == nil {
if user := session.Get(SessionUser); user == nil {
session.Clear()
session.Save()
ctx.JSON(http.StatusUnauthorized, gin.H{"message": "需要登录"})
return
} else if user.(*User).Expired < time.Now().Unix() {
session.Clear()
session.Save()
ctx.JSON(http.StatusUnauthorized, gin.H{"message": "账号过期"})
return
}
}
@ -35,10 +43,10 @@ func auth(ctx *gin.Context) {
}
func login(ctx *gin.Context) {
user := ctx.PostForm("user")
userName := ctx.PostForm("user")
session := sessions.Default(ctx)
if user == "" {
if userName == "" {
if tokenUser := session.Get(SessionUser); tokenUser != nil {
ctx.JSON(http.StatusOK, gin.H{"user": tokenUser})
@ -47,10 +55,17 @@ func login(ctx *gin.Context) {
}
if realPassword, ok := GlobalConfig.GetUser(user); ok {
if realPassword, ok := GlobalConfig.GetUser(userName); ok {
pwd := ctx.PostForm("pwd")
if realPassword == pwd {
user := &User{Name: userName,
Expired: time.Now().Unix() + 15,
ConfigPath: "",
Config: nil,
}
session.Set(SessionUser, user)
session.Save()
ctx.JSON(http.StatusOK, gin.H{"message": "登录成功"})
@ -73,6 +88,7 @@ func logout(ctx *gin.Context) {
session := sessions.Default(ctx)
session.Clear()
session.Save()
ctx.JSON(http.StatusOK, gin.H{"message": "退出登录成功"})
}
func userConfig(ctx *gin.Context) {
@ -84,7 +100,7 @@ func userConfig(ctx *gin.Context) {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "权限错误"})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "获取配置成功"})
ctx.JSON(http.StatusOK, gin.H{"message": "获取配置成功", "user": user.(*User).Name})
}
func main() {

15
user.go Normal file
View File

@ -0,0 +1,15 @@
package main
import "encoding/gob"
func init() {
gob.Register(&User{})
}
// User 用户结构
type User struct {
Expired int64
Name string
ConfigPath string
Config interface{}
}

View File

@ -15,7 +15,7 @@ axios.interceptors.response.use((response) => {
return response
}, (err) => {
if(err.response.status === 401){
ReactDOM.render(<App></App>, document.getElementById('root'));
ReactDOM.render(<Login isAutoLogin={false}></Login>, document.getElementById('root'));
}
return Promise.reject(err)
})

View File

@ -17,7 +17,7 @@ class Login extends React.Component {
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'))
ReactDom.render(<SiderConfig userName={value.data["user"]}></SiderConfig>, document.getElementById('root'))
} )
return