<commit_before>﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using System.Web.Providers.Entities;
using AttributeRouting.Web.Http;
using AutoMapper;
using MiniTrello.Api.Models;
using MiniTrello.Domain.Entities;
using MiniTrello.Domain.Services;
using RestSharp;
using Session = System.Web.Providers.Entities.Session;

namespace MiniTrello.Api.Controllers
{
    public class AccountController : ApiController
    {
        
        readonly IReadOnlyRepository _readOnlyRepository;
        readonly IWriteOnlyRepository _writeOnlyRepository;
        readonly IMappingEngine _mappingEngine;

        public AccountController(IReadOnlyRepository readOnlyRepository, IWriteOnlyRepository writeOnlyRepository,
            IMappingEngine mappingEngine)
        {
            _readOnlyRepository = readOnlyRepository;
            _writeOnlyRepository = writeOnlyRepository;
            _mappingEngine = mappingEngine;
        }

        public static IRestResponse SendSimpleMessage(string mail, string message)
        {
            RestClient client = new RestClient();
            client.BaseUrl = "https://api.mailgun.net/v2";
            client.Authenticator =
                    new HttpBasicAuthenticator("api",
                                               "key-<KEY>");
            RestRequest request = new RestRequest();
            request.AddParameter("domain",
                                 "app17493.mailgun.org", ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", "MinitrelloBot <<EMAIL>>");
            request.AddParameter("to", mail);
            request.AddParameter("subject", "Welcome to MiniTrello");
            request.AddParameter("text", message);
            request.Method = Method.POST;
            return client.Execute(request);
        }


        [HttpPost]
        [POST("login")]
        public AuthenticationModel Login([FromBody] AccountLoginModel model)
        {
            var account = _readOnlyRepository.First<Account>(account1 => account1.Email == model.Email && account1.Password == <PASSWORD>Password.EncryptString(model.Password, "password"));
            if (account != null)
            {
                var newSession = new Sessions
                {
                    User = account,
                    ExpireDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second).AddHours(24), 
                    LoginDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second),
                    Token = Guid.NewGuid().ToString()
                };
                
                var sessionCreated = _writeOnlyRepository.Create(newSession);
                
                return new AuthenticationModel(){Token = sessionCreated.Token};
            }
            
            throw new BadRequestException(
                "Usuario o clave incorrecto");
        }

        [POST("sendEmail")]
        public HttpResponseMessage sendEmail([FromBody] SendEmailModel model)
        {
            SendSimpleMessage(model.Email, "Please click in the link to redirect you... *link not implemented*");
            return new HttpResponseMessage(HttpStatusCode.OK);
        }

