示例#1
0
        /// <summary>
        /// </summary>
        /// <param name="personModelIdRequest"></param>
        /// <param name="personModelId"></param>
        /// <param name="newAuthorization"></param>
        /// <returns></returns>
        public async Task AutorizationModify(Guid personModelIdRequest, Guid personModelId, WellknownAuthorizationLevel newAuthorization)
        {
            try
            {
                var Usr = await _context.Persons.FirstOrDefaultAsync(p => p.Id == personModelId).ConfigureAwait(false);

                //in case of lowering the authorization i can do only if i'm not the only one with it, and only if thiere is at least one root
                if (newAuthorization < Usr.AutorizationLevel.AuthValue && await _context.Persons.AnyAsync(p => p.AutorizationLevel.AuthValue == Usr.AutorizationLevel.AuthValue && p.Id != Usr.Id).ConfigureAwait(false) &&
                    await _context.Persons.AnyAsync(p => p.AutorizationLevel.AuthValue == WellknownAuthorizationLevel.Root && p.Id != Usr.Id).ConfigureAwait(false))
                {
                    Usr.AutorizationLevel.AuthValue = newAuthorization;
                    await ModifySafeAut(Usr.Id, Usr.AutorizationLevel.Id, Usr.AutorizationLevel.AuthValue).ConfigureAwait(false);
                }
                else if (newAuthorization > Usr.AutorizationLevel.AuthValue)
                {
                    var UsrRequest = await _context.Persons.FirstOrDefaultAsync(p => p.Id == personModelIdRequest).ConfigureAwait(false);

                    if (Usr.AutorizationLevel.AuthValue == WellknownAuthorizationLevel.Root)
                    {
                        Usr.AutorizationLevel.AuthValue = newAuthorization;
                        await ModifySafeAut(Usr.Id, Usr.AutorizationLevel.Id, Usr.AutorizationLevel.AuthValue).ConfigureAwait(false);
                    }
                }
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during AutorizationModify", MethodBase.GetCurrentMethod(), ex);
            }
        }
