Merge branch 'feature/authorization' of Cadoles/daddy into develop

This commit is contained in:
wpetit 2020-09-08 10:18:06 +02:00 committed by Gitea
commit 12151ff613
40 changed files with 1056 additions and 186 deletions

View File

@ -1,4 +1,4 @@
import React, { FunctionComponent, useState } from 'react';
import React, { FunctionComponent, useState, useEffect } from 'react';
import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
import { HomePage } from './HomePage/HomePage';
import { ProfilePage } from './ProfilePage/ProfilePage';
@ -6,44 +6,76 @@ import { WorkgroupPage } from './WorkgroupPage/WorkgroupPage';
import { DecisionSupportFilePage } from './DecisionSupportFilePage/DecisionSupportFilePage';
import { DashboardPage } from './DashboardPage/DashboardPage';
import { useUserProfile } from '../gql/queries/profile';
import { LoggedInContext } from '../hooks/useLoggedIn';
import { LoggedInContext, getSavedLoggedIn, saveLoggedIn } from '../hooks/useLoggedIn';
import { PrivateRoute } from './PrivateRoute';
import { useKonamiCode } from '../hooks/useKonamiCode';
import { Modal } from './Modal';
import { createClient } from '../util/apollo';
import { ApolloProvider } from '@apollo/client';
import { LogoutPage } from './LogoutPage';
export interface AppProps {
}
export const App: FunctionComponent<AppProps> = () => {
const { user } = useUserProfile();
const [ loggedIn, setLoggedIn ] = useState(getSavedLoggedIn());
const client = createClient((loggedIn) => {
setLoggedIn(loggedIn);
});
useEffect(() => {
saveLoggedIn(loggedIn);
}, [loggedIn]);
const [ showBoneyM, setShowBoneyM ] = useState(false);
useKonamiCode(() => setShowBoneyM(true));
return (
<LoggedInContext.Provider value={user.id !== ''}>
<BrowserRouter>
<Switch>
<Route path="/" exact component={HomePage} />
<PrivateRoute path="/profile" exact component={ProfilePage} />
<PrivateRoute path="/workgroups/:id" exact component={WorkgroupPage} />
<PrivateRoute path="/decisions/:id" exact component={DecisionSupportFilePage} />
<PrivateRoute path="/dashboard" exact component={DashboardPage} />
<Route component={() => <Redirect to="/" />} />
</Switch>
</BrowserRouter>
{
showBoneyM ?
<Modal active={true} showCloseButton={true} onClose={() => setShowBoneyM(false)}>
<iframe width={560} height={315}
frameBorder={0}
allowFullScreen={true}
src="https://www.youtube.com/embed/uVzT5QEEQ2c?autoplay=1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture">
</iframe>
</Modal> :
null
}
</LoggedInContext.Provider>
<ApolloProvider client={client}>
<LoggedInContext.Provider value={loggedIn}>
<UserSessionCheck setLoggedIn={setLoggedIn} />
<BrowserRouter>
<Switch>
<Route path="/" exact component={HomePage} />
<PrivateRoute path="/profile" exact component={ProfilePage} />
<PrivateRoute path="/workgroups/:id" exact component={WorkgroupPage} />
<PrivateRoute path="/decisions/:id" exact component={DecisionSupportFilePage} />
<PrivateRoute path="/dashboard" exact component={DashboardPage} />
<PrivateRoute path="/logout" exact component={LogoutPage} />
<Route component={() => <Redirect to="/" />} />
</Switch>
</BrowserRouter>
{
showBoneyM ?
<Modal active={true} showCloseButton={true} onClose={() => setShowBoneyM(false)}>
<iframe width={560} height={315}
frameBorder={0}
allowFullScreen={true}
src="https://www.youtube.com/embed/uVzT5QEEQ2c?autoplay=1" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture">
</iframe>
</Modal> :
null
}
</LoggedInContext.Provider>
</ApolloProvider>
);
}
}
interface UserSessionCheckProps {
setLoggedIn: (boolean) => void
}
const UserSessionCheck: FunctionComponent<UserSessionCheckProps> = ({ setLoggedIn }) => {
const { user, loading } = useUserProfile();
useEffect(() => {
if (loading) return;
setLoggedIn(user.id !== '');
}, [user]);
return null;
};

View File

