view Agendas/trunk/src/Agendas.Domain/IdentityContext.cs @ 179:1deccd6c3cb2

Aplicando seguridad x roles en sitio web
author nelopauselli
date Mon, 08 Aug 2011 15:24:26 -0300
parents 7a2eeb9e9bf9
children
line wrap: on
line source

using System;
using System.Collections.Generic;
using System.Linq;
using AltNetHispano.Agendas.Domain.Exceptions;
using AltNetHispano.Agendas.Domain.Repositories;

namespace AltNetHispano.Agendas.Domain
{
	public class IdentityContext
	{
		private static ISeguridad _current;
		private static IPersonaRepository _personaRepository;

		public static void Init(ISeguridad seguridad, IPersonaRepository personaRepository)
		{
			_current = seguridad;
			_personaRepository = personaRepository;
		}

		private static ISeguridad Current
		{
			get
			{
				if (_current == null)
					throw new IdentityContextNotConfiguredException();
				return _current;
			}
		}

		public static string GetUserName()
		{
			return Current.GetUserName();
		}

		public static bool IsAuthenticated()
		{
			return !string.IsNullOrWhiteSpace(GetUserName());
		}

		public static Persona GetUsuario()
		{
			var userName = GetUserName();
			if (string.IsNullOrWhiteSpace(userName))
				throw new UsuarioNoAutenticadoException();

			var identification = new Identification(userName);

			var cuenta = _personaRepository.GetCuenta(identification.IdentityProvider, identification.LogonName);
			return cuenta != null ? cuenta.Persona : null;
		}

		public static bool IsInRole(IEnumerable<string> roles)
		{
			var persona = GetUsuario();
			return IsInRole(persona, roles);
		}

		public static bool IsInRole(Persona persona, IEnumerable<string> roles)
		{
			if (persona == null) return false;
			return roles.Any(role => persona.Roles.Contains(role));
		}
	}
}