Пример #1
0
        public static void Authenticate(HttpContext context)
        {
            string tokenString = context.Request.Headers[AUTH_TOKEN_KEY];

            if (String.IsNullOrEmpty(tokenString))
            {
                var cookie = context.Request.Cookies.FirstOrDefault(c => c.Key == AUTH_TOKEN_KEY);
                tokenString = cookie.Value.FirstOrDefault();
            }

            if (tokenString != null)
            {
                AuthToken token = AuthToken.Decrypt(tokenString);
                if (token != null && token.Verify())
                {
                    var identity = GetIdentityFromCache(token.UserId);
                    if (identity == null)
                    {
                        identity = CreateIdentity(token.UserId);

                        //user has token, but identity cannot be created
                        //1. user is disabled
                        //2. user is missing
                        if (identity == null)
                        {
                            return;
                        }

                        AddIdentityToCache(token.UserId, identity);
                    }

                    //when user is modified and issue old token
                    //1. we don't authenticate it
                    //2. clear identity from cache
                    if (identity.User.ModifiedOn != token.LastModified)
                    {
                        RemoveIdentityFromCache(identity.User.Id);

                        identity = CreateIdentity(token.UserId);

                        //user has token, but identity cannot be created
                        //1. user is disabled
                        //2. user is missing
                        if (identity == null)
                        {
                            return;
                        }

                        AddIdentityToCache(token.UserId, identity);

                        return;
                    }

                    context.User = new ErpPrincipal(identity);
                }
            }
        }