feat: admin login page is ready

This commit is contained in:
RockYang 2023-06-19 11:09:23 +08:00
parent 120e54fb29
commit fe7f021ddb
12 changed files with 266 additions and 344 deletions

View File

@ -5,6 +5,7 @@ import (
"chatplus/core/types" "chatplus/core/types"
"chatplus/handler" "chatplus/handler"
logger2 "chatplus/logger" logger2 "chatplus/logger"
"chatplus/utils"
"chatplus/utils/resp" "chatplus/utils/resp"
"github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions"
@ -35,7 +36,12 @@ func (h *ManagerHandler) Login(c *gin.Context) {
} }
manager := h.App.AppConfig.Manager manager := h.App.AppConfig.Manager
if data.Username == manager.Username && data.Password == manager.Password { if data.Username == manager.Username && data.Password == manager.Password {
manager.Password = "" // 清空密码 err := utils.SetLoginAdmin(c, manager)
if err != nil {
resp.ERROR(c, "Save session failed")
return
}
manager.Password = "" // 清空密码]
resp.SUCCESS(c, manager) resp.SUCCESS(c, manager)
} else { } else {
resp.ERROR(c, "用户名或者密码错误") resp.ERROR(c, "用户名或者密码错误")

View File

@ -128,6 +128,7 @@ func main() {
group := s.Engine.Group("/api/admin/") group := s.Engine.Group("/api/admin/")
group.POST("login", h.Login) group.POST("login", h.Login)
group.GET("logout", h.Logout) group.GET("logout", h.Logout)
group.GET("session", h.Session)
}), }),
fx.Invoke(func(s *core.AppServer, h *admin.ApiKeyHandler) { fx.Invoke(func(s *core.AppServer, h *admin.ApiKeyHandler) {
group := s.Engine.Group("/api/admin/apikey/") group := s.Engine.Group("/api/admin/apikey/")

View File

@ -19,7 +19,7 @@ func SetLoginUser(c *gin.Context, user model.User) error {
func SetLoginAdmin(c *gin.Context, admin types.Manager) error { func SetLoginAdmin(c *gin.Context, admin types.Manager) error {
session := sessions.Default(c) session := sessions.Default(c)
session.Set(types.SessionAdmin, admin) session.Set(types.SessionAdmin, admin.Username)
return session.Save() return session.Save()
} }

View File

@ -1,2 +1,3 @@
VUE_APP_API_HOST= VUE_APP_API_HOST=
VUE_APP_WS_HOST= VUE_APP_WS_HOST=
VUE_APP_BASE_URL=

View File

@ -1,3 +0,0 @@
/**
* actions for chat page
*/

View File

@ -18,11 +18,12 @@ const routes = [
{name: 'register', path: '/register', component: Register, meta: {title: '用户注册'}}, {name: 'register', path: '/register', component: Register, meta: {title: '用户注册'}},
{name: 'plus', path: '/chat', component: ChatPlus, meta: {title: 'ChatGPT-智能助手V3'}}, {name: 'plus', path: '/chat', component: ChatPlus, meta: {title: 'ChatGPT-智能助手V3'}},
{name: 'admin', path: '/admin', component: Admin, meta: {title: 'Chat-Plus 控制台'}}, {name: 'admin', path: '/admin', component: Admin, meta: {title: 'Chat-Plus 控制台'}},
{name: 'admin/login', path: '/admin/login', component: AdminLogin, meta: {title: 'Chat-Plus 控制台登录'}}, {name: 'admin-login', path: '/admin/login', component: AdminLogin, meta: {title: 'Chat-Plus 控制台登录'}},
{name: 'test', path: '/test', component: TestPage, meta: {title: '测试页面'}}, {name: 'test', path: '/test', component: TestPage, meta: {title: '测试页面'}},
{name: 'NotFound', path: '/:all(.*)', component: NotFound, meta: {title: '页面没有找到'}}, {name: 'NotFound', path: '/:all(.*)', component: NotFound, meta: {title: '页面没有找到'}},
] ]
// console.log(MY_VARIABLE)
const router = createRouter({ const router = createRouter({
history: createWebHistory(), history: createWebHistory(),
routes: routes, routes: routes,

View File

@ -5,20 +5,14 @@
*/ */
const SessionUserKey = 'LOGIN_USER'; const SessionUserKey = 'LOGIN_USER';
const SessionAdminKey = 'LOGIN_ADMIN';
export function getSessionId() { export function getSessionId() {
const user = getLoginUser(); const user = getLoginUser();
return user ? user['session_id'] : ''; return user ? user['session_id'] : '';
} }
export function getLoginAdmin() { export function removeLoginUser() {
const value = sessionStorage.getItem(SessionAdminKey); sessionStorage.removeItem(SessionUserKey)
if (value) {
return JSON.parse(value);
} else {
return null;
}
} }
export function getLoginUser() { export function getLoginUser() {
@ -33,7 +27,3 @@ export function getLoginUser() {
export function setLoginUser(user) { export function setLoginUser(user) {
sessionStorage.setItem(SessionUserKey, JSON.stringify(user)) sessionStorage.setItem(SessionUserKey, JSON.stringify(user))
} }
export function setLoginAdmin(admin) {
sessionStorage.setItem(SessionAdminKey, JSON.stringify(admin))
}

View File

@ -183,9 +183,9 @@
</el-main> </el-main>
</el-container> </el-container>
<config-dialog :show="showConfigDialog" :models="models" @hide="showConfigDialog = false" <config-dialog v-if="user" :show="showConfigDialog" :models="models" @hide="showConfigDialog = false"
@update-user="updateUser"/> @update-user="updateUser"/>
<password-dialog :show="showPasswordDialog" @hide="showPasswordDialog = false" @logout="logout"/> <password-dialog v-if="user" :show="showPasswordDialog" @hide="showPasswordDialog = false" @logout="logout"/>
</div> </div>
@ -200,7 +200,6 @@ import {
Close, Close,
Delete, Delete,
Edit, Edit,
Monitor,
Plus, Promotion, Plus, Promotion,
RefreshRight, RefreshRight,
Search, Search,
@ -211,7 +210,7 @@ import 'highlight.js/styles/a11y-dark.css'
import {dateFormat, randString, removeArrayItem, renderInputText, UUID} from "@/utils/libs"; import {dateFormat, randString, removeArrayItem, renderInputText, UUID} from "@/utils/libs";
import {ElMessage, ElMessageBox} from "element-plus"; import {ElMessage, ElMessageBox} from "element-plus";
import hl from "highlight.js"; import hl from "highlight.js";
import {getLoginUser, getSessionId} from "@/utils/storage"; import {getLoginUser, getSessionId, removeLoginUser} from "@/utils/storage";
import {httpGet, httpPost} from "@/utils/http"; import {httpGet, httpPost} from "@/utils/http";
import {useRouter} from "vue-router"; import {useRouter} from "vue-router";
import Clipboard from "clipboard"; import Clipboard from "clipboard";
@ -269,15 +268,15 @@ if (!user.value) {
ElMessage.error('复制失败!'); ElMessage.error('复制失败!');
}) })
}); });
}
// //
httpGet('/api/config/get?key=system').then(res => { httpGet('/api/config/get?key=system').then(res => {
title.value = res.data.title; title.value = res.data.title;
models.value = res.data.models; models.value = res.data.models;
}).catch(e => { }).catch(e => {
ElMessage.error("加载系统配置失败: " + e.message) ElMessage.error("加载系统配置失败: " + e.message)
}) })
}
const checkSession = function () { const checkSession = function () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -631,6 +630,7 @@ const clearAllChats = function () {
const logout = function () { const logout = function () {
activelyClose.value = true; activelyClose.value = true;
httpGet('/api/user/logout').then(() => { httpGet('/api/user/logout').then(() => {
removeLoginUser();
router.push('login'); router.push('login');
}).catch(() => { }).catch(() => {
ElMessage.error('注销失败!'); ElMessage.error('注销失败!');
@ -720,8 +720,10 @@ const updateUser = function (data) {
} }
</script> </script>
<style lang="stylus"> <style scoped lang="stylus">
@import '@/assets/iconfont/iconfont.css'; @import '@/assets/iconfont/iconfont.css';
$sideBgColor = #252526;
$borderColor = #4676d0;
#app { #app {
height: 100%; height: 100%;
@ -729,8 +731,8 @@ const updateUser = function (data) {
height: 100%; height: 100%;
// left side // left side
.el-aside { .el-aside {
background-color: $sideBgColor;
.title-box { .title-box {
padding: 6px 10px; padding: 6px 10px;
display: flex; display: flex;
@ -859,19 +861,14 @@ const updateUser = function (data) {
display flex display flex
.el-image { .el-image {
display flex width: 20px;
height: 20px;
img { border-radius: 5px;
width: 20px;
height: 20px;
border-radius: 5px;
}
} }
.username { .username {
display flex display flex
line-height 24px; line-height 22px;
width 230px; width 230px;
padding-left 10px; padding-left 10px;
@ -890,6 +887,8 @@ const updateUser = function (data) {
.el-main { .el-main {
overflow: hidden; overflow: hidden;
--el-main-padding: 0;
margin: 0;
.chat-head { .chat-head {
width: 100%; width: 100%;

View File

@ -1,5 +1,5 @@
<template> <template>
<div class="common-layout"> <div class="admin-body common-layout">
<el-container> <el-container>
<el-container> <el-container>
<el-aside <el-aside
@ -13,7 +13,7 @@
<span class="text">{{ title }}</span> <span class="text">{{ title }}</span>
<span <span
class="fold" class="fold"
@click="hideSidebar()" @click="showSidebar = !showSidebar"
:style="{ right: foldIconRight + 'px' }" :style="{ right: foldIconRight + 'px' }"
> >
<el-icon> <el-icon>
@ -44,8 +44,16 @@
</li> </li>
</ul> </ul>
<el-row class="tool-box"> <el-row class="nav-footer">
<el-button type="primary" plain @click="logout" v-show="isLogin">退出登录</el-button> <div class="source">
<i class="iconfont icon-github"></i>
<el-link href="https://github.com/yangjian102621/chatgpt-plus" target="_blank">ChatGPT-Plus-V3</el-link>
</div>
<div class="logout" @click="logout">
<i class="iconfont icon-logout"></i>
<span>退出登录</span>
</div>
</el-row> </el-row>
</el-aside> </el-aside>
@ -80,47 +88,13 @@
</div> </div>
</div> </div>
</el-main> </el-main>
<el-dialog
v-model="showDialog"
title="管理后台登录"
width="30%"
:destroy-on-close="true"
>
<el-form :model="user" label-width="80px">
<el-form-item label="用户名:">
<el-input
v-model.trim="user.username"
autocomplete="off"
placeholder="请输入用户名"
/>
</el-form-item>
<el-form-item label="密码:">
<el-input
v-model.trim="user.password"
autocomplete="off"
type="password"
placeholder="请输入密码"
@keyup="loginInputKeyup"
/>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="showDialog = false">取消</el-button>
<el-button type="primary" @click="login">提交</el-button>
</span>
</template>
</el-dialog>
</el-container> </el-container>
</el-container> </el-container>
</div> </div>
</template> </template>
<script> <script setup>
import {defineComponent} from 'vue' import {computed, defineComponent, onMounted, ref} from 'vue'
import {Fold, Menu} from "@element-plus/icons-vue" import {Fold, Menu} from "@element-plus/icons-vue"
import XWelcome from "@/views/admin/Welcome.vue"; import XWelcome from "@/views/admin/Welcome.vue";
import SysConfig from "@/views/admin/SysConfig.vue"; import SysConfig from "@/views/admin/SysConfig.vue";
@ -130,267 +104,233 @@ import RoleList from "@/views/admin/RoleList.vue";
import {httpGet, httpPost} from "@/utils/http"; import {httpGet, httpPost} from "@/utils/http";
import {ElMessage} from "element-plus"; import {ElMessage} from "element-plus";
import {setLoginUser} from "@/utils/storage"; import {setLoginUser} from "@/utils/storage";
import {useRouter} from "vue-router";
const title = ref('Chat-Plus 控制台')
export default defineComponent({ const logo = ref('images/logo.png')
name: "XAdmin", const user = ref({})
components: {RoleList, UserList, SysConfig, XWelcome, Fold, Menu}, const navs = ref([
data() { {
return { id: 1,
title: "Chat-Plus 控制台", title: '系统配置',
logo: 'images/logo.png', tab: 'config',
user: {}, active: false,
navs: [
{
id: 1,
title: '系统配置',
tab: 'config',
active: false,
},
{
id: 2,
title: '口令管理',
tab: 'user',
active: false,
},
{
id: 3,
title: '角色管理',
tab: 'role',
active: false,
}
],
curNav: null,
curTab: 'welcome',
tabs: [],
isLogin: false,
showDialog: false,
// window height
winHeight: window.innerHeight,
showSidebar: true
}
}, },
{
computed: { id: 2,
sideWidth: function () { title: '口令管理',
return this.showSidebar ? 250 : 30 tab: 'user',
}, active: false,
foldIconRight: function () {
return this.showSidebar ? 3 : 0
},
nodeListPaddingLeft: function () {
return this.showSidebar ? 20 : 5
}
},
mounted: function () {
// bind window resize event
window.addEventListener("resize", function () {
this.winHeight = window.innerHeight
})
this.checkSession()
},
methods: {
checkSession: function () {
httpGet("/api/session/get").then(() => {
this.isLogin = true
}).catch(() => {
this.showDialog = true
})
},
//
loginInputKeyup: function (e) {
if (e.keyCode === 13) {
this.login();
}
},
//
login: function () {
if (!this.user.username || !this.user.password) {
ElMessage.error('请输入用户名和密码')
return
}
httpPost('/api/admin/login', this.user).then((res) => {
setLoginUser(res.data)
this.showDialog = false
this.isLogin = true
this.user = {}
}).catch((e) => {
ElMessage.error('登录失败,' + e.message)
})
},
logout: function () {
httpPost("/api/logout", {opt: "logout"}).then(() => {
this.checkSession();
this.isLogin = false
}).catch(() => {
ElMessage.error("注销失败");
})
},
arrayContains(array, value, compare) {
return arrayContains(array, value, compare);
},
hideSidebar: function () {
this.showSidebar = !this.showSidebar
},
// tab
addTab: function (nav) {
if (this.curNav) {
this.curNav.active = false
}
this.curNav = nav;
this.curNav.active = true;
this.curTab = nav.tab;
if (!arrayContains(this.tabs, nav.tab)) {
this.tabs.push(nav.tab);
}
},
changeTab: function (name) {
for (let i = 0; i < this.navs.length; i++) {
if (this.navs[i].tab === name) {
this.curNav.active = false
this.curNav = this.navs[i];
this.curNav.active = true;
break;
}
}
},
// tab
removeTab: function (name) {
this.tabs = removeArrayItem(this.tabs, name);
if (this.tabs.length === 0) {
this.curTab = 'welcome';
return;
}
for (let i = 0; i < this.navs.length; i++) {
if (this.navs[i].tab === this.tabs[this.tabs.length - 1]) {
this.addTab(this.navs[i]);
}
}
}
}, },
{
id: 3,
title: '角色管理',
tab: 'role',
active: false,
}
])
const tabs= ref([])
const curNav = ref(null)
const curTab = ref('welcome')
const winHeight = ref(window.innerHeight)
const showSidebar = ref(true)
const sideWidth = computed(() =>{
return showSidebar.value ? 250 : 30
}) })
const foldIconRight = computed(() =>{
return showSidebar.value ? 3 : 0
})
const nodeListPaddingLeft = computed(() =>{
return showSidebar.value ? 20 : 5
})
const router = useRouter()
onMounted(() => {
window.addEventListener("resize", function () {
winHeight.value = window.innerHeight
})
httpGet("/api/admin/session").catch(() => {
router.push('/admin/login')
})
})
const logout = function () {
httpGet("/api/admin/logout").then(() => {
router.push('/admin/login')
}).catch((e) => {
ElMessage.error("注销失败: "+ e.message);
})
}
// tab
const addTab= function (nav) {
if (curNav.value) {
curNav.value.active = false
}
nav.active = true
curNav.value = nav;
curTab.value = nav.tab;
if (!arrayContains(tabs.value, nav.tab)) {
this.tabs.push(nav.tab);
}
}
// tab
const changeTab= function (name) {
for (let i = 0; i < navs.value.length; i++) {
let _nav = navs.value[i]
if (_nav.tab === name) {
curNav.value.active = false // active
_nav.active = true
curNav.value = _nav;
break;
}
}
}
// tab
const removeTab= function (name) {
tabs.value = removeArrayItem(tabs.value, name);
if (tabs.value.length === 0) {
curTab.value = 'welcome';
return;
}
for (let i = 0; i < navs.value.length; i++) {
if (navs.value[i].tab === tabs.value[tabs.value.length - 1]) {
addTab(navs.value[i]);
}
}
}
</script> </script>
<style lang="stylus"> <style scoped lang="stylus">
$sideBgColor = #252526; $sideBgColor = #252526;
$borderColor = #4676d0; $borderColor = #4676d0;
.el-aside { .admin-body {
background-color: $sideBgColor; .el-aside {
background-color: $sideBgColor;
.title { .title {
text-align: center; text-align: center;
line-height: 60px; line-height: 60px;
color: #fff; color: #fff;
font-size: 20px; font-size: 20px;
border-bottom: 2px solid #333841; border-bottom: 2px solid #333841;
display flex display flex
flex-direction row flex-direction row
.logo { .logo {
background-color #ffffff background-color #ffffff
border-radius 50%; border-radius 50%;
width 32px; width 32px;
height 32px; height 32px;
margin: 12px 5px 0 5px; margin: 12px 5px 0 5px;
} }
.fold { .fold {
cursor: pointer; cursor: pointer;
position: relative;
top: 2px;
margin-left 10px;
}
}
.title.hide {
.text {
display none
}
.logo {
display none
}
.fold {
margin-left 5px;
}
}
.nav-list {
list-style: none;
position: relative;
margin: 0;
padding-left: 0;
text-align: left;
li {
line-height: 40px;
color: #aaa;
font-size: 14px;
cursor: pointer;
padding: 0 10px 0 10px;
border-bottom: 1px dashed #333841;
i {
margin-right: 6px;
position: relative; position: relative;
top: 1px; top: 2px;
} margin-left 10px;
.delete {
float: right;
} }
} }
li.active { .title.hide {
background-color: #363535 .text {
display none
}
.logo {
display none
}
.fold {
margin-left 5px;
}
}
.nav-list {
list-style: none;
position: relative;
margin: 0;
padding-left: 0;
text-align: left;
li {
line-height: 40px;
color: #ffffff;
font-size: 14px;
cursor: pointer;
padding: 0 10px 0 10px;
border-bottom: 1px dashed #333841;
i {
margin-right: 6px;
position: relative;
top: 1px;
}
.delete {
float: right;
}
}
li.active {
background-color: #363535
}
}
.nav-footer {
flex-direction column
div {
padding 10px 20px;
font-size 14px;
color #aaaaaa
.el-link {
color #aaaaaa
}
.iconfont {
margin-right 5px
position relative
top 1px
}
}
.logout {
cursor pointer
}
} }
} }
.tool-box { .el-main {
display flex --el-main-padding: 0;
justify-content center margin: 0;
padding 10px 20px; background-image url("~@/assets/img/bg_01.jpeg")
.main-container {
display: flex;
flex-flow: column;
.content-tabs {
background: #ffffff;
padding 10px 20px;
.el-tabs__item {
height 35px
line-height 35px
}
}
}
} }
} }
.el-main {
--el-main-padding: 0;
margin: 0;
background-image url("~@/assets/img/bg_01.jpeg")
.main-container {
display: flex;
flex-flow: column;
.content-tabs {
background: #ffffff;
padding 10px 20px;
.el-tabs__item {
height 35px
line-height 35px
}
}
}
}
</style> </style>

View File

@ -75,7 +75,7 @@ const login = function () {
httpPost('/api/admin/login', {username: username.value.trim(), password: password.value.trim()}).then((res) => { httpPost('/api/admin/login', {username: username.value.trim(), password: password.value.trim()}).then((res) => {
setLoginUser(res.data) setLoginUser(res.data)
router.push("admin") router.push("/admin")
}).catch((e) => { }).catch((e) => {
ElMessage.error('登录失败,' + e.message) ElMessage.error('登录失败,' + e.message)
}) })

View File

@ -4,22 +4,14 @@
</div> </div>
</template> </template>
<script> <script setup>
import {defineComponent} from "vue" import {defineComponent, onMounted, ref} from "vue"
export default defineComponent({ const winHeight = ref(window.innerHeight)
name: 'XWelcome', onMounted(() => {
data() { window.addEventListener("resize", function () {
return { winHeight.value = window.innerHeight
winHeight: window.innerHeight, })
}
},
mounted: function () {
const that = this
window.addEventListener("resize", function () {
that.winHeight = window.innerHeight
})
}
}) })
</script> </script>

View File

@ -10,16 +10,11 @@ module.exports = defineConfig({
}, },
plugins: [ plugins: [
new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}) new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000})
], ]
// resolve: {
// fallback: {
// fs: false,
// path: require.resolve('path-browserify')
// }
// }
}, },
publicPath: '/', publicPath: process.env.NODE_ENV === 'production' ? '/' : '/',
outputDir: 'dist', outputDir: 'dist',
crossorigin: "anonymous", crossorigin: "anonymous",
devServer: { devServer: {