Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Member role add (fixes: #405) #406

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
52 changes: 50 additions & 2 deletions api/src/controllers/communityUserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ const getAllMembers = async (req, res) => {
const data = await db.CommunityUser.findAll(
{
where: { communityId: req.params.id, active: true },
attributes: ['userId'],
attributes: ['userId', 'role'],
include: [{
model: db.User,
attributes: ['firstName']
Expand All @@ -101,6 +101,54 @@ const getAllMembers = async (req, res) => {
}
}

// @desc Get the community-users
// @route GET /api/community-users/community/:id/details
// @access Public

const getAllMemberDetails = async (req, res) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like getAllMemberDetails, getAllMembers, getCommunityUsers can be single function

try {
const data = await db.CommunityUser.findAll(
{
where: { communityId: req.params.id, active: true },
attributes: ['id', 'userId', 'role'],
include: [{
model: db.User,
attributes: ['firstName', 'lastName', 'email', 'phone', 'dateOfBirth']
}],
required: true
}
)

// flattening the array to show only one object
const newArray = data.map(item => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it could just be nested to after findall

const { userId, role, id } = item.dataValues
const { ...rest } = item.user
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this line is not required can be used directly below in place of rest.datavalues

return { id, userId, role, ...rest.dataValues }
}
)

res.json({
results: newArray
})
} catch (error) {
res.status(400).json({ error })
}
}

// @desc Update the community users
// @route PUT /api/community-users/:memberId/community/:id/
// @access Public

const updateMemberRole = async (req, res) => {
try {
const { role } = req.body
await db.CommunityUser.update({ role }, { where: { id: parseInt(req.params.memberId) } })
res.json({ message: 'Successfully role updated' })
} catch (error) {
res.status(400).json({ error })
}
}

// @desc Search Name
// @route POST /api/news/community/:id/search
// @access Private
Expand Down Expand Up @@ -129,4 +177,4 @@ const searchMemberName = (req, res) => {
.catch(err => res.json({ error: err }).status(400))
}

module.exports = { getCommunityUsers, followCommunity, getAllMembers, searchMemberName }
module.exports = { getCommunityUsers, followCommunity, getAllMembers, searchMemberName, getAllMemberDetails, updateMemberRole }
30 changes: 23 additions & 7 deletions api/src/middleware/permission.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,31 @@
const permit = (role) => {
return (req, res, next) => {
if (checkRole(req, role)) {
const db = require('../models')

function checkRole (dbRole, roles) {
return roles.some(el => el === dbRole)
}

// async function checkMemberRole(req, roles) {
// const member = await db.CommunityUser.findOne({ where: { userId: req.user.id, communityId: req.params.id }, attributes: ['role'] })
// console.log(member.dataValues.role);
// console.log(checkRole(member.dataValues.role, roles))
// if (checkRole(member.dataValues.role, roles)) {
// return true;
// } else {
// return false;
// }
// }

const permit = (roles) => {
return async (req, res, next) => {
// getting member role
const member = await db.CommunityUser.findOne({ where: { userId: req.user.id, communityId: req.params.id }, attributes: ['role'] })

if (checkRole(member.dataValues.role, roles) || checkRole(req.user.role, roles)) {
next()
} else {
res.json({ error: 'Sorry, You don\'t have permission' })
}
}
}

function checkRole (req, role) {
return role.some(el => el === req.user.role)
}

module.exports = permit
14 changes: 14 additions & 0 deletions api/src/migrations/20210728085949-alter_community_user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict'

module.exports = {
up: async (queryInterface, Sequelize) => {
queryInterface.addColumn('communities_users', 'role', {
type: Sequelize.STRING,
defaultValue: 'member'
})
},

down: async (queryInterface, Sequelize) => {
queryInterface.removeColumn('communities_users', 'role')
}
}
4 changes: 4 additions & 0 deletions api/src/models/communityUserModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ module.exports = (sequelize, DataTypes) => {
active: {
type: DataTypes.INTEGER,
defaultValue: true
},
role: {
type: DataTypes.STRING,
defaultValue: 'member'
}
},
{ timestamps: true }
Expand Down
8 changes: 5 additions & 3 deletions api/src/routes/communityUserRouter.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const { getCommunityUsers, followCommunity, getAllMembers, searchMemberName } = require('../controllers/communityUserController')
const { getCommunityUsers, followCommunity, getAllMembers, searchMemberName, getAllMemberDetails, updateMemberRole } = require('../controllers/communityUserController')
const protect = require('../middleware/authMiddleware')
const permit = require('../middleware/permission')
const router = require('express').Router()

router.get('/', getCommunityUsers)
router.post('/follow', protect, followCommunity)
router.get('/community/:id', getAllMembers)
router.get('/community/:id', protect, permit(['manager']), getAllMembers)
router.get('/community/:id/search', searchMemberName)
router.put('/:memberId/community/:id/', protect, permit(['manager']), updateMemberRole)
// router.put('/:id', updateCommunityUsers);

router.get('/community/:id/details', protect, permit(['manager']), getAllMemberDetails)
module.exports = router
2 changes: 2 additions & 0 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import AddTest from './screens/addTest/AddTest'
import LogoutUser from './screens/logoutUser/LogoutUser'
import Category from './screens/category/Category'
import PageNotFound from './screens/pageNotFound/PageNotFound'
import CommunityMemberAdmin from './screens/admin/CommunityMemberAdmin'

function App () {
return (
Expand All @@ -78,6 +79,7 @@ function App () {
<PrivateRoute component={CommunityNewsViewPage} path='/community-page-news-view' exact />
<PrivateRoute component={AllCommunitiesCard} path='/community-switching' exact />
<PrivateRoute component={CommunityMembers} path='/community-members/:id' exact />
<PrivateRoute component={CommunityMemberAdmin} path='/admin/community-members' exact />
<PrivateRoute component={CommunityMembersProfile} path='/community-members-profile/:id' exact />
<PrivateRoute component={CommunityGroup} path='/community-group/:id' exact />
<PrivateRoute component={CommunityGroup} path='/your-community-group/:id' exact />
Expand Down
61 changes: 61 additions & 0 deletions src/screens/admin/CommunityMemberAdmin.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import Table from '../../components/table/Table'
import DashboardLayout from '../../layout/dashboardLayout/DashboardLayout'
import { getApi, putApi } from '../../utils/apiFunc'
import { getCommunity } from '../../utils/getCommunity'
import './CommunityMemberAdmin.scss'

const ComMemberAdmin = () => {
const [data, setData] = useState([])
const [success, setSuccess] = useState(null)

const dispatch = useDispatch()

// fetching current community
const currentCommunity = getCommunity()

useEffect(() => {
getMemberDetails()
}, [success])

const getMemberDetails = async () => {
const { data } = await getApi(
dispatch,
`${process.env.REACT_APP_API_BASE_URL}/api/communities-users/community/${currentCommunity.id}/details`
)
setData(data.results)
}

const allowAccess = async (id) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be able to switch between roles not always make manager

const { data } = await putApi(
dispatch,
`${process.env.REACT_APP_API_BASE_URL}/api/communities-users/${id}/community/${currentCommunity.id}`,
{ role: 'manager' }
)
setSuccess(data)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is also not reloading table so have to manually do refresh

}

return (
<DashboardLayout title={currentCommunity.name}>
{data.length && <Table
addSymbolNumber
data={{
tblData: data,
tblProperty: ['firstName', 'lastName', 'email', 'phone', 'dateOfBirth', 'role', 'options'],
tblHeader: ['First Name', 'Last Name', 'Email', 'Phone', 'Date of Birth', 'Role', 'options']
}}
options={
[
{
img: '/img/edit-icon.svg',
action: allowAccess
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be list of roles for now lets take [manager, member, coach] and should show list which is not current role of member as dropdown

}
]
}
/>}
</DashboardLayout>
)
}

export default ComMemberAdmin
38 changes: 38 additions & 0 deletions src/screens/admin/CommunityMemberAdmin.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
.com-member-container {
width: 100%;
display: flex;
flex-direction: column;
color: #fff;
}

.com-member-header {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
background: var(--primary-color);
padding: 12px;
text-align: center;

p {
flex: 1;
}
}

.com-member-item {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px;
text-align: center;
background: var(--dropdowns);

p {
flex: 1;
}
}

.access-btn {
cursor: pointer;
}
4 changes: 4 additions & 0 deletions src/utils/apiFunc.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ export const getApi = async (dispatch, url, config) => {
export const postApi = async (dispatch, url, data, config) => {
return await axios.post(url, data, configFunc(config))
}

export const putApi = async (dispatch, url, data, config) => {
return await axios.put(url, data, configFunc(config))
}
5 changes: 5 additions & 0 deletions src/utils/getCommunity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const getCommunity = () => {
return localStorage.getItem('currentCommunity')
? JSON.parse(localStorage.getItem('currentCommunity'))
: null
}