示例#2
0
        public async Task <bool> CreateCard(CardCreateModel model)
        {
            if (model == null)
            {
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.CardNumber))
            {
                return(false);
            }
            try
            {
                if (await _context.CardModels.AnyAsync(c => c.CardNumber == model.CardNumber))
                {
                    return(false);
                }
                await _context.CardModels.AddAsync(_cardCreateModelToCardConverter.Map(model));

                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized od person", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#3
0
        public async Task <Guid> GetUserByInputAsync(string UserInput)
        {
            try
            {
                var user = new PersonModel();
                if (string.IsNullOrEmpty(UserInput) || string.IsNullOrEmpty(UserInput.Trim()))
                {
                    return(Guid.Empty);
                }
                string toFind = UserInput.Trim();

                if (toFind.IsValidEmail() && await _context.Persons.AnyAsync(p => string.Equals(p.Email, UserInput, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false))
                {
                    user = await _context.Persons.FirstOrDefaultAsync(p => string.Equals(p.Email, UserInput, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false);
                }
                else if (!toFind.IsValidEmail() && await _context.Persons.AnyAsync(p => string.Equals(p.UserName, UserInput, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false))
                {
                    user = await _context.Persons.FirstOrDefaultAsync(p => string.Equals(p.UserName, UserInput, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false);
                }
                return(user.Id);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Login", MethodBase.GetCurrentMethod(), ex);
                throw new Exception();
            }
        }
示例#4
0
        public async Task <bool> ChangeCardNumber(Guid personModelId, string CardNumber)
        {
            if (personModelId.Equals(Guid.Empty))
            {
                return(false);
            }
            if (string.IsNullOrWhiteSpace(CardNumber))
            {
                return(false);
            }
            try
            {
                if (!_context.Persons.Any(p => p.Id == personModelId))
                {
                    return(false);
                }
                if (!_context.CardModels.Any(c => c.CardNumber == CardNumber))
                {
                    return(false);
                }
                var usr = _context.Persons.First(p => p.Id == personModelId);
                usr.CardNumber = _context.CardModels.First(c => c.CardNumber == CardNumber);
                var encryptedRelation = await _securLib.EncryptEntityRelation(usr, usr.AutorizationLevel);

                usr.SafeAuthModel.Control = await _securLib.EncriptLine(encryptedRelation);

                _context.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized od person", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#5
0
        public List <MainMenuModel> GetMenuForUser(string personName)
        {
            try
            {
                if (string.IsNullOrEmpty(personName))
                {
                    StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "personName is null or empty", MethodBase.GetCurrentMethod());
                    return(null);
                }
                var user = new PersonModel();
                user = _context.Persons.FirstOrDefault(p => p.UserName == personName);

                if (user != null && user.AutorizationLevel != null)
                {
                    return(GetMenuForAuthorization(user.AutorizationLevel.AuthValue.ToString()));
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during GetMenuForUser", MethodBase.GetCurrentMethod(), ex);
                return(null);
            }
        }
示例#6
0
        /// <summary>
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="newAuthorization"></param>
        /// <param name="NewWellknownAuthorizationLevel"></param>
        /// <returns></returns>
        private async Task ModifySafeAut(Guid personId, Guid newAuthorization, WellknownAuthorizationLevel NewWellknownAuthorizationLevel)
        {
            try
            {
                if (await _context.Persons.AnyAsync(p => p.Id == personId))
                {
                    if (await AuthNotModified(personId))
                    {
                        return;
                    }
                    var user = await _context.Persons.FirstAsync(p => p.Id == personId);

                    if (user.SafeAuthModel == null)
                    {
                        return;
                    }
                    user.SafeAuthModel.AutId = newAuthorization;
                    var encryptedRelation = await _securLib.EncryptEntityRelation(user, user.AutorizationLevel);

                    user.SafeAuthModel.Control = await _securLib.EncriptLine(encryptedRelation);

                    await _context.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during ModifySafeAut", MethodBase.GetCurrentMethod(), ex);
            }
        }
示例#7
0
        public async Task <bool> UpdateAsync(NodeUpdateModel node)
        {
            try
            {
                var savenode = JToken.FromObject(node).ToObject <NodeModel>();
                var any      = await GetByIdAsync(node.Id);

                if (any == null)
                {
                    return(false);
                }
                else
                {
                    var toUpdate = _context.Nodes.First(n => n.Id == node.Id);
                    toUpdate = savenode;
                }
                _context.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Update", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#8
0
 public async Task <Guid> GetUserByInputAsync(string UserInput)
 {
     try
     {
         return(await _accessManagerService.GetUserByInputAsync(UserInput));
     }
     catch (Exception ex)
     {
         StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Login", MethodBase.GetCurrentMethod(), ex);
         throw new UnauthorizedAccessException($"error during Login:{ex.Message}, {ex.InnerException}");
     }
 }
示例#9
0
 public override async Task <SignInResult> PasswordSignInAsync(PersonModel user, string password, bool isPersistent, bool lockoutOnFailure)
 {
     try
     {
         return(await _accessManagerService.ValidateLoginAsync(user.UserName, password, isPersistent, lockoutOnFailure));
     }
     catch (Exception ex)
     {
         StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Login", MethodBase.GetCurrentMethod(), ex);
         return(SignInResult.Failed);
     }
 }
示例#10
0
        /// <summary>
        /// determine if the authorization of the car match the needed Authorization
        /// </summary>
        /// <param name="CarModelId">car anagraphic</param>
        /// <param name="AuthNeeded">needed Authorization</param>
        /// <returns></returns>
        public async Task <bool> IsCarAutorized(string CarModelId, WellknownAuthorizationLevel AuthNeeded)
        {
            try
            {
                CarAnagraphicModel car = await _context.Cars.FirstOrDefaultAsync(ca => ca.LicencePlate == CarModelId).ConfigureAwait(false);

                return(await IsAutorized(car.Owner.Id, AuthNeeded).ConfigureAwait(false));
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized of CAR", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#11
0
        public async Task <bool> Access(AccessModel newAccess)
        {
            newAccess.GrantedAccess = false;
            if (newAccess.personEntered.Equals(Guid.Empty) || !string.IsNullOrEmpty(newAccess.Plate) || !string.IsNullOrEmpty(newAccess.CardNumber))
            {
                try
                {
                    PersonModel owner = new PersonModel();
                    WellknownAuthorizationLevel accessLevelNeed = WellknownAuthorizationLevel.Root;
                    if (newAccess.personEntered.Equals(Guid.Empty) && !string.IsNullOrEmpty(newAccess.Plate))
                    {
                        if (await _context.Cars.AnyAsync(c => c.LicencePlate == newAccess.Plate))
                        {
                            var entered = await _context.Cars.FirstAsync(c => c.LicencePlate == newAccess.Plate).ConfigureAwait(false);

                            owner = entered.Owner;
                        }
                    }
                    else if (await _context.Persons.AnyAsync(c => c.CardNumber.CardNumber == newAccess.CardNumber).ConfigureAwait(false))
                    {
                        owner = await _context.Persons.FirstAsync(a => a.CardNumber.CardNumber == newAccess.CardNumber).ConfigureAwait(false);

                        if (!await _context.Nodes.AnyAsync(n => n.Name == newAccess.NodeName && n.MacAddress == newAccess.MacAddress))
                        {
                            return(false);
                        }
                        var node = await _context.Nodes.FirstAsync(n => n.Name == newAccess.NodeName && n.MacAddress == newAccess.MacAddress);

                        accessLevelNeed = node.AuthValue;
                    }
                    if (await _autorizationManagerService.IsAutorized(owner.Id, accessLevelNeed).ConfigureAwait(false))
                    {
                        newAccess.personEntered = owner.Id;
                        newAccess.GrantedAccess = true;
                    }
                    await _context.Access.AddAsync(newAccess).ConfigureAwait(false);

                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    //StaticEventHandler.SendMail(new MailEventArgs(ResourceString.AccessCarMailSubject, ResourceString.AccessCarMailBody, DateTime.UtcNow));
                }
                catch (Exception ex)
                {
                    StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Card verification", MethodBase.GetCurrentMethod(), ex);
                    return(false);
                }
            }
            return(newAccess.GrantedAccess);
        }
示例#12
0
        public async Task <SignInResult> ValidateLoginAsync(string username, string password, bool rememberMe, bool shouldLockout)
        {
            try
            {
                var userId = await GetUserByInputAsync(username).ConfigureAwait(false);

                if (userId.Equals(Guid.Empty))
                {
                    return(SignInResult.Failed);
                }
                if (await _context.Persons.AnyAsync(p => p.Id == userId).ConfigureAwait(false))
                {
                    PersonModel userSelected = await _context.Persons.Include(Auth => Auth.AutorizationLevel).Include(Card => Card.CardNumber).FirstOrDefaultAsync(p => p.Id == userId).ConfigureAwait(false);

                    var encrypted = await _securLib.EncriptLine(password);

                    if (await _securLib.CompareHash(userSelected.Password, encrypted))
                    {
                        // authentication successful so generate jwt token
                        var tokenHandler = new JwtSecurityTokenHandler();

                        var key             = Encoding.ASCII.GetBytes(_configuration["PreSharedKey"]);
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                                new Claim(ClaimTypes.Name, userSelected.Id.ToString())
                            }),
                            Expires            = DateTime.UtcNow.AddDays(7),
                            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                        };
                        var token       = tokenHandler.CreateToken(tokenDescriptor);
                        var secureToken = tokenHandler.WriteToken(token);
                        return(SignInResult.Success);
                    }
                    else
                    {
                        return(SignInResult.Failed);
                    }
                }
                return(SignInResult.Failed);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Login", MethodBase.GetCurrentMethod(), ex);
                return(SignInResult.Failed);
            }
        }
示例#13
0
        public async Task <List <NodeReadModel> > GetAllAsync()
        {
            try
            {
                var list = await _context.Nodes.ToListAsync();

                var readedRes = new List <NodeReadModel>();
                list.ForEach(l => readedRes.Add(JToken.FromObject(l).ToObject <NodeReadModel>()));
                return(readedRes);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "", MethodBase.GetCurrentMethod(), ex);
                return(null);
            }
        }
示例#14
0
 public Guid Create(NodeCreateModel node)
 {
     try
     {
         var savenode = JToken.FromObject(node).ToObject <NodeModel>();
         savenode.Id        = Guid.NewGuid();
         savenode.CreatedAt = DateTime.UtcNow;
         _context.Nodes.Add(savenode);
         _context.SaveChanges();
         return(savenode.Id);
     }
     catch (Exception ex)
     {
         StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Update", MethodBase.GetCurrentMethod(), ex);
         return(Guid.Empty);
     }
 }
示例#15
0
        public List <MainMenuModel> GetMenuForAuthorization(string Auth)
        {
            try
            {
                if (string.IsNullOrEmpty(Auth))
                {
                    StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "Auth is null or empty", MethodBase.GetCurrentMethod());
                    return(null);
                }
                var authlevel = (WellknownAuthorizationLevel)Convert.ToInt32(Auth);

                return(_context.MainMenu.Where(c => c.AuthLevel == authlevel).ToList());
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during GetMenuForUser", MethodBase.GetCurrentMethod(), ex);
                return(null);
            }
        }
示例#16
0
        public async Task <bool> DeleteAsync(Guid nodeId)
        {
            try
            {
                var any = await _context.Nodes.AnyAsync(n => n.Id == nodeId);

                if (!any)
                {
                    return(false);
                }
                _context.Nodes.Remove(_context.Nodes.First(n => n.Id == nodeId));
                _context.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during Delete", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#17
0
 private void SendMessage(object sender, MailEventArgs mailEvent)
 {
     try
     {
         mailMessage = new MailMessage
         {
             From = new MailAddress("*****@*****.**")
         };
         foreach (var rec in mailEvent.Recievers)
         {
             mailMessage.To.Add(rec);
         }
         mailMessage.Body    = mailEvent.Message;
         mailMessage.Subject = mailEvent.Subject;
         client.Send(mailMessage);
     }
     catch (Exception ex)
     {
         StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "Error Sending mail", MethodBase.GetCurrentMethod(), ex);
     }
 }
示例#18
0
        public async Task <Guid> Create(PersonCreateModel person, AutorizationLevelCreateModel autorizationLevel)
        {
            try
            {
                if (person == null || autorizationLevel == null)
                {
                    return(Guid.Empty);
                }
                var dbPerson = await _personCreateModelToPersonModelConverter.Map(person).ConfigureAwait(false);

                _context.Persons.Add(dbPerson);
                _context.Autorizations.Add(dbPerson.AutorizationLevel);
                _context.SafeAuthModels.Add(dbPerson.SafeAuthModel);
                _context.SaveChanges();
                return(dbPerson.Id);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized od person", MethodBase.GetCurrentMethod(), ex);
                return(Guid.Empty);
            }
        }
示例#19
0
        public async Task <NodeReadModel> GetByIdAsync(Guid nodeId)
        {
            try
            {
                if (_context.Nodes.Any(n => n.Id.Equals(nodeId)))
                {
                    var model = await _context.Nodes.FirstAsync(n => n.Id.Equals(nodeId));

                    var res = JToken.FromObject(model).ToObject <NodeReadModel>();
                    return(res);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "", MethodBase.GetCurrentMethod(), ex);
                return(null);
            }
        }
示例#20
0
        public async Task <bool> UpdateCardExpirationDate(string CardNumber, DateTime newExpirationDate)
        {
            if (string.IsNullOrWhiteSpace(CardNumber))
            {
                return(false);
            }
            try
            {
                if (!await _context.CardModels.AnyAsync(c => c.CardNumber == CardNumber).ConfigureAwait(false))
                {
                    return(false);
                }
                var card = await _context.CardModels.FirstAsync(c => c.CardNumber == CardNumber).ConfigureAwait(false);

                card.ExpirationDate = newExpirationDate;
                _context.SaveChanges();
                return(true);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized od person", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#21
0
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public async Task CreateAdmin()
        {
            try
            {
                var card = new CardCreateModel()
                {
                    CardNumber     = "123456",
                    ExpirationDate = DateTime.UtcNow.AddYears(1),
                };
                var usr = new PersonCreateModel()
                {
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Password = await _securLib.EncriptLine("Admin"),
                };
                var auth = new AutorizationLevelCreateModel()
                {
                    AuthName       = "ROOT",
                    AuthValue      = WellknownAuthorizationLevel.Root,
                    ExpirationDate = DateTime.UtcNow.AddYears(1)
                };
                await Create(usr, auth);

                var menu = _menuService.CreateMenuFromPages();
                foreach (var vm in menu)
                {
                    vm.AuthLevel = WellknownAuthorizationLevel.User;
                }
                _context.MainMenu.AddRange(menu);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized of person", MethodBase.GetCurrentMethod(), ex);
            }
        }
示例#22
0
        /// <summary>
        /// </summary>
        /// <param name="personId"></param>
        /// <returns></returns>
        private async Task <bool> AuthNotModified(Guid personId)
        {
            try
            {
                if (await _context.Persons.AnyAsync(p => p.Id == personId).ConfigureAwait(false))
                {
                    var user = await _context.Persons.Include(Auth => Auth.AutorizationLevel).Include(Card => Card.CardNumber).FirstAsync(p => p.Id == personId).ConfigureAwait(false);

                    if (user.SafeAuthModel == null)
                    {
                        return(false);
                    }
                    var encryptedRelation = await _securLib.EncryptEntityRelation(user, user.AutorizationLevel);

                    return(await _securLib.CompareHash(user.SafeAuthModel.Control, encryptedRelation));
                }
                return(false);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during AuthNotModified", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }
示例#23
0
        /// <summary>
        /// private member that verify the user an the autorization
        /// </summary>
        /// <param name="personModelId"></param>
        /// <param name="AuthNeeded"></param>
        /// <returns></returns>
        public async Task <bool> IsAutorized(Guid personModelId, WellknownAuthorizationLevel AuthNeeded)
        {
            try
            {
                if (await _context.Persons.AnyAsync(p => p.Id == personModelId).ConfigureAwait(false))
                {
                    PersonModel usr = await _context.Persons.FirstOrDefaultAsync(p => p.Id == personModelId).ConfigureAwait(false);

                    if (usr.AutorizationLevel.AuthValue >= AuthNeeded &&
                        await AuthNotModified(usr.Id).ConfigureAwait(false) &&
                        (usr.AutorizationLevel.ExpirationDate.Date >= DateTime.Today.Date || usr.AutorizationLevel.AuthValue == WellknownAuthorizationLevel.Root))
                    {
                        return(true);
                    }
                    return(false);
                }
                return(false);
            }
            catch (Exception ex)
            {
                StaticEventHandler.Log(System.Diagnostics.TraceLevel.Error, "error during IsAutorized of person", MethodBase.GetCurrentMethod(), ex);
                return(false);
            }
        }