Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Martina_Shebova avatar Martina_Shebova 10 Точки

Login формата не работи

Здравейте,

логина ми не работи, гледах какво се случва като се опитам да се логна в файла dev.log и там изписва следната грешка:

security.INFO: Authentication request failed. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException(code: 0): Bad credentials. at C:\\Users\\User\\Desktop\\Mars_BattleGround_2031\\vendor\\symfony\\symfony\\src\\Symfony\\Component\\Security\\Core\\Authentication\\Provider\\UserAuthenticationProvider.php:90, Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException(code: 0): The presented password is invalid. at C:\\Users\\User\\Desktop\\Mars_BattleGround_2031\\vendor\\symfony\\symfony\\src\\Symfony\\Component\\Security\\Core\\Authentication\\Provider\\DaoAuthenticationProvider.php:67)"} []

Security Controller:

<?php

namespace MarsGameBundle\Controller;

use MarsGameBundle\Entity\Player;
use MarsGameBundle\Form\PlayerType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller used to manage the application security.
 * See http://symfony.com/doc/current/cookbook/security/form_login_setup.html.
 *
 * @author Ryan Weaver <weaverryan@gmail.com>
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
class SecurityController extends Controller
{
    /**
     * @Route("/login", name="security_login")
     */
    public function loginAction()
    {
        return $this->render('security/login.html.twig');
    }

    /**
     * This is the route the user can use to logout.
     *
     * But, this will never be executed. Symfony will intercept this first
     * and handle the logout automatically. See logout in app/config/security.yml
     *
     * @Route("/logout", name="security_logout")
     */
    public function logoutAction()
    {
        throw new \Exception('This should never be reached!');
    }
}

Security.yml

security:
    encoders:
        # Our user class and the algorithm we'll use to encode passwords
        # http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password
        MarsGameBundle\Entity\Player: bcrypt

    providers:
        # in this example, users are stored via Doctrine in the database
        # To see the users at src/AppBundle/DataFixtures/ORM/LoadFixtures.php
        # To load users from somewhere else: http://symfony.com/doc/current/cookbook/security/custom_provider.html
        database_users:
            entity: { class: MarsGameBundle:Player, property: username }

    # http://symfony.com/doc/current/book/security.html#firewalls-authentication
    firewalls:
        secured_area:
            # this firewall applies to all URLs
            pattern: ^/

            # but the firewall does not require login on every page
            # denying access is done in access_control or in your controllers
            anonymous: true

            # This allows the user to login by submitting a username and password
            # Reference: http://symfony.com/doc/current/cookbook/security/form_login_setup.html
            form_login:
                # The route name that the login form submits to
                check_path: security_login
                # The name of the route where the login form lives
                # When the user tries to access a protected page, they are redirected here
                login_path: security_login
                # Secure the login form against CSRF
                # Reference: http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html
                csrf_token_generator: security.csrf.token_manager

            logout:
                # The route name the user can go to in order to logout
                path: security_logout
                # The name of the route to redirect to after logging out
                target: home_index


    access_control:
        # this is a catch-all for the admin area
        # additional security lives in the controllers
#        - { path: '^/(%locale%)/admin', roles: ROLE_ADMIN }
security:
    encoders:
        # Our user class and the algorithm we'll use to encode passwords
        # http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password
        MarsGameBundle\Entity\Player: bcrypt

    providers:
        # in this example, users are stored via Doctrine in the database
        # To see the users at src/AppBundle/DataFixtures/ORM/LoadFixtures.php
        # To load users from somewhere else: http://symfony.com/doc/current/cookbook/security/custom_provider.html
        database_users:
            entity: { class: MarsGameBundle:Player, property: username }

    # http://symfony.com/doc/current/book/security.html#firewalls-authentication
    firewalls:
        secured_area:
            # this firewall applies to all URLs
            pattern: ^/

            # but the firewall does not require login on every page
            # denying access is done in access_control or in your controllers
            anonymous: true

            # This allows the user to login by submitting a username and password
            # Reference: http://symfony.com/doc/current/cookbook/security/form_login_setup.html
            form_login:
                # The route name that the login form submits to
                check_path: security_login
                # The name of the route where the login form lives
                # When the user tries to access a protected page, they are redirected here
                login_path: security_login
                # Secure the login form against CSRF
                # Reference: http://symfony.com/doc/current/cookbook/security/csrf_in_login_form.html
                csrf_token_generator: security.csrf.token_manager

            logout:
                # The route name the user can go to in order to logout
                path: security_logout
                # The name of the route to redirect to after logging out
                target: home_index


    access_control:
        # this is a catch-all for the admin area
        # additional security lives in the controllers
#        - { path: '^/(%locale%)/admin', roles: ROLE_ADMIN }

Прочетох в Интернет, че понякога тази грешка е от дължината на паролата, но при различен алгоритъм за криптиране. Дължината на колоната с паролата е VARCHAR 255.

Тагове:
0
PHP Web Development
RoYaL avatar RoYaL Trainer 6849 Точки

А записите в базата криптирани ли са? Дай да видим регистрацията

0
Martina_Shebova avatar Martina_Shebova 10 Точки

В базата влизат криптирани. Ето кода на регистрацията:

namespace MarsGameBundle\Controller;

use MarsGameBundle\Entity\Building;
use MarsGameBundle\Entity\GameResource;
use MarsGameBundle\Entity\City;
use MarsGameBundle\Entity\CityBuildings;
use MarsGameBundle\Entity\CityResource;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use MarsGameBundle\Entity\Player;
use MarsGameBundle\Form\PlayerType;
use MarsGameBundle\Repository\PlayerRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class PlayerController
 * @package MarsGameBundle\Controller
 * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
 */