@ -26,8 +26,7 @@ export function DecisionSupportFilePanel() {
itemFilter: (item: Item) => (item as DecisionSupportFile).status === DecisionSupportFileStatus.Closed
},
];
return (
<ItemPanel
className='is-link'

View File

@ -11,8 +11,6 @@ export interface TabDefinition {
label: string
itemFilter?: (item: Item) => boolean
}
export interface ItemPanelProps {
className?: string
itemIconClassName?: string
@ -30,9 +28,12 @@ export const ItemPanel: FunctionComponent<ItemPanelProps> = (props) => {
const {
title, className, newItemUrl,
itemKey, itemLabel,
itemIconClassName, itemUrl
itemIconClassName, itemUrl,
} = props;
const items = props.items || [];
const tabs = props.tabs || [];
const [ state, setState ] = useState({ selectedTab: 0, filteredItems: [] });
const filterItemsForTab = (tab: TabDefinition, items: Item[]) => {
@ -42,7 +43,6 @@ export const ItemPanel: FunctionComponent<ItemPanelProps> = (props) => {
const selectTab = (tabIndex: number) => {
setState(state => {
const { tabs, items } = props;
const newTab = Array.isArray(tabs) && tabs.length > 0 ? tabs[tabIndex] : null;
return {
...state,
@ -61,7 +61,7 @@ export const ItemPanel: FunctionComponent<ItemPanelProps> = (props) => {
filteredItems: filterItemsForTab(newTab, items),
}
});
}, [props.items, props.tabs]);
}, [items, tabs]);
const itemElements = state.filteredItems.map((item: Item, i: number) => {
return (
@ -74,8 +74,6 @@ export const ItemPanel: FunctionComponent<ItemPanelProps> = (props) => {
);
});
const tabs = props.tabs || [];
return (
<nav className={`panel ${className}`}>
<div className="level is-mobile panel-heading mb-0">

View File

@ -1,10 +1,7 @@
import React, { useEffect, useState } from 'react';
import React, { } from 'react';
import { Workgroup, inWorkgroup } from '../../types/workgroup';
import { User } from '../../types/user';
import { Link } from 'react-router-dom';
import { useWorkgroupsQuery, useWorkgroups } from '../../gql/queries/workgroups';
import { useUserProfileQuery, useUserProfile } from '../../gql/queries/profile';
import { WithLoader } from '../WithLoader';
import { useWorkgroups } from '../../gql/queries/workgroups';
import { useUserProfile } from '../../gql/queries/profile';
import { ItemPanel, Item } from './ItemPanel';
export function WorkgroupsPanel() {

View File

@ -3,14 +3,15 @@ import { Page } from '../Page';
import { WelcomeContent } from './WelcomeContent';
import { useUserProfile } from '../../gql/queries/profile';
import { useHistory } from 'react-router';
import { useLoggedIn } from '../../hooks/useLoggedIn';
export function HomePage() {
const { user } = useUserProfile();
const loggedIn = useLoggedIn();
const history = useHistory();
useEffect(() => {
if (user.id !== '') history.push('/dashboard');
}, [user.id])
if (loggedIn) history.push('/dashboard');
}, [loggedIn])
return (
<Page title="Accueil">

View File

@ -0,0 +1,15 @@
import React, { FunctionComponent, useEffect } from "react";
import { saveLoggedIn } from "../hooks/useLoggedIn";
import { Config } from "../config";
export interface LogoutPageProps {
}
export const LogoutPage: FunctionComponent<LogoutPageProps> = () => {
useEffect(() => {
saveLoggedIn(false);
window.location.replace(Config.logoutURL);
}, []);
return null;
};

View File

@ -44,11 +44,11 @@ export function Navbar() {
</span>
<span>Mon profil</span>
</Link>
<a className="button is-warning" href={Config.logoutURL}>
<Link className="button is-warning" to="/logout">
<span className="icon">
<i className="fas fa-sign-out-alt"></i>
</span>
</a>
</Link>
</Fragment> :
<a className="button is-primary" href={Config.loginURL}>
<span className="icon">

View File

@ -1,12 +1,13 @@
import React, { useState, ChangeEvent, useEffect } from 'react';
import { Workgroup } from '../../types/workgroup';
import { useIsAuthorized } from '../../gql/queries/authorization';
export interface InfoFormProps {
workgroup: Workgroup
onChange?: (workgroup: Workgroup) => void
}
export function InfoForm({ workgroup, onChange }: InfoFormProps) {
export function InfoForm({ workgroup, onChange }: InfoFormProps) {
const [ state, setState ] = useState({
changed: false,
workgroup: {
@ -17,6 +18,15 @@ export function InfoForm({ workgroup, onChange }: InfoFormProps) {
}
});
const { isAuthorized } = useIsAuthorized({
variables: {
action: 'update',
object: {
workgroupId: state.workgroup.id,
}
}
}, state.workgroup.id === '' ? true : false);
useEffect(() => {
setState({
changed: false,
@ -60,7 +70,8 @@ export function InfoForm({ workgroup, onChange }: InfoFormProps) {
<div className="field">
<label className="label">Nom du groupe</label>
<div className="control">
<input type="text" className="input" value={state.workgroup.name}
<input type="text" className="input" value={state.workgroup.name}
disabled={!isAuthorized}
onChange={onWorkgroupAttrChange.bind(null, "name")} />
</div>
</div>
@ -85,7 +96,7 @@ export function InfoForm({ workgroup, onChange }: InfoFormProps) {
null
}
<div className="buttons is-right">
<button disabled={!state.changed}
<button disabled={!state.changed || !isAuthorized}
className="button is-success" onClick={onSaveClick}>
<span>Enregistrer</span>
<span className="icon"><i className="fa fa-save"></i></span>

View File

@ -2,8 +2,8 @@ import React, { useEffect, useState, Fragment } from 'react';
import { Page } from '../Page';
import { WithLoader } from '../WithLoader';
import { useParams } from 'react-router';
import { useWorkgroupsQuery } from '../../gql/queries/workgroups';
import { useUserProfileQuery } from '../../gql/queries/profile';
import { useWorkgroupsQuery, useWorkgroups } from '../../gql/queries/workgroups';
import { useUserProfileQuery, useUserProfile } from '../../gql/queries/profile';
import { MembersPanel } from './MembersPanel';
import { User } from '../../types/user';
import { InfoPanel } from './InfoPanel';
@ -12,17 +12,19 @@ import { useJoinWorkgroupMutation, useLeaveWorkgroupMutation, useCloseWorkgroupM
export function WorkgroupPage() {
const { id } = useParams();
const workgroupsQuery = useWorkgroupsQuery({
const { workgroups } = useWorkgroups({
variables:{
filter: {
ids: [id],
}
}
});
const userProfileQuery = useUserProfileQuery();
const [ joinWorkgroup, joinWorkgroupMutation ] = useJoinWorkgroupMutation();
const [ leaveWorkgroup, leaveWorkgroupMutation ] = useLeaveWorkgroupMutation();
const [ closeWorkgroup, closeWorkgroupMutation ] = useCloseWorkgroupMutation();
const { user } = useUserProfile();
const [ joinWorkgroup ] = useJoinWorkgroupMutation();
const [ leaveWorkgroup ] = useLeaveWorkgroupMutation();
const [ closeWorkgroup ] = useCloseWorkgroupMutation();
const [ state, setState ] = useState({
userProfileId: '',
workgroup: {
@ -35,14 +37,12 @@ export function WorkgroupPage() {
});
useEffect(() => {
if (!workgroupsQuery.data) return;
setState(state => ({...state, workgroup:{ ...state.workgroup, ...workgroupsQuery.data.workgroups[0]}}));
}, [workgroupsQuery.data]);
setState(state => ({...state, workgroup:{ ...state.workgroup, ...workgroups[0]}}));
}, [workgroups]);
useEffect(() => {
if (!userProfileQuery.data) return;
setState(state => ({...state, userProfileId: userProfileQuery.data.userProfile.id }));
}, [userProfileQuery.data]);
setState(state => ({...state, userProfileId: user.id }));
}, [user]);
const onJoinWorkgroupClick = () => {
joinWorkgroup({
@ -54,6 +54,18 @@ export function WorkgroupPage() {
const onLeaveWorkgroupClick = () => {
leaveWorkgroup({
update: (cache, result) => {
cache.modify({
id: cache.identify(result.data.leaveWorkgroup),
fields: {
members(existingMembers, { readField }) {
return existingMembers.filter(
user => state.userProfileId !== readField('id', user)
);
},
},
});
},
variables: {
workgroupId: state.workgroup.id,
}
@ -121,16 +133,14 @@ export function WorkgroupPage() {
</div>
</div>
</div>
<WithLoader loading={[workgroupsQuery.loading, userProfileQuery.loading, joinWorkgroupMutation.loading, leaveWorkgroupMutation.loading]}>
<div className="columns">
<div className="column">
<InfoPanel workgroup={state.workgroup as Workgroup} />
</div>
<div className="column">
<MembersPanel users={state.workgroup.members as User[]} />
</div>
<div className="columns">
<div className="column">
<InfoPanel workgroup={state.workgroup as Workgroup} />
</div>
</WithLoader>
<div className="column">
<MembersPanel users={state.workgroup.members as User[]} />
</div>
</div>
</section>
</div>
</Page>

View File

@ -1,56 +0,0 @@
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { Config } from '../config';
import { WebSocketLink } from "@apollo/client/link/ws";
import { RetryLink } from "@apollo/client/link/retry";
import { SubscriptionClient } from "subscriptions-transport-ws";
import { User } from '../types/user';
const subscriptionClient = new SubscriptionClient(Config.subscriptionEndpoint, {
reconnect: true,
});
const link = new RetryLink({attempts: {max: 2}}).split(
(operation) => operation.operationName === 'subscription',
new WebSocketLink(subscriptionClient),
new HttpLink({ uri: Config.graphQLEndpoint, credentials: 'include' })
);
const cache = new InMemoryCache({
typePolicies: {
Workgroup: {
fields: {
members: {
merge: mergeArrayByField<User>("id"),
}
}
}
}
});
export const client = new ApolloClient<any>({
cache: cache,
link: link,
});
function mergeArrayByField<T>(fieldName: string) {
return (existing: T[] = [], incoming: T[], { readField, mergeObjects }) => {
const merged: any[] = existing ? existing.slice(0) : [];
const objectFieldToIndex: Record<string, number> = Object.create(null);
if (existing) {
existing.forEach((obj, index) => {
objectFieldToIndex[readField(fieldName, obj)] = index;
});
}
incoming.forEach(obj => {
const field = readField(fieldName, obj);
const index = objectFieldToIndex[field];
if (typeof index === "number") {
merged[index] = mergeObjects(merged[index], obj);
} else {
objectFieldToIndex[name] = merged.length;
merged.push(obj);
}
});
return merged;
}
}

View File

@ -9,7 +9,16 @@ mutation createDecisionSupportFile($changes: DecisionSupportFileChanges!) {
status,
sections,
createdAt,
updatedAt
updatedAt,
workgroup {
id,
name,
members {
id,
email,
name
}
},
}
}`;
@ -27,7 +36,16 @@ mutation updateDecisionSupportFile($id: ID!, $changes: DecisionSupportFileChange
status,
sections,
createdAt,
updatedAt
updatedAt,
workgroup {
id,
name,
members {
id,
email,
name
}
},
}
}`;

View File

@ -1,5 +1,6 @@
import { gql, useQuery, useMutation } from '@apollo/client';
import { gql, useQuery, useMutation, FetchResult } from '@apollo/client';
import { QUERY_WORKGROUP } from '../queries/workgroups';
import { QUERY_IS_AUTHORIZED } from '../queries/authorization';
export const MUTATION_UPDATE_WORKGROUP = gql`
mutation updateWorkgroup($workgroupId: ID!, $changes: WorkgroupChanges!) {
@ -57,7 +58,19 @@ mutation joinWorkgroup($workgroupId: ID!) {
}`;
export function useJoinWorkgroupMutation() {
return useMutation(MUTATION_JOIN_WORKGROUP);
return useMutation(MUTATION_JOIN_WORKGROUP, {
refetchQueries: ({ data }: FetchResult) => {
return [{
query: QUERY_IS_AUTHORIZED,
variables: {
action: 'update',
object: {
workgroupId: data.joinWorkgroup.id,
}
}
}]
}
});
}
const MUTATION_LEAVE_WORKGROUP = gql`
@ -76,7 +89,27 @@ mutation leaveWorkgroup($workgroupId: ID!) {
}`;
export function useLeaveWorkgroupMutation() {
return useMutation(MUTATION_LEAVE_WORKGROUP);
return useMutation(MUTATION_LEAVE_WORKGROUP, {
refetchQueries: ({ data }: FetchResult) => {
return [{
query: QUERY_WORKGROUP,
variables: {
filter: {
ids: [data.leaveWorkgroup.id],
}
}
},
{
query: QUERY_IS_AUTHORIZED,
variables: {
action: 'update',
object: {
workgroupId: data.leaveWorkgroup.id,
}
}
}]
}
});
}
const MUTATION_CLOSE_WORKGROUP = gql`

View File

@ -0,0 +1,19 @@
import { gql, useQuery } from '@apollo/client';
import { useGraphQLData } from './helper';
export const QUERY_IS_AUTHORIZED = gql`
query isAuthorized($action: String!, $object: AuthorizationObject!) {
isAuthorized(action: $action, object: $object)
}
`;
export function useIsAuthorizedQuery(options = {}) {
return useQuery(QUERY_IS_AUTHORIZED, options);
}
export function useIsAuthorized(options = {}, defaultValue = false) {
const { data, loading, error } = useGraphQLData<boolean>(
QUERY_IS_AUTHORIZED, 'isAuthorized', defaultValue, options
);
return { isAuthorized: data, loading, error };
}

View File

@ -16,7 +16,9 @@ export const QUERY_DECISION_SUPPORT_FILES = gql`
id,
name,
members {
id
id,
email,
name
}
},
}

View File

@ -1,7 +1,23 @@
import React, { useState, useContext } from "react";
import React, { useContext, useEffect } from "react";
export const LoggedInContext = React.createContext(false);
const LOGGED_IN_KEY = 'loggedIn';
export const LoggedInContext = React.createContext(getSavedLoggedIn());
export const useLoggedIn = () => {
return useContext(LoggedInContext);
};
};
export function saveLoggedIn(loggedIn: boolean) {
console.log("saveLoggedIn", JSON.stringify(loggedIn))
window.sessionStorage.setItem(LOGGED_IN_KEY, JSON.stringify(loggedIn));
}
export function getSavedLoggedIn(): boolean {
try {
const loggedIn = JSON.parse(window.sessionStorage.getItem(LOGGED_IN_KEY));
return !!loggedIn;
} catch(err) {
return false;
}
}

View File

@ -2,7 +2,6 @@ import './sass/_all.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './components/App';
import { client } from './gql/client';
import '@fortawesome/fontawesome-free/js/fontawesome'
import '@fortawesome/fontawesome-free/js/solid'
@ -12,8 +11,6 @@ import './resources/favicon.png';
import { ApolloProvider } from '@apollo/client';
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
<App />,
document.getElementById('app')
);

74
client/src/util/apollo.ts Normal file
View File

@ -0,0 +1,74 @@
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';
import { Config } from '../config';
import { WebSocketLink } from "@apollo/client/link/ws";
import { RetryLink } from "@apollo/client/link/retry";
import { onError } from "@apollo/client/link/error";
import { SubscriptionClient } from "subscriptions-transport-ws";
import { User } from '../types/user';
export function createClient(setLoggedIn: (boolean) => void) {
const subscriptionClient = new SubscriptionClient(Config.subscriptionEndpoint, {
reconnect: true,
});
const errorLink = onError(({ operation }) => {
const { response } = operation.getContext();
if (response.status === 401) setLoggedIn(false);
});
const retryLink = new RetryLink({attempts: {max: 2}}).split(
(operation) => operation.operationName === 'subscription',
new WebSocketLink(subscriptionClient),
new HttpLink({
uri: Config.graphQLEndpoint,
credentials: 'include',
})
);
const cache = new InMemoryCache({
typePolicies: {
Workgroup: {
fields: {
members: {
merge: mergeArrayByField<User>("id"),
}
}
}
}
});
return new ApolloClient<any>({
cache: cache,
link: from([
errorLink,
retryLink
]),
});
}
export function mergeArrayByField<T>(fieldName: string) {
return (existing: T[] = [], incoming: T[], { readField, mergeObjects }) => {
const merged: any[] = existing ? existing.slice(0) : [];
const objectFieldToIndex: Record<string, number> = Object.create(null);
if (existing) {
existing.forEach((obj, index) => {
objectFieldToIndex[readField(fieldName, obj)] = index;
});
}
incoming.forEach(obj => {
const field = readField(fieldName, obj);
const index = objectFieldToIndex[field];
if (typeof index === "number") {
merged[index] = mergeObjects(merged[index], obj);
} else {
objectFieldToIndex[name] = merged.length;
merged.push(obj);
}
});
return merged;
}
}

View File

@ -5,6 +5,9 @@ import (
"net/http"
"time"
"forge.cadoles.com/Cadoles/daddy/internal/model"
"forge.cadoles.com/Cadoles/daddy/internal/voter"
"github.com/wader/gormstore"
"forge.cadoles.com/Cadoles/daddy/internal/auth"
@ -99,5 +102,11 @@ func getServiceContainer(ctx context.Context, conf *config.Config) (*service.Con
ctn.Provide(auth.ServiceName, auth.ServiceProvider(conf.Auth.Rules))
ctn.Provide(voter.ServiceName, voter.ServiceProvider(
voter.StrategyUnanimous,
model.NewDecisionSupportFileVoter(),
model.NewWorkgroupVoter(),
))
return ctn, nil
}

View File

@ -90,7 +90,7 @@ func NewDefault() *Config {
Address: ":8081",
CookieAuthenticationKey: "",
CookieEncryptionKey: "",
CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour
CookieMaxAge: int((time.Hour * 24).Seconds()), // 24 hours
TemplateDir: "template",
PublicDir: "public",
FrontendURL: "http://localhost:8080",

View File

@ -0,0 +1,59 @@
package graph
import (
"context"
"forge.cadoles.com/Cadoles/daddy/internal/model"
errs "github.com/pkg/errors"
)
func handleIsAuthorized(ctx context.Context, action string, obj model.AuthorizationObject) (bool, error) {
db, err := getDB(ctx)
if err != nil {
return false, errs.WithStack(err)
}
var object interface{}
switch {
case obj.WorkgroupID != nil:
repo := model.NewWorkgroupRepository(db)
workgroup, err := repo.Find(ctx, *obj.WorkgroupID)
if err != nil {
return false, errs.WithStack(err)
}
object = workgroup
case obj.DecisionSupportFileID != nil:
repo := model.NewDSFRepository(db)
dsf, err := repo.Find(ctx, *obj.DecisionSupportFileID)
if err != nil {
return false, errs.WithStack(err)
}
object = dsf
case obj.UserID != nil:
repo := model.NewUserRepository(db)
user, err := repo.Find(ctx, *obj.UserID)
if err != nil {
return false, errs.WithStack(err)
}
object = user
default:
return false, errs.WithStack(ErrInvalidInput)
}
authorized, err := isAuthorized(ctx, object, model.Action(action))
if err != nil {
return false, errs.WithStack(err)
}
return authorized, nil
}

View File

@ -12,6 +12,15 @@ import (
)
func handleCreateDecisionSupportFile(ctx context.Context, changes *model.DecisionSupportFileChanges) (*model.DecisionSupportFile, error) {
authorized, err := isAuthorized(ctx, &model.DecisionSupportFile{}, model.ActionCreate)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
ctn := container.Must(ctx)
db := orm.Must(ctn).DB()
@ -31,7 +40,21 @@ func handleUpdateDecisionSupportFile(ctx context.Context, id string, changes *mo
repo := model.NewDSFRepository(db)
dsf, err := repo.Update(ctx, id, changes)
dsf, err := repo.Find(ctx, id)
if err != nil {
return nil, errs.WithStack(err)
}
authorized, err := isAuthorized(ctx, dsf, model.ActionUpdate)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
dsf, err = repo.Update(ctx, id, changes)
if err != nil {
return nil, errs.WithStack(err)
}
@ -45,7 +68,25 @@ func handleDecisionSupportFiles(ctx context.Context, filter *model.DecisionSuppo
repo := model.NewDSFRepository(db)
return repo.Search(ctx, filter)
found, err := repo.Search(ctx, filter)
if err != nil {
return nil, errs.WithStack(err)
}
dsfs := make([]*model.DecisionSupportFile, 0)
for _, d := range found {
authorized, err := isAuthorized(ctx, d, model.ActionRead)
if err != nil {
return nil, errs.WithStack(err)
}
if authorized {
dsfs = append(dsfs, d)
}
}
return dsfs, nil
}
func handleSections(ctx context.Context, dsf *model.DecisionSupportFile) (map[string]interface{}, error) {

8
internal/graph/error.go Normal file
View File

@ -0,0 +1,8 @@
package graph
import "errors"
var (
ErrForbidden = errors.New("forbidden")
ErrInvalidInput = errors.New("invalid input")
)

View File

@ -3,6 +3,8 @@ package graph
import (
"context"
"forge.cadoles.com/Cadoles/daddy/internal/voter"
"forge.cadoles.com/Cadoles/daddy/internal/model"
"forge.cadoles.com/Cadoles/daddy/internal/orm"
"forge.cadoles.com/Cadoles/daddy/internal/session"
@ -46,3 +48,31 @@ func getSessionUser(ctx context.Context) (*model.User, *gorm.DB, error) {
return user, db, nil
}
func isAuthorized(ctx context.Context, obj interface{}, action interface{}) (bool, error) {
user, _, err := getSessionUser(ctx)
if err != nil {
return false, errors.WithStack(err)
}
ctn, err := container.From(ctx)
if err != nil {
return false, errors.WithStack(err)
}
voterSrv, err := voter.From(ctn)
if err != nil {
return false, errors.WithStack(err)
}
decision, err := voterSrv.Authorized(ctx, user, obj, action)
if err != nil {
return false, errors.WithStack(err)
}
if decision == voter.Allow {
return true, nil
}
return false, nil
}

View File

@ -38,8 +38,15 @@ input DecisionSupportFileFilter {
ids: [ID]
}
input AuthorizationObject {
workgroupId: ID
userId: ID
decisionSupportFileId: ID
}
type Query {
userProfile: User
workgroups(filter: WorkgroupsFilter): [Workgroup]!
decisionSupportFiles(filter: DecisionSupportFileFilter): [DecisionSupportFile]!
isAuthorized(action: String!, object: AuthorizationObject!): Boolean!
}

View File

@ -31,6 +31,10 @@ func (r *queryResolver) DecisionSupportFiles(ctx context.Context, filter *model1
return handleDecisionSupportFiles(ctx, filter)
}
func (r *queryResolver) IsAuthorized(ctx context.Context, action string, object model1.AuthorizationObject) (bool, error) {
return handleIsAuthorized(ctx, action, object)
}
func (r *userResolver) ID(ctx context.Context, obj *model1.User) (string, error) {
return strconv.FormatUint(uint64(obj.ID), 10), nil
}

View File

@ -2,10 +2,10 @@ package graph
import (
"context"
"strconv"
"forge.cadoles.com/Cadoles/daddy/internal/model"
"github.com/pkg/errors"
errs "github.com/pkg/errors"
)
func handleWorkgroups(ctx context.Context, filter *model.WorkgroupsFilter) ([]*model.Workgroup, error) {
@ -24,20 +24,28 @@ func handleWorkgroups(ctx context.Context, filter *model.WorkgroupsFilter) ([]*m
}
}
workgroups, err := repo.FindWorkgroups(ctx, criteria...)
found, err := repo.FindWorkgroups(ctx, criteria...)
if err != nil {
return nil, errors.WithStack(err)
}
workgroups := make([]*model.Workgroup, 0)
for _, wg := range found {
authorized, err := isAuthorized(ctx, wg, model.ActionRead)
if err != nil {
return nil, errs.WithStack(err)
}
if authorized {
workgroups = append(workgroups, wg)
}
}
return workgroups, nil
}
func handleJoinWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Workgroup, error) {
workgroupID, err := parseWorkgroupID(rawWorkgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
user, db, err := getSessionUser(ctx)
if err != nil {
return nil, errors.WithStack(err)
@ -45,7 +53,21 @@ func handleJoinWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Wor
repo := model.NewWorkgroupRepository(db)
workgroup, err := repo.AddUserToWorkgroup(ctx, user.ID, workgroupID)
workgroup, err := repo.Find(ctx, rawWorkgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
authorized, err := isAuthorized(ctx, workgroup, model.ActionJoin)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
workgroup, err = repo.AddUserToWorkgroup(ctx, user.ID, workgroup.ID)
if err != nil {
return nil, errors.WithStack(err)
}
@ -53,12 +75,7 @@ func handleJoinWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Wor
return workgroup, nil
}
func handleLeaveWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Workgroup, error) {
workgroupID, err := parseWorkgroupID(rawWorkgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
func handleLeaveWorkgroup(ctx context.Context, workgroupID string) (*model.Workgroup, error) {
user, db, err := getSessionUser(ctx)
if err != nil {
return nil, errors.WithStack(err)
@ -66,7 +83,21 @@ func handleLeaveWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Wo
repo := model.NewWorkgroupRepository(db)
workgroup, err := repo.RemoveUserFromWorkgroup(ctx, user.ID, workgroupID)
workgroup, err := repo.Find(ctx, workgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
authorized, err := isAuthorized(ctx, workgroup, model.ActionLeave)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
workgroup, err = repo.RemoveUserFromWorkgroup(ctx, user.ID, workgroup.ID)
if err != nil {
return nil, errors.WithStack(err)
}
@ -75,6 +106,15 @@ func handleLeaveWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Wo
}
func handleCreateWorkgroup(ctx context.Context, changes model.WorkgroupChanges) (*model.Workgroup, error) {
authorized, err := isAuthorized(ctx, &model.Workgroup{}, model.ActionCreate)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
db, err := getDB(ctx)
if err != nil {
return nil, errors.WithStack(err)
@ -90,12 +130,7 @@ func handleCreateWorkgroup(ctx context.Context, changes model.WorkgroupChanges)
return workgroup, nil
}
func handleCloseWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Workgroup, error) {
workgroupID, err := parseWorkgroupID(rawWorkgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
func handleCloseWorkgroup(ctx context.Context, workgroupID string) (*model.Workgroup, error) {
db, err := getDB(ctx)
if err != nil {
return nil, errors.WithStack(err)
@ -103,7 +138,21 @@ func handleCloseWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Wo
repo := model.NewWorkgroupRepository(db)
workgroup, err := repo.CloseWorkgroup(ctx, workgroupID)
workgroup, err := repo.Find(ctx, workgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
authorized, err := isAuthorized(ctx, workgroup, model.ActionClose)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
workgroup, err = repo.CloseWorkgroup(ctx, workgroup.ID)
if err != nil {
return nil, errors.WithStack(err)
}
@ -111,12 +160,7 @@ func handleCloseWorkgroup(ctx context.Context, rawWorkgroupID string) (*model.Wo
return workgroup, nil
}
func handleUpdateWorkgroup(ctx context.Context, rawWorkgroupID string, changes model.WorkgroupChanges) (*model.Workgroup, error) {
workgroupID, err := parseWorkgroupID(rawWorkgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
func handleUpdateWorkgroup(ctx context.Context, workgroupID string, changes model.WorkgroupChanges) (*model.Workgroup, error) {
db, err := getDB(ctx)
if err != nil {
return nil, errors.WithStack(err)
@ -124,19 +168,24 @@ func handleUpdateWorkgroup(ctx context.Context, rawWorkgroupID string, changes m
repo := model.NewWorkgroupRepository(db)
workgroup, err := repo.UpdateWorkgroup(ctx, workgroupID, changes)
workgroup, err := repo.Find(ctx, workgroupID)
if err != nil {
return nil, errors.WithStack(err)
}
authorized, err := isAuthorized(ctx, workgroup, model.ActionUpdate)
if err != nil {
return nil, errs.WithStack(err)
}
if !authorized {
return nil, errs.WithStack(ErrForbidden)
}
workgroup, err = repo.UpdateWorkgroup(ctx, workgroup.ID, changes)
if err != nil {
return nil, errors.WithStack(err)
}
return workgroup, nil
}
func parseWorkgroupID(workgroupID string) (uint, error) {
workgroupID64, err := strconv.ParseUint(workgroupID, 10, 32)
if err != nil {
return 0, errors.WithStack(err)
}
return uint(workgroupID64), nil
}

13
internal/model/action.go Normal file
View File

@ -0,0 +1,13 @@
package model
type Action string
const (
ActionCreate Action = "create"
ActionRead Action = "read"
ActionUpdate Action = "update"
ActionDelete Action = "delete"
ActionJoin Action = "join"
ActionLeave Action = "leave"
ActionClose Action = "close"
)

View File

@ -88,6 +88,17 @@ func (r *DSFRepository) updateFromChanges(dsf *DecisionSupportFile, changes *Dec
return nil
}
func (r *DSFRepository) Find(ctx context.Context, id string) (*DecisionSupportFile, error) {
dsf := &DecisionSupportFile{}
query := r.db.Model(dsf).Preload("Workgroup").Where("id = ?", id)
if err := query.First(&dsf).Error; err != nil {
return nil, errs.WithStack(err)
}
return dsf, nil
}
func (r *DSFRepository) Search(ctx context.Context, filter *DecisionSupportFileFilter) ([]*DecisionSupportFile, error) {
query := r.db.Model(&DecisionSupportFile{}).Preload("Workgroup")

View File

@ -0,0 +1,48 @@
package model
import (
"context"
"forge.cadoles.com/Cadoles/daddy/internal/voter"
)
type DecisionSupportFileVoter struct {
}
func (v *DecisionSupportFileVoter) Vote(ctx context.Context, subject interface{}, obj interface{}, act interface{}) (voter.Decision, error) {
user, ok := subject.(*User)
if !ok {
return voter.Abstain, nil
}
dsf, ok := obj.(*DecisionSupportFile)
if !ok {
return voter.Abstain, nil
}
action, ok := act.(Action)
if !ok {
return voter.Abstain, nil
}
switch action {
case ActionCreate:
return voter.Allow, nil
case ActionRead:
return voter.Allow, nil
case ActionUpdate:
if inWorkgroup(user, dsf.Workgroup) {
return voter.Allow, nil
}
return voter.Deny, nil
case ActionDelete:
return voter.Deny, nil
}
return voter.Abstain, nil
}
func NewDecisionSupportFileVoter() *DecisionSupportFileVoter {
return &DecisionSupportFileVoter{}
}

15
internal/model/helper.go Normal file
View File

@ -0,0 +1,15 @@
package model
func inWorkgroup(user *User, workgroup *Workgroup) bool {
if workgroup == nil {
return false
}
for _, w := range user.Workgroups {
if w.ID == workgroup.ID {
return true
}
}
return false
}

View File

@ -7,6 +7,7 @@ import (
"forge.cadoles.com/Cadoles/daddy/internal/orm"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
errs "github.com/pkg/errors"
)
type UserRepository struct {
@ -68,6 +69,17 @@ func (r *UserRepository) UpdateUserByEmail(ctx context.Context, email string, ch
return user, nil
}
func (r *UserRepository) Find(ctx context.Context, id string) (*User, error) {
user := &User{}
query := r.db.Model(user).Where("id = ?", id)
if err := query.First(&user).Error; err != nil {
return nil, errs.WithStack(err)
}
return user, nil
}
func NewUserRepository(db *gorm.DB) *UserRepository {
return &UserRepository{db}
}

View File

@ -6,6 +6,7 @@ import (
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
errs "github.com/pkg/errors"
)
type WorkgroupRepository struct {
@ -47,7 +48,7 @@ func (r *WorkgroupRepository) CreateWorkgroup(ctx context.Context, changes Workg
Name: changes.Name,
}
if err := r.db.Model(&Workgroup{}).Create(workgroup).Error; err != nil {
if err := r.db.Model(&Workgroup{}).Preload("Members").Create(workgroup).Error; err != nil {
return nil, errors.WithStack(err)
}
@ -135,6 +136,17 @@ func (r *WorkgroupRepository) RemoveUserFromWorkgroup(ctx context.Context, userI
return workgroup, nil
}
func (r *WorkgroupRepository) Find(ctx context.Context, id string) (*Workgroup, error) {
wg := &Workgroup{}
query := r.db.Model(wg).Preload("Members").Where("id = ?", id)
if err := query.First(&wg).Error; err != nil {
return nil, errs.WithStack(err)
}
return wg, nil
}
func NewWorkgroupRepository(db *gorm.DB) *WorkgroupRepository {
return &WorkgroupRepository{db}
}

View File

@ -0,0 +1,54 @@
package model
import (
"context"
"forge.cadoles.com/Cadoles/daddy/internal/voter"
)
type WorkgroupVoter struct {
}
func (v *WorkgroupVoter) Vote(ctx context.Context, subject interface{}, obj interface{}, act interface{}) (voter.Decision, error) {
user, ok := subject.(*User)
if !ok {
return voter.Abstain, nil
}
workgroup, ok := obj.(*Workgroup)
if !ok {
return voter.Abstain, nil
}
action, ok := act.(Action)
if !ok {
return voter.Abstain, nil
}
switch action {
case ActionCreate:
return voter.Allow, nil
case ActionRead:
return voter.Allow, nil
case ActionJoin:
return voter.Allow, nil
case ActionLeave:
fallthrough
case ActionUpdate:
fallthrough
case ActionClose:
if inWorkgroup(user, workgroup) {
return voter.Allow, nil
} else {
return voter.Deny, nil
}
case ActionDelete:
return voter.Deny, nil
}
return voter.Abstain, nil
}
func NewWorkgroupVoter() *WorkgroupVoter {
return &WorkgroupVoter{}
}

View File

@ -36,10 +36,12 @@ func Mount(r *chi.Mux, config *config.Config) error {
}).Handler)
r.Use(session.UserEmailMiddleware)
gqlConfig := generated.Config{
Resolvers: &graph.Resolver{},
}
gql := handler.New(
generated.NewExecutableSchema(generated.Config{
Resolvers: &graph.Resolver{},
}),
generated.NewExecutableSchema(gqlConfig),
)
gql.AddTransport(transport.POST{})

View File

@ -0,0 +1,22 @@
package voter
type Decision int
const (
Allow Decision = iota
Deny
Abstain
)
func AsString(d Decision) string {
switch d {
case Allow:
return "allow"
case Deny:
return "deny"
case Abstain:
return "abstain"
default:
return "unknown"
}
}

60
internal/voter/manager.go Normal file
View File

@ -0,0 +1,60 @@
package voter
import (
"context"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
type Voter interface {
Vote(ctx context.Context, subject interface{}, obj interface{}, action interface{}) (Decision, error)
}
type Strategy func(ctx context.Context, decisions []Decision) (Decision, error)
type Manager struct {
strategy Strategy
voters []Voter
}
func (m *Manager) Authorized(ctx context.Context, subject interface{}, obj interface{}, action interface{}) (Decision, error) {
decisions := make([]Decision, 0, len(m.voters))
logger.Debug(
ctx,
"checking authorization",
logger.F("subject", subject),
logger.F("object", obj),
logger.F("action", action),
)
for _, v := range m.voters {
dec, err := v.Vote(ctx, subject, obj, action)
if err != nil {
return Deny, errors.WithStack(err)
}
decisions = append(decisions, dec)
}
result, err := m.strategy(ctx, decisions)
if err != nil {
return Deny, errors.WithStack(err)
}
logger.Debug(
ctx,
"authorization checked",
logger.F("subject", subject),
logger.F("object", obj),
logger.F("action", action),
logger.F("result", AsString(result)),
)
return result, nil
}
func NewManager(strategy Strategy, voters ...Voter) *Manager {
return &Manager{strategy, voters}
}

View File

@ -0,0 +1,13 @@
package voter
import (
"gitlab.com/wpetit/goweb/service"
)
func ServiceProvider(strategy Strategy, voters ...Voter) service.Provider {
manager := NewManager(strategy, voters...)
return func(ctn *service.Container) (interface{}, error) {
return manager, nil
}
}

33
internal/voter/service.go Normal file
View File

@ -0,0 +1,33 @@
package voter
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "voter"
// From retrieves the voter service in the given container.
func From(container *service.Container) (*Manager, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Manager)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the voter service in the given container or panic otherwise.
func Must(container *service.Container) *Manager {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}

View File

@ -0,0 +1,77 @@
package voter
import "context"
// StrategyUnanimous returns Allow if all voters allow the operations.
func StrategyUnanimous(ctx context.Context, decisions []Decision) (Decision, error) {
allAbstains := true
for _, d := range decisions {
if d == Deny {
return Deny, nil
}
if d != Abstain {
allAbstains = false
}
}
if allAbstains {
return Abstain, nil
}
return Allow, nil
}
// StrategyAffirmative returns Allow if at least one voter allow the operation.
func StrategyAffirmative(ctx context.Context, decisions []Decision) (Decision, error) {
allAbstains := true
for _, d := range decisions {
if d == Allow {
return Allow, nil
}
if allAbstains && d != Abstain {
allAbstains = false
}
}
if allAbstains {
return Abstain, nil
}
return Deny, nil
}
// StrategyConsensus returns Allow if the majority of voters allow the operation.
func StrategyConsensus(ctx context.Context, decisions []Decision) (Decision, error) {
deny := 0
allow := 0
abstain := 0
for _, d := range decisions {
switch {
case d == Allow:
allow++
case d == Deny:
deny++
case d == Abstain:
abstain++
}
}
if abstain > allow && abstain > deny {
return Abstain, nil
}
if allow > abstain && allow > deny {
return Allow, nil
}
if deny > allow && deny > abstain {
return Deny, nil
}
return Abstain, nil
}

View File

@ -0,0 +1,125 @@
package voter
import (
"context"
"testing"
)
func TestStrategyUnanimous(t *testing.T) {
testCases := []struct {
Decisions []Decision
Expect Decision
}{
{
Decisions: []Decision{Allow, Allow, Allow},
Expect: Allow,
},
{
Decisions: []Decision{Abstain, Abstain, Abstain},
Expect: Abstain,
},
{
Decisions: []Decision{Deny, Abstain, Abstain},
Expect: Deny,
},
{
Decisions: []Decision{Deny, Allow, Abstain},
Expect: Deny,
},
}
for _, tc := range testCases {
ctx := context.Background()
result, err := StrategyUnanimous(ctx, tc.Decisions)
if err != nil {
t.Error(err)
}
if e, g := tc.Expect, result; e != g {
t.Errorf("result: expected '%v', got '%v'", AsString(e), AsString(g))
}
}
}
func TestStrategyAffirmative(t *testing.T) {
testCases := []struct {
Decisions []Decision
Expect Decision
}{
{
Decisions: []Decision{Allow, Allow, Allow},
Expect: Allow,
},
{
Decisions: []Decision{Abstain, Abstain, Abstain},
Expect: Abstain,
},
{
Decisions: []Decision{Deny, Abstain, Abstain},
Expect: Deny,
},
{
Decisions: []Decision{Deny, Allow, Abstain},
Expect: Allow,
},
}
for _, tc := range testCases {
ctx := context.Background()
result, err := StrategyAffirmative(ctx, tc.Decisions)
if err != nil {
t.Error(err)
}
if e, g := tc.Expect, result; e != g {
t.Errorf("result: expected '%v', got '%v'", AsString(e), AsString(g))
}
}
}
func TestStrategyConsensus(t *testing.T) {
testCases := []struct {
Decisions []Decision
Expect Decision
}{
{
Decisions: []Decision{Allow, Allow, Allow},
Expect: Allow,
},
{
Decisions: []Decision{Abstain, Abstain, Abstain},
Expect: Abstain,
},
{
Decisions: []Decision{Deny, Allow, Abstain},
Expect: Abstain,
},
{
Decisions: []Decision{Deny, Deny, Allow},
Expect: Deny,
},
{
Decisions: []Decision{Deny, Deny, Allow, Allow},
Expect: Abstain,
},
{
Decisions: []Decision{Deny, Deny, Allow, Allow, Allow},
Expect: Allow,
},
}
for _, tc := range testCases {
ctx := context.Background()
result, err := StrategyConsensus(ctx, tc.Decisions)
if err != nil {
t.Error(err)
}
if e, g := tc.Expect, result; e != g {
t.Errorf("result: expected '%v', got '%v'", AsString(e), AsString(g))
}
}
}