Ejemplo n.º 1
0
        public void SignOut(SignOutOption signOutOption)
        {
            var identity = (AnkaCMSIdentity)Thread.CurrentPrincipal.Identity;

            var cacheKeyProfile = CacheKeyOption.Profile + "-" + identity.UserId;

            var sessions = _repositorySession.Get().Where(e => e.Creator.Id == identity.UserId).ToList();

            if (sessions.Count > 0)
            {
                foreach (var session in sessions)
                {
                    _repositorySessionHistory.Add(new SessionHistory
                    {
                        Id                   = GuidHelper.NewGuid(),
                        Creator              = session.Creator,
                        CreationTime         = session.CreationTime,
                        LastModificationTime = DateTime.Now,
                        LogoutType           = signOutOption.ToString(),
                    }, true);

                    //          _repositorySession.Delete(session,true);
                }
            }

            // Kimlik nesnesi boşaltılıp yeniden oluşturuluyor
            identity = new AnkaCMSIdentity();
            identity.AddClaims(new[]
            {
                new Claim("UserId", Guid.Empty.ToString()),
                new Claim("Username", string.Empty),
                new Claim("Password", string.Empty),
                new Claim("FirstName", string.Empty),
                new Claim("LastName", string.Empty),
                new Claim("DisplayName", string.Empty),
                new Claim("Email", string.Empty)
            });

            var principal = new AnkaCMSPrincipal(identity);

            // Thread geçerli kimlik bilgisi ayarlanıyor
            Thread.CurrentPrincipal = principal;
            //     _cacheService.Remove(cacheKeyProfile);
        }
Ejemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            var httpContext     = context.Request.HttpContext;
            var securityService = httpContext.RequestServices.GetService <IIdentityService>();

            try
            {
                var identity = securityService.Get();
                if (identity == null)
                {
                    identity = new AnkaCMSIdentity();
                    identity.AddClaims(new[]
                    {
                        new Claim("UserId", Guid.Empty.ToString()),
                        new Claim("Username", string.Empty),
                        new Claim("Password", string.Empty),
                        new Claim("FirstName", string.Empty),
                        new Claim("LastName", string.Empty),
                        new Claim("DisplayName", string.Empty),
                        new Claim("Email", string.Empty)
                    });
                }
                var principal = new AnkaCMSPrincipal(identity);
                Thread.CurrentPrincipal = principal;
                httpContext.User        = principal;
                var pathValue = httpContext.Request.Path.Value;
                if (pathValue != "/")
                {
                    pathValue = pathValue.Replace("api/", "");

                    var pathValueArray = pathValue.Split('/');

                    if (pathValueArray.Length > 1)
                    {
                        string controller;
                        string action;

                        if (pathValueArray.Length == 2)
                        {
                            controller = pathValueArray[1];
                            action     = "Index";
                        }
                        else
                        {
                            controller = pathValueArray[1];
                            action     = pathValueArray[2];
                        }
                        var roleService = httpContext.RequestServices.GetService <IRoleService>();
                        var actionRoles = roleService.GetActionRoles(controller, action);

                        // Sayfa vtde kayıtlı değilse devam et
                        if (actionRoles != null && actionRoles.Count > 0)
                        {
                            var identityIsAuthorized = identity.Roles.Any(r => actionRoles.Contains(r));
                            if (!identityIsAuthorized)
                            {
                                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                                return;
                            }
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = StatusCodes.Status403Forbidden;
                        return;
                    }
                }
            }
            catch (Exception)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return;
            }



            await _next(context);
        }
Ejemplo n.º 3
0
        public void SignIn(SignInModel model)
        {
            IValidator validator         = new FluentValidator <SignInModel, SignInModelValidationRules>(model);
            var        validationResults = validator.Validate();

            if (!validator.IsValid)
            {
                throw new ValidationException(Messages.DangerInvalidEntitiy)
                      {
                          ValidationResult = validationResults
                      };
            }

            var user = _repositoryUser
                       .Join(x => x.Person)
                       .Join(x => x.Creator)
                       .Join(x => x.RoleUserLines)
                       .Join(x => x.SessionsCreatedBy)
                       .FirstOrDefault(x => x.Username == model.Username);

            // Kullanıcı sistemde kayıtlı değilse
            if (user == null)
            {
                throw new NotFoundException(Messages.DangerUserNotFound);
            }

            // Şifresi yanlış ise
            if (model.Password.ToSha512() != user.Password)
            {
                throw new NotFoundException(Messages.DangerIncorrectPassword);
            }

            // Kullanıcı pasif durumda ise
            if (!user.IsApproved)
            {
                throw new NotApprovedException(Messages.DangerItemNotApproved);
            }

            // Kullanıcının hiç rolü yoksa
            if (user.RoleUserLines.Count <= 0)
            {
                throw new NotApprovedException(Messages.DangerUserHasNoRole);
            }

            var sessionIdList = new List <Guid>();

            // Açık kalan oturumu varsa
            if (user.SessionsCreatedBy?.Count > 0)
            {
                foreach (var session in user.SessionsCreatedBy)
                {
                    // oturum bilgileri tarihçe tablosuna alınıyor
                    _repositorySessionHistory.Add(new SessionHistory
                    {
                        Id                   = GuidHelper.NewGuid(),
                        Creator              = session.Creator,
                        CreationTime         = session.CreationTime,
                        LastModificationTime = DateTime.Now,
                        LogoutType           = SignOutOption.InvalidLogout.ToString()
                    }, true);
                    sessionIdList.Add(session.Id);
                }
            }

            // Oturumlar siliniyor
            foreach (var i in sessionIdList)
            {
                _repositorySession.Delete(_repositorySession.Get(e => e.Id == i), true);
            }

            // Yeni oturum kaydı yapılıyor
            _repositorySession.Add(new Session
            {
                Id           = GuidHelper.NewGuid(),
                Creator      = user,
                CreationTime = DateTime.Now
            }, true);

            var roles = user.RoleUserLines
                        .Select(
                line =>
                _repositoryRoleUserLine
                .Join(t => t.Role)

                .FirstOrDefault(x => x.Id == line.Id).Role)
                        .Select(role => new KeyValuePair <Guid, string>(role.Id, role.Name)).ToList();

            // Kimlik nesnesi
            var identity = new AnkaCMSIdentity();

            // Kullanıcıdaki bilgiler kullanılarak kimlik nesnesinin claim (hak) listesi ayarlanıyor
            var claims = new List <Claim>
            {
                new Claim("UserId", user.Id.ToString()),
                new Claim("Username", user.Username),
                new Claim("FirstName", user.Person.FirstName),
                new Claim("LastName", user.Person.LastName),
                new Claim("DisplayName", user.Person.DisplayName),
                new Claim("Email", user.Email),
                new Claim("IsAuthenticated", "true", ClaimValueTypes.Boolean),
                new Claim("AuthenticationType", "Normal")
            };

            // claim listesi kimlik nesnesine ekleniyor.
            identity.AddClaims(claims);

            // Kullanıcının rol id'leri kimlik nesnesine ekleniyor.
            foreach (var role in roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role.Key.ToString()));
            }

            // Yetkilendirilme işlemleri için temel nesne oluşturuluyor
            var principal = new AnkaCMSPrincipal(identity);

            // Thread geçerli kimlik bilgisi ayarlanıyor
            Thread.CurrentPrincipal = principal;
        }