        [POST("register")]
        public HttpResponseMessage Register([FromBody] AccountRegisterModel model)
        {
            
            
            
            Account accountCreated = null;
            if (PasswordIsValid(model.Password, model.ConfirmPassword) && EmailIsValid(model.Email))
            {
                Account account = _mappingEngine.Map<AccountRegisterModel, Account>(model);
                account.Password = EncryptPassword.EncryptString(account.Password, "password");
                accountCreated = _writeOnlyRepository.Create(account);
            }

            
            if (accountCreated != null)
            {
                SendSimpleMessage(accountCreated.Email, "Hi there, I'm happy that you decide to join our MiniTrello community. :)");
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            throw new BadRequestException("Hubo un error al guardar el usuario");
        }

        private bool PasswordIsValid(string password, string confirmPassword)
        {
            if (password != confirmPassword)
            {
                throw new BadRequestException("Claves no son iguales");
            }

            if (password.Any(char.IsDigit) && password.Length > 5)
            {
                return true;
            }
            throw new BadRequestException("La clave debe contener por lo menos 1 numero y debe ser de 6 caracteres o mas.");
        }

        [POST("/Account/ChangePassword/{token}")]<commit_msg>confirm password verification added<commit_after>﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using System.Web.Providers.Entities;
using AttributeRouting.Web.Http;
using AutoMapper;
using MiniTrello.Api.Models;
using MiniTrello.Domain.Entities;
using MiniTrello.Domain.Services;
using RestSharp;
using Session = System.Web.Providers.Entities.Session;

namespace MiniTrello.Api.Controllers
{
    public class AccountController : ApiController
    {
        
        readonly IReadOnlyRepository _readOnlyRepository;
        readonly IWriteOnlyRepository _writeOnlyRepository;
        readonly IMappingEngine _mappingEngine;

        public AccountController(IReadOnlyRepository readOnlyRepository, IWriteOnlyRepository writeOnlyRepository,
            IMappingEngine mappingEngine)
        {
            _readOnlyRepository = readOnlyRepository;
            _writeOnlyRepository = writeOnlyRepository;
            _mappingEngine = mappingEngine;
        }

        public static IRestResponse SendSimpleMessage(string mail, string message)
        {
            RestClient client = new RestClient();
            client.BaseUrl = "https://api.mailgun.net/v2";
            client.Authenticator =
                    new HttpBasicAuthenticator("api",
                                               "key-<KEY>");
            RestRequest request = new RestRequest();
            request.AddParameter("domain",
                                 "app17493.mailgun.org", ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", "MinitrelloBot <<EMAIL>>");
            request.AddParameter("to", mail);
            request.AddParameter("subject", "Welcome to MiniTrello");
            request.AddParameter("text", message);
            request.Method = Method.POST;
            return client.Execute(request);
        }


        [HttpPost]
        [POST("login")]
        public AuthenticationModel Login([FromBody] AccountLoginModel model)
        {
            var account = _readOnlyRepository.First<Account>(account1 => account1.Email == model.Email && account1.Password == EncryptPassword.EncryptString(model.Password, "password"));
            if (account != null)
            {
                var newSession = new Sessions
                {
                    User = account,
                    ExpireDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second).AddHours(24), 
                    LoginDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second),
                    Token = Guid.NewGuid().ToString()
                };
                
                var sessionCreated = _writeOnlyRepository.Create(newSession);
                
                return new AuthenticationModel(){Token = sessionCreated.Token};
            }
            
            throw new BadRequestException(
                "Usuario o clave incorrecto");
        }

        [POST("sendEmail")]
        public HttpResponseMessage sendEmail([FromBody] SendEmailModel model)
        {
            SendSimpleMessage(model.Email, "Please click in the link to redirect you... *link not implemented*");
            return new HttpResponseMessage(HttpStatusCode.OK);
        }

        [POST("register")]
        public HttpResponseMessage Register([FromBody] AccountRegisterModel model)
        {
            
            
            
            Account accountCreated = null;
            if (PasswordIsValid(model.Password, model.ConfirmPassword) && EmailIsValid(model.Email))
            {
                Account account = _mappingEngine.Map<AccountRegisterModel, Account>(model);
                account.Password = EncryptPassword.EncryptString(account.Password, "password");
                accountCreated = _writeOnlyRepository.Create(account);
            }

            
            if (accountCreated != null)
            {
                SendSimpleMessage(accountCreated.Email, "Hi there, I'm happy that you decide to join our MiniTrello community. :)");
                SendSimpleMessage("<EMAIL>", model.FirstName+" se registro en MiniTrello! :) Un usuario mas! ");
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            throw new BadRequestException("Hubo un error al guardar el usuario");
        }

        private bool PasswordIsValid(string password, string confirmPassword)
        {
            if (password != confirmPassword)
            {
                throw new BadRequestException("Claves no son iguales");
            }

            if (password.Any(char.IsDigit) && password.Length > 5)
            {
                return true;
            }
            throw new BadRequestException("La clave debe contener por lo menos 1 numero y debe ser de 6 caracteres o mas.");
        }

        [POST("/Account/ChangePassword/{token}")]
{'fraction_non_alphanumeric': 0.08861756597085467, 'fraction_numerical': 0.0027569909413154787, 'mean_word_length': 2.111825980392157, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1077176', 'n_tokens_mistral': 2459, 'n_tokens_neox': 2394, 'n_words': 551}