<commit_before><?php

/**
 * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project.
 * @copyright 2017 subtitulamos.tv
 */

namespace App\Controllers;

use \Psr\Container\ContainerInterface;
use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Message\ResponseInterface;
use \Dflydev\FigCookies\FigResponseCookies;
use \Dflydev\FigCookies\SetCookie;

use \Doctrine\ORM\EntityManager;
use \Respect\Validation\Validator as v;
use \App\Services\Auth;
use \App\Entities\User;

class LoginController
{
    // TODO: Export to some config file
    const MINIMUM_PASSWORD_LENGTH = 8;
    const MINIMUM_USER_LENGTH = 4;

    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Attempt to login a user
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function login(ServerRequestInterface $request, ResponseInterface $response, EntityManager $em, Auth $auth)
    {
        $username = $request->getParam('username', '');
        $password = $request->getParam('password', '');
        $remember = $request->getParam('remember', '') == 'on';

        if (!$username || !$password) {
            return $response->withStatus(400);
        }
        
        $user = $em->getRepository("App:User")->findOneByUsername($username);
        if (!$user || !\password_verify($password, $user->getPassword())) {
            return $response->withJson(['Usuario o contraseña incorrectos'], 403);
        }

        $auth->log($user, $remember);
        if ($remember) {
            $response = FigResponseCookies::set($response, SetCookie::create('remember')->withValue($auth->getUser()->getRememberToken())->rememberForever());
        }

        return $response->withStatus(200);
    }

    public function register(ServerRequestInterface $request, ResponseInterface $response, EntityManager $em)
    {
        $username = $request->getParam('username', '');
        $password = $request->getParam('password', '');
        $password_confirmation = $request->getParam('password_confirmation', false); // TODO: Implement
        $email = $request->getParam('email', '');
        $terms = $request->getParam('terms', false);

        $errors = [];
        if (!$terms) {
            $errors[] = ["terms" => "Debes aceptar los términos y condiciones"];
        }

        if (!v::alnum()->noWhitespace()->length(3, 24)->validate($username)) {
            $errors[] = ["username" => "El nombre de usuario no puede tener caracteres especiales o espacios, y debe tener entre 3 y 24 caracteres"];
        } elseif ($em->getRepository("App:User")->findByUsername($username) != null) {
            $errors[] = ["username" => "El nombre de usuario ya está en uso"];
        }<commit_msg>Allow underscores on usernames<commit_after><?php

/**
 * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project.
 * @copyright 2017 subtitulamos.tv
 */

namespace App\Controllers;

use \Psr\Container\ContainerInterface;
use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Message\ResponseInterface;
use \Dflydev\FigCookies\FigResponseCookies;
use \Dflydev\FigCookies\SetCookie;

use \Doctrine\ORM\EntityManager;
use \Respect\Validation\Validator as v;
use \App\Services\Auth;
use \App\Entities\User;

class LoginController
{
    // TODO: Export to some config file
    const MINIMUM_PASSWORD_LENGTH = 8;
    const MINIMUM_USER_LENGTH = 4;

    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Attempt to login a user
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function login(ServerRequestInterface $request, ResponseInterface $response, EntityManager $em, Auth $auth)
    {
        $username = $request->getParam('username', '');
        $password = $request->getParam('password', '');
        $remember = $request->getParam('remember', '') == 'on';

        if (!$username || !$password) {
            return $response->withStatus(400);
        }
        
        $user = $em->getRepository("App:User")->findOneByUsername($username);
        if (!$user || !\password_verify($password, $user->getPassword())) {
            return $response->withJson(['Usuario o contraseña incorrectos'], 403);
        }

        $auth->log($user, $remember);
        if ($remember) {
            $response = FigResponseCookies::set($response, SetCookie::create('remember')->withValue($auth->getUser()->getRememberToken())->rememberForever());
        }

        return $response->withStatus(200);
    }

    public function register(ServerRequestInterface $request, ResponseInterface $response, EntityManager $em)
    {
        $username = $request->getParam('username', '');
        $password = $request->getParam('password', '');
        $password_confirmation = $request->getParam('password_confirmation', false); // TODO: Implement
        $email = $request->getParam('email', '');
        $terms = $request->getParam('terms', false);

        $errors = [];
        if (!$terms) {
            $errors[] = ["terms" => "Debes aceptar los términos y condiciones"];
        }

        if (!v::alnum('_')->noWhitespace()->length(3, 24)->validate($username)) {
            $errors[] = ["username" => "El nombre de usuario no puede tener caracteres especiales o espacios, y debe tener entre 3 y 24 caracteres"];
        } elseif ($em->getRepository("App:User")->findByUsername($username) != null) {
            $errors[] = ["username" => "El nombre de usuario ya está en uso"];
        }
{'fraction_non_alphanumeric': 0.14372061786433848, 'fraction_numerical': 0.007387508394895903, 'mean_word_length': 3.2069209039548023, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6941303', 'n_tokens_mistral': 1725, 'n_tokens_neox': 1657, 'n_words': 403}