create logs page

This commit is contained in:
mahyargdz
2024-11-18 18:56:14 +03:30
parent 7583fe1cb9
commit f75f890fa5
8 changed files with 688 additions and 371 deletions
+87 -66
View File
@@ -3,10 +3,8 @@
fixed
:minimize="minimize"
:show="show"
@update:show="
(value) =>
$store.commit('admin/set', ['sidebarShow', value])
">
@update:show="(value) => $store.commit('admin/set', ['sidebarShow', value])"
>
<CSidebarBrand class="d-md-down-none">
<a href="/" target="_blank">
<span style="color: #fff">پرتال خبری</span>
@@ -20,68 +18,86 @@
<CSidebarNavItem
name="صفحه اصلی"
:to="{ name: 'admin' }"
font-icon="fal fa-home" />
font-icon="fal fa-home"
/>
<CSidebarNavItem
name="مدیریت کاربران"
:to="{ name: 'admin-users' }"
v-if="hasPermission('superAdmin')"
fontIcon="fal fa-users"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت صفحات"
:to="{ name: 'admin-pages' }"
v-if="hasPermission('categories')"
fontIcon="fal fa-file"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت عملکرد"
:to="{ name: 'admin-pdfManagement' }"
v-if="hasPermission('categories')"
fontIcon="fal fa-file"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت پرونده خبری"
:to="{ name: 'admin-newsFile' }"
v-if="hasPermission('newsFile')"
font-icon="fal fa-cabinet-filing"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت اخبار"
:to="{ name: 'admin-news' }"
v-if="hasPermission('news')"
font-icon="fal fa-newspaper"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت چند رسانه ای ها"
v-if="hasPermission('gallery')"
:to="{ name: 'admin-gallery' }"
font-icon="fal fa-images"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت نظرسنجی ها"
:to="{ name: 'admin-polls', query: { page: 1 } }"
font-icon="fal fa-poll-people"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت انتخابات"
:exact="false"
:to="{ name: 'admin-elections' }"
v-if="hasPermission('elections')"
font-icon="fal fa-box-ballot" />
font-icon="fal fa-box-ballot"
/>
<CSidebarNavItem
name="مدیریت نشست ها"
:exact="false"
:to="{ name: 'admin-sessions' }"
v-if="hasPermission('superAdmin')"
font-icon="fal fa-solid fa-user"
/>
<CSidebarNavDropdown
name="میز خدمت"
:show="Boolean(unreadMeetingReq)"
v-if="hasPermission('superAdmin')"
font-icon="fal fa-browser">
font-icon="fal fa-browser"
>
<CSidebarNavItem
name="درخواست های ملاقات با استاندار"
:exact="false"
@@ -90,7 +106,8 @@
? { text: unreadMeetingReq, color: 'danger' }
: null
"
:to="{ name: 'admin-meeting' }" />
:to="{ name: 'admin-meeting' }"
/>
</CSidebarNavDropdown>
<!-- <CSidebarNavItem
@@ -102,16 +119,12 @@
<CSidebarNavDropdown
name="مدیریت پیام ها"
:show="
Boolean(
unreadContactMessages + unreadNewsMessages
)
"
:show="Boolean(unreadContactMessages + unreadNewsMessages)"
v-if="
hasPermission('comment-News') ||
hasPermission('comment-ContactUs')
hasPermission('comment-News') || hasPermission('comment-ContactUs')
"
fontIcon="fal fa-envelope">
fontIcon="fal fa-envelope"
>
<CSidebarNavItem
v-if="hasPermission('comment-News')"
name="کامنت های اخبار"
@@ -127,7 +140,8 @@
:to="{
name: 'admin-comments-type',
params: { type: 'News' },
}" />
}"
/>
<CSidebarNavItem
v-if="hasPermission('comment-ContactUs')"
name="پیام های تماس با ما"
@@ -143,83 +157,100 @@
:to="{
name: 'admin-comments-type',
params: { type: 'ContactUs' },
}" />
}"
/>
</CSidebarNavDropdown>
<CSidebarNavDropdown
name="تنظیمات"
v-if="hasPermission('superAdmin')"
fontIcon="fal fa-cog">
fontIcon="fal fa-cog"
>
<CSidebarNavItem
name="اخباری روی صفحه اصلی"
:to="{
name: 'admin-homePageNews',
query: { portal: 'ostandari' },
}" />
}"
/>
<CSidebarNavItem
name="مدیریت پیوندها"
:to="{ name: 'admin-links' }"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="استاندار"
:to="{
name: 'admin-contents-details',
params: { details: 'manager' },
}" />
}"
/>
<CSidebarNavItem
name="مدیریت اسلایدر"
:to="{ name: 'admin-slider' }"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="عکس شعار سال"
:to="{ name: 'admin-yearBanner' }" />
:to="{ name: 'admin-yearBanner' }"
/>
<CSidebarNavItem
name="دکمه ستاد انتخابات"
:to="{ name: 'admin-electionBtn' }" />
:to="{ name: 'admin-electionBtn' }"
/>
<CSidebarNavItem
name="آدرس ایمیل و شبکه های اجتماعی"
:to="{ name: 'admin-socialLinks' }" />
:to="{ name: 'admin-socialLinks' }"
/>
<CSidebarNavItem
name="مدیریت مناسبت ها"
:to="{ name: 'admin-occasion' }"
:exact="false" />
:exact="false"
/>
<CSidebarNavItem
name="مدیریت روز شمار"
:to="{ name: 'admin-counterDay' }" />
:to="{ name: 'admin-counterDay' }"
/>
<CSidebarNavItem
name="پشتیبان گیری از سایت"
:to="{ name: 'admin-backup' }" />
:to="{ name: 'admin-backup' }"
/>
</CSidebarNavDropdown>
<CSidebarNavDropdown
name="مدیریت صفحات خاص"
v-if="hasPermission('contents')"
fontIcon="fal fa-file-alt">
fontIcon="fal fa-file-alt"
>
<CSidebarNavItem
name="صفحه اصلی"
:to="{
name: 'admin-homePageManagement',
query: { portal: 'ostandari' },
}" />
}"
/>
<CSidebarNavItem
name="صفحه عملکرد"
:to="{
name: 'admin-contents-details',
params: { details: 'performance' },
}" />
}"
/>
<CSidebarNavItem
name="صفحه سیمای استان"
:to="{
name: 'admin-contents-details',
params: { details: 'sima' },
}" />
}"
/>
<CSidebarNavItem
name="صفحه درباره ما"
:to="{
name: 'admin-contents-details',
params: { details: 'aboutus' },
}" />
}"
/>
<!-- <CSidebarNavItem-->
<!-- name="صفحه خدمات"-->
<!-- :to="{ name: 'admin-contents-details' , params : {details : 'services'} }"-->
@@ -233,7 +264,8 @@
:to="{
name: 'admin-contents-details',
params: { details: 'privacy' },
}" />
}"
/>
<!-- <CSidebarNavItem-->
<!-- name="صفحه کوکی ها"-->
<!-- :to="{ name: 'admin-contents-details' , params : {details : 'cookies'} }"-->
@@ -251,31 +283,30 @@
:to="{
name: 'admin-contents-details',
params: { details: 'faq' },
}" />
}"
/>
<CSidebarNavItem
name="صفحه قوانین و مقررات"
:to="{
name: 'admin-contents-details',
params: { details: 'rules' },
}" />
}"
/>
<CSidebarNavItem
name="صفحه نقشه سایت"
:to="{
name: 'admin-contents-details',
params: { details: 'sitemap' },
}" />
}"
/>
</CSidebarNavDropdown>
</CSidebarNav>
<!-- sidebar content -->
<CSidebarMinimizer
class="d-md-down-none"
@click.native="
$store.commit('admin/set', [
'sidebarMinimize',
!minimize,
])
" />
@click.native="$store.commit('admin/set', ['sidebarMinimize', !minimize])"
/>
</CSidebar>
</template>
@@ -294,11 +325,7 @@ export default {
"مشکلی هنگام خروج از سیسیتم بوجود امده لطفا دوباره تلاش کنید",
};
},
mixins: [
unreadNewsMessages,
unreadContactMessages,
unreadMeetingReq,
],
mixins: [unreadNewsMessages, unreadContactMessages, unreadMeetingReq],
computed: {
show() {
return this.$store.state.admin.sidebarShow;
@@ -307,12 +334,10 @@ export default {
return this.$store.state.admin.sidebarMinimize;
},
unreadNewsMessages() {
return this.$store.state.admin
.unreadNewsMessagesCount;
return this.$store.state.admin.unreadNewsMessagesCount;
},
unreadContactMessages() {
return this.$store.state.admin
.unreadContactMessagesCount;
return this.$store.state.admin.unreadContactMessagesCount;
},
unreadMeetingReq() {
return this.$store.state.admin.unreadMeetingReqCount;
@@ -321,13 +346,9 @@ export default {
methods: {
hasPermission(permission) {
if (this.$auth.loggedIn) {
if (
this.$auth.user.permissions.includes("superAdmin")
) {
if (this.$auth.user.permissions.includes("superAdmin")) {
return true;
} else if (
this.$auth.user.permissions.includes(permission)
) {
} else if (this.$auth.user.permissions.includes(permission)) {
return true;
} else {
return false;
+16 -12
View File
@@ -3,7 +3,6 @@ const webpack = require("webpack");
const serverPort = 3756;
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: "پورتال خبری استانداری",
@@ -44,18 +43,27 @@ export default {
type: "text/css",
href: "/js/flipBook/font-awesome.css",
},
{ rel: 'stylesheet',
href: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js' }
{
rel: "stylesheet",
href: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js",
},
],
script: [
{ src: "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js" },
{ src: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" },
{
src: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js",
},
{ src: "/js/flipBook/flipbook.min.js" },
{ src: "/js/lightBox/simple-lightbox.min.js" },
{ src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', defer: true },
{ src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery-flipbook/1.0.5/jquery.flipbook.min.js', defer: true }
{
src: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js",
defer: true,
},
{
src: "https://cdnjs.cloudflare.com/ajax/libs/jquery-flipbook/1.0.5/jquery.flipbook.min.js",
defer: true,
},
],
},
loading: "~/components/pageLoad.vue",
@@ -68,7 +76,6 @@ export default {
"~/assets/scss/main.scss",
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
"@/plugins/element-ui",
@@ -85,10 +92,7 @@ export default {
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: [
"~/components/",
{ path: "~/components/admin/", prefix: "" },
],
components: ["~/components/", { path: "~/components/admin/", prefix: "" }],
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
+95 -57
View File
@@ -4,23 +4,23 @@
<CCardGroup>
<CCard class="p-4">
<CCardBody>
<CForm
v-if="step === 1"
@submit.prevent="doLogin">
<CForm v-if="step === 1" @submit.prevent="doLogin">
<h1 class="text-muted text-center mb-5">پنل مدیریت</h1>
<CInput
:class="validation.username ? 'err' : null"
placeholder="شماره موبایل"
:description="validation.username ? validation.username.msg : null"
:description="
validation.username ? validation.username.msg : null
"
autocomplete="username email"
v-model="phone"
>
<template #prepend-content>
<CIcon name="cil-user"/>
<CIcon name="cil-user" />
</template>
</CInput>
<!--
<!--
<CInput
:class="validation.username ? 'err' : null"
@@ -54,40 +54,38 @@
<CInputCheckbox label="مرا به خاطر بسپار" @update:checked="val => login.remember_me = val"/> -->
<CRow>
<CCol col="12" class="text-right mt-2">
<CButton color="primary" @click="send_number" class="px-4">ارسال کد</CButton>
<CButton color="primary" @click="send_number" class="px-4"
>ارسال کد</CButton
>
</CCol>
</CRow>
<!-- <p class="text-muted mt-3" style="font-size: 11px;">*درصورتی که گزینه "مرا به خاطر بسپار" را فعال نکنید بعد از 1 ساعت باید دوباره وارد سیستم شوید.</p> -->
</CForm>
<CForm
v-if="step === 2"
@submit.prevent="doLogin">
<CForm v-if="step === 2" @submit.prevent="doLogin">
<h1 class="text-muted text-center mb-5">پنل مدیریت</h1>
<CInput
:class="validation.username ? 'err' : null"
placeholder="کد ورود را وارد کنید"
:description="validation.username ? validation.username.msg : null"
:description="
validation.username ? validation.username.msg : null
"
autocomplete="username email"
v-model="otp"
>
<template #prepend-content>
<CIcon name="cil-user"/>
<CIcon name="cil-user" />
</template>
</CInput>
<CRow>
<CCol col="12" class="text-right mt-2">
<CButton color="primary" type="submit" class="px-4">ارسال کد</CButton>
<CButton color="primary" type="submit" class="px-4"
>ورود</CButton
>
</CCol>
</CRow>
</CForm>
</CCardBody>
</CCard>
</CCardGroup>
@@ -96,71 +94,111 @@
</template>
<script>
import { ref } from 'vue';
import { ref } from "vue";
export default {
data() {
return {
showPass: false,
step: 1,
phone: '',
otp: '',
phone: "",
otp: "",
login: {
username: '',
password: '',
remember_me: false
username: "",
password: "",
remember_me: false,
},
validation: {}
}
validation: {},
};
},
computed: {
passwordState() {
return this.showPass ? "text" : "password"
}
return this.showPass ? "text" : "password";
},
},
methods: {
async send_number(){
console.log(this.phone)
const phoneNumber = this.phone
const send_request = await fetch('/api/auth/otp', {
method: 'POST',
async send_number() {
if (!this.phone) {
this.$message({
type: "warning",
message: "شماره تماس را وارد کنید !",
});
return;
}
try {
const phoneNumber = this.phone;
const send_request = await fetch("/api/auth/otp", {
method: "POST",
headers: {
'Accept' : 'application/json',
'content-type' : 'application/json'
Accept: "application/json",
"content-type": "application/json",
},
body: JSON.stringify({phone: phoneNumber})
body: JSON.stringify({ phone: phoneNumber }),
});
})
//if (send_request.status === 200) {
this.step = 2
//}
if (send_request.status === 429 || send_request.status === 406) {
this.$message({
type: "warning",
message: "شما دسترسی ورود ندارید !",
});
return;
}
if (send_request.status === 200 || send_request.status === 201) {
this.$message({
type: "success",
message: "کد ورود ارسال شد",
});
this.step = 2;
return;
} else {
this.$message({
type: "warning",
message: "مشکل در برقرای ارتباط",
});
}
} catch (error) {
console.log("err", error);
this.$message({
type: "warning",
message: "خطای ناشناخته",
});
return;
}
},
doLogin() {
this.validation = {}
this.validation = {};
this.$auth.loginWith('local', {
this.$auth
.loginWith("local", {
data: {
phone: this.phone,
code: this.otp
}
code: this.otp,
},
})
.then(response => {
window.location.replace(window.location.origin + "/admin" )
.then((response) => {
window.location.replace(window.location.origin + "/admin");
})
.catch(err => {
if (err.response.status === 422) this.validation = err.response.data.validation
.catch((err) => {
if (err.response.status === 422)
this.validation = err.response.data.validation;
if (err.response.status === 403) {
this.$message({
type: 'warning',
message: err.response.data.message
})
} else console.log(err.response.data)
})
type: "warning",
message: err.response.data.message,
});
} else {
this.$message({
type: "warning",
message: err?.response?.data?.validation?.code?.msg,
});
console.log(err.response.data.validation.code.msg);
}
});
},
layout: 'admin-auth',
}
},
layout: "admin-auth",
};
</script>
<style lang="scss">
+245
View File
@@ -0,0 +1,245 @@
<template>
<div>
<CCard>
<CCardHeader>
<slot name="header">
<i class="fal fa-bars"></i>
<span>{{ list_title }}</span>
</slot>
<slot></slot>
</CCardHeader>
<CCardBody>
<el-table v-loading="loading" :data="sessions" style="width: 100%">
<el-table-column type="index" label="#"> </el-table-column>
<el-table-column label="نام کاربر">
<template slot-scope="scope">
<span class="title">
<el-popover
placement="top-end"
trigger="hover"
:content="scope.row.title"
>
</el-popover>
{{ scope.row?.user?.firstName + scope?.row?.user?.lastName }}
</span>
</template>
</el-table-column>
<el-table-column label="شماره موبایل">
<template slot-scope="scope">
<span class="title">
<el-popover
placement="top-end"
trigger="hover"
:content="scope.row.title"
>
</el-popover>
{{ scope.row?.user?.mobileNumber }}
</span>
</template>
</el-table-column>
<el-table-column label="آی پی">
<template slot-scope="scope">
<span class="title">
<el-popover
placement="top-end"
trigger="hover"
:content="scope.row.title"
>
</el-popover>
{{ scope.row?.ip }}
</span>
</template>
</el-table-column>
<el-table-column label="تاریخ ورود" width="">
<template slot-scope="scope">
<span>{{ scope.row.LastLogin }}</span>
</template>
</el-table-column>
</el-table>
</CCardBody>
</CCard>
<CCard class="col">
<CRow alignHorizontal="center" style="padding: 10px">
<el-pagination
:hide-on-single-page="true"
layout="prev, pager, next"
page-size="10"
@current-change="change_page"
:current-page.sync="elections.page"
:total="length"
>
</el-pagination>
</CRow>
</CCard>
</div>
</template>
<script>
import moment from "moment-jalaali";
export default {
data() {
return {
title: "لیست انتخابات",
list_title: "لیست",
elections: null,
search: {},
parent: null,
loading: false,
sessions: [],
length: null,
page: 1,
};
},
computed: {
pageQuery() {
return this.$route.query.page;
},
},
watch: {
pageQuery(newPage, oldPage) {
this.$nuxt.refresh();
},
},
mounted() {
this.getData();
},
methods: {
jDate(date) {
return moment(date).format("jYYYY/jMM/jDD");
},
async change_page(value) {
this.page = value;
this.getData();
},
async getData() {
try {
const response = await this.$axios.get(
`/api/admin/logs?page=${this.page}&limit=10`
);
// const data = await response.json(); // if you want to parse JSON response
console.log(response, "res");
this.sessions = response?.data?.logs;
this.length = response?.data?.totalLogs;
} catch (error) {
console.error("Failed to fetch data:", error);
}
},
deletePoll(id) {
this.$confirm("انتخابات حذف شود؟", "اخطار", {
confirmButtonText: "بله",
cancelButtonText: "لغو",
type: "warning",
})
.then(async () => {
this.$axios
.delete(`/api/admin/election/${id}`)
.then((res) => {
this.$message({
type: "success",
message: "انتخابات با موفقیت حذف شد",
});
this.elections.docs = this.elections.docs.filter(
(item) => item._id !== id
);
})
.catch((err) => {
if (err.response.status === 401) {
return this.$message({
type: "error",
message: "لطفا دوباره وارد سیستم شوید.",
});
}
if (err.response.status === 403) {
return this.$message({
type: "error",
message: err.response.data.message,
});
}
if (err.response.status === 422) {
return this.$message({
type: "error",
message: err.response.data.message,
});
}
console.log(err.response.data);
});
})
.catch(() => {
this.$message({
type: "warning",
message: "عملیات لغو شد",
});
});
},
handleCurrentChange(page) {
this.handleSearch(page);
},
handleSearch(page) {
this.loading = true;
const data = {
term: this.search.term,
catId: this.search.catId,
showInHome: this.search.showInHome,
};
this.$axios
.post(`/api/admin/election/search?page=${page}`, data, this.axiosConfig)
.then((result) => {
this.elections = result.data;
this.loading = false;
})
.catch((err) => {
this.loading = false;
if (err.response.status === 401) {
return this.$message({
type: "error",
message: "لطفا دوباره وارد سیستم شوید.",
});
}
if (err.response.status === 422)
this.validation = err.response.data.validation;
else console.log(err.response.data);
});
},
},
head() {
return {
title: this.title,
};
},
layout: "admin",
async asyncData({ $axios, query, error }) {
try {
const requests = [
$axios.get(`/api/admin/election?page=${query.page}`),
$axios.get("/api/admin/category/getParent"),
];
const fetch = await Promise.all(requests);
let [elections, parents] = fetch;
return {
elections: elections.data,
parents: parents.data,
};
} catch (e) {
if (e?.response?.status === 401)
error({
status: 401,
message: "شما اجازه دسترسی به این صفحه را ندارید",
});
else
error({
status: 500,
message: "مشکلی در گرفتن اطلاعات بوجود آمده است",
});
}
},
};
</script>
+43 -36
View File
@@ -1,37 +1,41 @@
const jwt = require('jsonwebtoken')
const User = require('./models/User');
const {res500} = require('./plugins/controllersHelperFunctions');
const Category = require('./models/Category');
const Election = require('./models/Election');
const jwt = require("jsonwebtoken");
const User = require("./models/User");
const { res500 } = require("./plugins/controllersHelperFunctions");
const Category = require("./models/Category");
const Election = require("./models/Election");
const authentication = {
// secret for generating jwt token
secretKey: 'kyQa8pFI5BJnj7LCVPlSfoATTSZuS5DMSjgBPxQo2zkcdKnxKCPzWs1DEBgMfnXFsjgT0YWgqn8HgLLcmdIgSR6fSQpy6vchmY3kUSD564J',
secretKey:
"kyQa8pFI5BJnj7LCVPlSfoATTSZuS5DMSjgBPxQo2zkcdKnxKCPzWs1DEBgMfnXFsjgT0YWgqn8HgLLcmdIgSR6fSQpy6vchmY3kUSD564J",
// check if just logged in (admin-or-user) (middleware)
isLoggedIn: async function (req, res, next) {
try {
const token = req.headers.authorization?.replace(/^Bearer\s/, '');
const token = req.headers.authorization?.replace(/^Bearer\s/, "");
if (token) {
// check if token is not destroyed
var user = await User.findOne({token: token});
var user = await User.findOne({ token: token });
if (!user) {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
if (!user.registration_done) {
return res500(res, 'user is disable please contact to support');
return res500(res, "user is disable please contact to support");
}
//verifies secret and checks if the token is expired
try {
var checkToken = await jwt.verify(user.token.replace(/^Bearer\s/, ''), authentication.secretKey);
var checkToken = await jwt.verify(
user.token.replace(/^Bearer\s/, ""),
authentication.secretKey
);
if (!checkToken) {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
} catch (error) {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
req.user = {
@@ -40,12 +44,12 @@ const authentication = {
portals: user.portals,
permissions: user.permissions,
specialPermissions: user.specialPermissions,
private: user.private
private: user.private,
};
return next();
} else {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
} catch (error) {
return res500(res, error.message);
@@ -59,16 +63,16 @@ const authentication = {
if (req.user) {
const scope = req.user.scope;
if (!scope.includes('admin')) {
return res.status(401).json({message: 'unauthorized'});
if (!scope.includes("admin")) {
return res.status(401).json({ message: "unauthorized" });
}
return next()
return next();
} else {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
} catch (error) {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
},
// check if user has permission (middleware)
@@ -76,18 +80,18 @@ const authentication = {
return (req, res, next) => {
if (req.user && req.user.permissions) {
const permissions = req.user.permissions;
if (permissions.includes('superAdmin')) {
if (permissions.includes("superAdmin")) {
return next();
}
if (!permissions.includes(permission)) {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
} else {
return next();
}
} else {
return res.status(401).json({message: 'unauthorized'});
}
return res.status(401).json({ message: "unauthorized" });
}
};
},
// hasSpecPermission: () => {
// return async (req, res, next) => {
@@ -116,32 +120,35 @@ const authentication = {
// }
// }
// },
hasSubPermission: () => {
return (req, res, next, value) => {
if (req.user && req.user.permissions) {
var permissions = req.user.permissions;
if (permissions.includes('superAdmin')) {
if (permissions.includes("superAdmin")) {
return next();
}
if (!permissions.some(item => new RegExp(value, 'i').test(item))) {
return res.status(401).json({message: 'unauthorized'});
if (!permissions.some((item) => new RegExp(value, "i").test(item))) {
return res.status(401).json({ message: "unauthorized" });
} else {
return next();
}
} else {
return res.status(401).json({message: 'unauthorized'});
}
return res.status(401).json({ message: "unauthorized" });
}
};
},
isVoter: async function (req, res, next) {
try {
const token = req.headers.authorization?.replace(/^Bearer\s/, '');
const token = req.headers.authorization?.replace(/^Bearer\s/, "");
if (token) {
// check if token is not destroyed
const user = await Election.findOne({'voters': {$elemMatch: {_id: token}}});
const user = await Election.findOne({
voters: { $elemMatch: { _id: token } },
});
if (!user) {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
const voter = user.voters.id(token);
@@ -150,17 +157,17 @@ const authentication = {
_id: voter._id,
username: voter.username,
password: voter.password,
voted: voter.voted
voted: voter.voted,
};
return next();
} else {
return res.status(401).json({message: 'unauthorized'});
return res.status(401).json({ message: "unauthorized" });
}
} catch (error) {
return res500(res, error.message);
}
},
}
};
module.exports = authentication
module.exports = authentication;
+1 -1
View File
@@ -34,7 +34,7 @@ module.exports.getAdminLoginLogs = [
try {
const {
page = 1,
limit = 1000,
limit = 10,
sort = "desc",
fromDate,
toDate,
+50 -48
View File
@@ -1,77 +1,79 @@
const mongoose = require('mongoose');
const mongoose = require("mongoose");
function autoPopulateSubs(next) {
this.populate({
path: 'childs',
select: 'title childs navIndex url modelType treeCat parent defaultPageType',
options:{
sort : 'navIndex'
}
path: "childs",
select:
"title childs navIndex url modelType treeCat parent defaultPageType",
options: {
sort: "navIndex",
},
// sort: {navIndex: -1},
});
next();
}
function file(file) {
return '/uploads/files/terms/' + file
return "/uploads/files/terms/" + file;
}
function image(img) {
if (img) return '/uploads/images/category/' + img
else return '/img/no-cover.jpg'
if (img) return "/uploads/images/category/" + img;
else return "/img/no-cover.jpg";
}
const CategoryTermsFile = mongoose.Schema({
file: {type: String, get: file},
title: String
})
file: { type: String, get: file },
title: String,
});
const CategorySchema = mongoose.Schema({
title: String,
parent: {type: mongoose.Schema.Types.ObjectId, ref: 'Category', default: null},
childs: [{type: mongoose.Schema.Types.ObjectId, ref: 'Category'}],
treeCat: [{type: mongoose.Schema.Types.ObjectId, ref: 'Category'}],
rootParent: {type: mongoose.Schema.Types.ObjectId, ref: 'Category'},
priority: {type: Number, default: 0},
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
default: null,
},
childs: [{ type: mongoose.Schema.Types.ObjectId, ref: "Category" }],
treeCat: [{ type: mongoose.Schema.Types.ObjectId, ref: "Category" }],
rootParent: { type: mongoose.Schema.Types.ObjectId, ref: "Category" },
priority: { type: Number, default: 0 },
showInMenu: Boolean,
navIndex: {type: Number, default: null},
news: {type: Boolean, default: true},
child: {type: Boolean, default: true},
special: {type: Boolean, default: false},
allowComment: {type: Boolean, default: false},
level: {type: Number, default: 1},
siteMap: {type: Boolean, default: true},
navIndex: { type: Number, default: null },
news: { type: Boolean, default: true },
child: { type: Boolean, default: true },
special: { type: Boolean, default: false },
allowComment: { type: Boolean, default: false },
level: { type: Number, default: 1 },
siteMap: { type: Boolean, default: true },
modelType: String,
_creator: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
_updatedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
haveNews: {type: Boolean, default: false},
_creator: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
_updatedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
haveNews: { type: Boolean, default: false },
///// for client
hasNewsTab: {type: Boolean, default: true},
hasContentTab: {type: Boolean, default: true},
hasMediaTab: {type: Boolean, default: true},
hasSubMenusTab: {type: Boolean, default: true},
hasTermsTab: {type: Boolean, default: true},
hasNotificationsTab: {type: Boolean, default: true},
hasSpecNewsTab: {type: Boolean, default: true},
hasNazarTab: {type: Boolean, default: true},
hasNewsFileTab: {type: Boolean, default: true},
defaultPageType: {type: String, default: 'news'},
hasNewsTab: { type: Boolean, default: true },
hasContentTab: { type: Boolean, default: true },
hasMediaTab: { type: Boolean, default: true },
hasSubMenusTab: { type: Boolean, default: true },
hasTermsTab: { type: Boolean, default: true },
hasNotificationsTab: { type: Boolean, default: true },
hasSpecNewsTab: { type: Boolean, default: true },
hasNazarTab: { type: Boolean, default: true },
hasNewsFileTab: { type: Boolean, default: true },
defaultPageType: { type: String, default: "news" },
/** page */
showInFooter: {type: Number, enum: [0, 1, 2, 3], default: 0},
url: {type: String, default: null},
showInFooter: { type: Number, enum: [0, 1, 2, 3], default: 0 },
url: { type: String, default: null },
pageContent: String,
terms: [CategoryTermsFile],
hasManagerInfo: {type: Boolean, default: true},
managerCover: {type: String, get: image},
hasManagerInfo: { type: Boolean, default: true },
managerCover: { type: String, get: image },
managerName: String,
managerDescription: String
managerDescription: String,
});
CategorySchema.index({parent: 1, childs: 1});
CategorySchema.index({ parent: 1, childs: 1 });
CategorySchema
.pre('findOne', autoPopulateSubs)
.pre('find', autoPopulateSubs);
CategorySchema.pre("findOne", autoPopulateSubs).pre("find", autoPopulateSubs);
module.exports = mongoose.model('Category', CategorySchema);
module.exports = mongoose.model("Category", CategorySchema);
+1 -1
View File
@@ -28,7 +28,6 @@ module.exports.sms = async (phoneNumber, message) => {
SendDateTime: "",
CanContinueInCaseOfError: "false",
};
const response = await axios.post(
`http://RestfulSms.com/api/MessageSend`,
data,
@@ -39,6 +38,7 @@ module.exports.sms = async (phoneNumber, message) => {
},
}
);
return response.data;
} catch (e) {
console.log(e);