aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.BL/EntitiesExtensions/User.cs
blob: 321fa55701699de93133ed7e78cd9530bc10537e (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Enumerations;
using SimpleValidator.Extensions;

namespace Tango.BL.Entities
{
    public partial class User
    {
        /// <summary>
        /// Determines whether the user has the specified permission.
        /// </summary>
        /// <param name="permission">The permission.</param>
        /// <returns>
        ///   <c>true</c> if the user has permission; otherwise, <c>false</c>.
        /// </returns>
        public bool HasPermission(Permissions permission)
        {
            return UsersRoles.Select(x => x.Role).ToList().SelectMany(x => x.RolesPermissions).ToList().Exists(x => x.Permission.Code == permission.ToInt32());
        }

        /// <summary>
        /// Gets the aggregated user roles as enumerations.
        /// </summary>
        [NotMapped]
        public List<Role> Roles
        {
            get { return UsersRoles.Select(x => x.Role).ToList(); }
        }

        /// <summary>
        /// Gets the aggregated user permissions as enumerations.
        /// </summary>
        [NotMapped]
        public List<Permission> Permissions
        {
            get
            {
                return UsersRoles.Select(x => x.Role).ToList().SelectMany(x => x.RolesPermissions).Select(x => x.Permission).ToList();
            }
        }

        public override void Validate(ObservablesContext context)
        {
            var users = context.Users.ToList();

            if (users.Exists(x => x.Guid != Guid && x.Email.ToLower() == Email.ToLower()))
            {
                throw new ArgumentException("The specified email is already taken by another account.");
            }

            if (!Email.IsEmail())
            {
                throw new ArgumentException("The specified email address is invalid.");
            }

            if (!Password.IsBetweenLength(4, 30))
            {
                throw new ArgumentException("A user password must be at least 4 characters long and maximum 30.");
            }

            if (Contact != null)
            {
                Contact.Validate(context);
            }

            if (Address != null)
            {
                Address.Validate(context);
            }
        }
    }
}