class PlayerController extends CityController
{
    const MIN_COORDINATE_X = 0;
    const MAX_COORDINATE_X = 1000;

    const MIN_COORDINATE_Y = 0;
    const MAX_COORDINATE_Y = 1000;

    const NUMBER_OF_CITIES_EVERY_PLAYER_STARTS_WITH = 3;

    const AMOUNT_OF_RESOURCES_EVERY_PLAYER_STARTS_WITH = 5000;


    /**
     * @Route("/register", name="user_register")
     * @Security("is_granted('IS_AUTHENTICATED_ANONYMOUSLY')")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function registerAction(Request $request)
    {
        // 1) build the form
        $player = new Player();
        $form = $this->createForm(PlayerType::class, $player);

        // 2) handle the submit (will only happen on POST)
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            // 3) Encode the password (you could also do this via Doctrine listener)
            $password = $this->get('security.password_encoder')
                ->encodePassword($player, $player->getPassword());
            $player->setPassword($password);

            $getRequest = $request->request->get('user');

            $userName = $getRequest['username'];
            $fullName = $getRequest['fullName'];

            $player->setUsername($userName);
            $player->setFullName($fullName);

            // 4) save the User!
            $em = $this->getDoctrine()->getManager();
            $em->persist($player);
            $em->flush();

            $cityRepository = $this->getDoctrine()->getRepository(City::class);
            for ($i = 0; $i < self::NUMBER_OF_CITIES_EVERY_PLAYER_STARTS_WITH; $i++) {
                $coordinateX = -1;
                $coordinateY = -1;
                do {
                    $coordinateX = rand(self::MIN_COORDINATE_X, self::MAX_COORDINATE_X);
                    $coordinateY = rand(self::MIN_COORDINATE_Y, self::MAX_COORDINATE_Y);
                    $alreadyTakenCity = $cityRepository->findOneBy(
                        ['x' => $coordinateX, 'y' => $coordinateY]
                    );
                } while ($alreadyTakenCity !== null);

                $city = new City();
                $city->setX($coordinateX);
                $city->setY($coordinateY);
                $city->setCityName($player->getUsername() . "_" . ($i+1));
                $city->setPlayer($player);
                $em->persist($city);
                $em->flush();

                $resourceRepository = $this->getDoctrine()->getRepository(GameResource::class);
                $resourceTypes = $resourceRepository->findAll();

                foreach ($resourceTypes as $resourceType) {
                    $cityResource = new CityResource();
                    $cityResource->setResource($resourceType);
                    $cityResource->setCity($city);
                    $cityResource->setAmount(self::AMOUNT_OF_RESOURCES_EVERY_PLAYER_STARTS_WITH);
                    $em->persist($cityResource);
                    $em->flush();
                }

                $buildingRepository = $this->getDoctrine()->getRepository(Building::class);
                $buildingTypes = $buildingRepository->findAll();
                foreach ($buildingTypes as $buildingType) {
                    $cityBuilding = new CityBuildings();
                    $cityBuilding->setCity($city);
                    $cityBuilding->setBuilding($buildingType);
                    $cityBuilding->setLevel(0);
                    $em->persist($cityBuilding);
                    $em->flush();
                }

            }

            // ... do any other work - like sending them an email, etc
            // maybe set a "flash" success message for the user

            return $this->redirectToRoute('security_login');
        }

        return $this->render(
            'user/register.html.twig',
            array('form' => $form->createView())
        );
    }



    /**
     *
     * @Route("/profile", name="user_profile")
     */
    public function profileAction()
    {
        /** @var Player $player */
        $player = $this->getUser();
        return $this->render("user/profile.html.twig", [
            'player'=>$player,
            'cityId' => $this->getCity()
        ]);
    }
0
Martina_Shebova avatar Martina_Shebova 10 Точки

Не знам дали е свързано, но не мога да изтрия и кеша ....

  [Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "C:\Users\User\Desktop\Mars_BattleGround_2031\var\cache\de~\annotations\fe": .


cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debu
g] [--] <command>

 

0
RoYaL avatar RoYaL Trainer 6849 Точки

Рестартирай компютъра и отвори само конзола в папката и нищо друго ип робвай да изтриеш кеша. Има нещо, което държи някой файл отворен и не дава да се изтрие. Ако не е това - значи е проблем с правата на потребителя на компютъра.

0
b.yordanov avatar b.yordanov 146 Точки

Сигурна ли си, че изпращаш правилната парола?

The presented password is invalid.
0
Martina_Shebova avatar Martina_Shebova 10 Точки

Целият ми проблем идва от криптирането, не работи правилно. В security.yml му дадох вместо bcrypt, plaintext. Вкарвам паролата некриптирана и се логвам без проблем...

0
Martina_Shebova avatar Martina_Shebova 10 Точки

Аз plaintext го сложих, когато не ми работеше bcrypt, а не обратното.

0
b.yordanov avatar b.yordanov 146 Точки

Каква е дължината на колоната за парола в дб-то?

0
netbull avatar netbull -4 Точки
$password = $this->get('security.password_encoder')->encodePassword($player, $player->getPassword());

този ред е грешен..

идеята е следната 

1-во генерираш СОЛ, която учасвта в криптирането на паролата, нещо от сорта на:

$player->setSalt(substr(md5(uniqid(rand(), true)),0,22));

2-ро създават ХАШ на паролата encodePassword метода на очаква два параметъра plaintext парола и вторият е солта:

:

$hash = $this->get('security.password_encoder')->encodePassword($plaintextPassword, $player->getSalt());

и 3-то сетваш ХАША като парола на играча

$player->setPassword($hash);
0
19/12/2016 16:27:43
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.