File size: 1,465 Bytes
fc06b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System.Linq;
using ContactManagementAPI.Data;
using ContactManagementAPI.Models;
using Microsoft.EntityFrameworkCore;

namespace ContactManagementAPI.Services
{
    public class AuthorizationService
    {
        private readonly ApplicationDbContext _context;

        public AuthorizationService(ApplicationDbContext context)
        {
            _context = context;
        }

        public bool HasRight(int userId, string rightKey)
        {
            var user = _context.AppUsers
                .AsNoTracking()
                .FirstOrDefault(u => u.Id == userId);

            if (user == null || !user.IsActive)
                return false;

            if (user.IsAdmin)
                return true;

            var userRight = _context.UserRights
                .AsNoTracking()
                .FirstOrDefault(r => r.AppUserId == userId && r.RightKey == rightKey);

            if (userRight != null)
                return userRight.IsGranted;

            var groupRight = _context.GroupRights
                .AsNoTracking()
                .FirstOrDefault(r => r.UserGroupId == user.GroupId && r.RightKey == rightKey);

            return groupRight?.IsGranted ?? false;
        }

        public bool IsAdmin(int userId)
        {
            var user = _context.AppUsers
                .AsNoTracking()
                .FirstOrDefault(u => u.Id == userId);

            return user?.IsAdmin == true && user.IsActive;
        }
    }
}