showing results for - "casl react"
Nadir
28 May 2017
1import { AbilityBuilder } from '@casl/ability';
2import React, { useState, useContext } from 'react';
3import { AbilityContext } from './Can';
4
5function updateAbility(ability, user) {
6  const { can, rules } = new AbilityBuilder();
7
8  if (user.role === 'admin') {
9    can('manage', 'all');
10  } else {
11    can('read', 'all');
12  }
13
14  ability.update(rules);
15}
16
17export default () => {
18  const [username, setUsername] = useState('');
19  const [password, setPassword] = useState('');
20  const ability = useContext(AbilityContext);
21  const login = () => {
22    const params = {
23      method: 'POST',
24      body: JSON.stringify({ username, password })
25    };
26    return fetch('path/to/api/login', params)
27      .then(response => response.json())
28      .then(({ user }) => updateAbility(ability, user));
29  };
30
31  return (
32    <form>
33      {/* input fields */}
34      <button onClick={login}>Login</button>
35    </form>
36  );
37};