1

我需要让时事通讯订阅工作正常进行。我使用的逻辑是当用户提交他的电子邮件时,我检查是否已经有用户使用该电子邮件注册到该站点。如果是,我会检查他是否订阅了时事通讯并进行适当的订阅。如果电子邮件不在注册用户列表中,那么我有一个匿名用户的通讯表。我在这里检查他是否订阅并执行必要的操作。

这是我的控制器操作代码:

/**
 * @Route("/newsletter/", name="site_newsletter")
 * @return array
 */
public function newsletterSubscriptionAction(httpRequest $request)
{  
    $email = $request->request->get('email');

    try {

        $email = $request->request->get('email');
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery(
            'SELECT u FROM MyBundle:User u WHERE u.email = :email'
        )->setParameter('email', $email);

        $user = $query->getSingleResult();

        if(!is_object($user)){ //this means anonymous user not registered to site
            $em = $this->getDoctrine()->getEntityManager();
            $query = $em->createQuery(
                'SELECT n FROM MyBundle:Newsletter n WHERE n.email = :email AND n.isSubscribed = 1'
            )->setParameter('email', $email);

            $record = $query->getSingleResult();

            if($record){
                $msg = "You are already subscribed!";
            }else{
                $newsletter = new Newsletter();
                $newsletter->setEmail($email);
                $newsletter->setIsSubscribed(true);

                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($newsletter);
                $em->flush();

                $msg = "You have been subscribed to our newsletter! Thank You.";
            }
        }else{
            if($user->getNewsletterSubscription()){
                $msg = "You are already subscribed!";
            }else{
                $user->setNewsletterSubscription(1);
                $em = $this->getDoctrine()->getEntityManager();
                $em->flush();                    
                $msg = "You have been subscribed to our newsletter! Thank You.";
            }                
        }

    }
    catch (\Exception $e) {
        $msg = 'Some problem occured. Please try again later';
    }

    if ($this->getRequest()->isXmlHttpRequest()) {
        return new \Symfony\Component\HttpFoundation\Response($msg);
        return array('msg' => $msg);
    }

}

我正在使用 ajax 来调用这个控制器动作。这是行不通的。返回到 ajax 的数据是重定向的登录页面。

我正在使用 FOSUSerBundle 来管理用户。这会导致任何问题吗?实现它的最佳方法是什么?

提前致谢!

4

1 回答 1

2

听起来您需要授予匿名用户使用您的订阅路线的权限。

在您的 security.yml 文件中,添加如下内容:

security:
    access_control:
        - { path: ^/subscribe, roles: IS_AUTHENTICATED_ANONYMOUSLY }
于 2012-04-10T13:35:26.737 回答