<commit_before>﻿using System;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using Core.DomainModel;
using Core.DomainServices;

namespace Core.ApplicationServices
{
    public class UserService : IUserService
    {
        private readonly TimeSpan _ttl;
        private readonly string _baseUrl;
        private readonly IGenericRepository<User> _userRepository;
        private readonly IGenericRepository<Organization> _orgRepository;
        private readonly IGenericRepository<PasswordResetRequest> _passwordResetRequestRepository;
        private readonly IMailClient _mailClient;
        private readonly ICryptoService _cryptoService;

        public UserService(TimeSpan ttl,
            string baseUrl,
            IGenericRepository<User> userRepository, 
            IGenericRepository<Organization> orgRepository, 
            IGenericRepository<PasswordResetRequest> passwordResetRequestRepository, 
            IMailClient mailClient, 
            ICryptoService cryptoService)
        {
            _ttl = ttl;
            _baseUrl = baseUrl;
            _userRepository = userRepository;
            _orgRepository = orgRepository;
            _passwordResetRequestRepository = passwordResetRequestRepository;
            _mailClient = mailClient;
            _cryptoService = cryptoService;
        }

        public User AddUser(User user)
        {
            // hash his salt and default password
            user.Salt = _cryptoService.Encrypt(DateTime.Now + " spices");
#if DEBUG
            user.Password = _cryptoService.Encrypt("<PASSWORD>" + user.Salt); //TODO: Don't use default password
#else
            user.Password = _cryptoService.Encrypt(DateTime.Now + user.Salt);
#endif
            // user isn't an EF proxy class so navigation properites aren't set,
            // so we need to fetch org name ourself
            var org = _orgRepository.GetByKey(user.CreatedInId);

            user.DefaultOrganizationUnitId = org.GetRoot().Id;

            _userRepository.Insert(user);
            _userRepository.Save();

            var reset = GenerateResetRequest(user);
            var resetLink = _baseUrl + "#/reset-password/" + HttpUtility.UrlEncode(reset.Hash);

            const string subject = "Oprettelse af KITOS profil";
            var content = "<h2>Kære " + user.Name + "</h2>" +
                          "<p>Du er blevet oprettet, som bruger i KITOS (Kommunernes IT Overblikssystem) under organisationen " +
                          org.Name + ".</p>" +
                          "<p>Du bedes klikke <a href='" + resetLink +
                          "'>her</a>, hvor du første gang bliver bedt om at indtaste et nyt password for din KITOS profil.</p>" +
                          "<p>Linket udløber om " + _ttl.TotalDays + " dage.</p>";

            IssuePasswordReset(user, subject, content);

            return user;
        }

        public PasswordResetRequest IssuePasswordReset(User user, string subject, string content)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            var mailContent = "";
            var reset = new PasswordResetRequest();
            if (content == null)
            {
                reset = GenerateResetRequest(user);
                var resetLink = _baseUrl + "#/reset-password/" + HttpUtility.UrlEncode(reset.Hash);
                mailContent = "<p>Du har bedt om at få nulstillet dit password.</p>" +
                              "<p><a href='" + resetLink +
                              "'>Klik her for at nulstille passwordet for din KITOS profil</a>.</p>" +
                              "<p>Linket udløber om " + _ttl.TotalDays + " dage.</p>";
            }
            const string mailSubject = "Nulstilning af dit KITOS password";

            var message = new MailMessage()
                {
                    Subject = subject ?? mailSubject,
                    Body = content ?? mailContent,
                    IsBodyHtml = true,
                    BodyEncoding = Encoding.UTF8,
                };
            message.To.Add(user.Email);

            _mailClient.Send(message);

            return reset;
        }

        private PasswordResetRequest GenerateResetRequest(User user)
        {
            var now = DateTime.Now;
            var hash = _cryptoService.Encrypt(now + user.Email);

            var request = new PasswordResetRequest { Hash = hash, Time = now, UserId = user.Id, ObjectOwner = user, LastChangedByUser = user};<commit_msg>Added help link to email content<commit_after>﻿using System;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using Core.DomainModel;
using Core.DomainServices;

namespace Core.ApplicationServices
{
    public class UserService : IUserService
    {
        private readonly TimeSpan _ttl;
        private readonly string _baseUrl;
        private readonly IGenericRepository<User> _userRepository;
        private readonly IGenericRepository<Organization> _orgRepository;
        private readonly IGenericRepository<PasswordResetRequest> _passwordResetRequestRepository;
        private readonly IMailClient _mailClient;
        private readonly ICryptoService _cryptoService;

        public UserService(TimeSpan ttl,
            string baseUrl,
            IGenericRepository<User> userRepository, 
            IGenericRepository<Organization> orgRepository, 
            IGenericRepository<PasswordResetRequest> passwordResetRequestRepository, 
            IMailClient mailClient, 
            ICryptoService cryptoService)
        {
            _ttl = ttl;
            _baseUrl = baseUrl;
            _userRepository = userRepository;
            _orgRepository = orgRepository;
            _passwordResetRequestRepository = passwordResetRequestRepository;
            _mailClient = mailClient;
            _cryptoService = cryptoService;
        }

        public User AddUser(User user)
        {
            // hash his salt and default password
            user.Salt = _cryptoService.Encrypt(DateTime.Now + " spices");
#if DEBUG
            user.Password = _cryptoService.Encrypt("<PASSWORD>" + user.Salt); //TODO: Don't use default password
#else
            user.Password = _cryptoService.Encrypt(DateTime.Now + user.Salt);
#endif
            // user isn't an EF proxy class so navigation properites aren't set,
            // so we need to fetch org name ourself
            var org = _orgRepository.GetByKey(user.CreatedInId);

            user.DefaultOrganizationUnitId = org.GetRoot().Id;

            _userRepository.Insert(user);
            _userRepository.Save();

            var reset = GenerateResetRequest(user);
            var resetLink = _baseUrl + "#/reset-password/" + HttpUtility.UrlEncode(reset.Hash);

            const string subject = "Oprettelse af KITOS profil";
            var content = "<h2>Kære " + user.Name + "</h2>" +
                          "<p>Du er blevet oprettet, som bruger i KITOS (Kommunernes IT Overblikssystem) under organisationen " +
                          org.Name + ".</p>" +
                          "<p>Du bedes klikke <a href='" + resetLink +
                          "'>her</a>, hvor du første gang bliver bedt om at indtaste et nyt password for din KITOS profil.</p>" +
                          "<p>Linket udløber om " + _ttl.TotalDays + " dage.</p>" +
                          "<p><a href='" + _baseUrl + "docs/Vejledning%20til%20slutbrugeren.pdf'>Klik her for at få Hjælp til log ind og brugerkonto</a></p>";

            IssuePasswordReset(user, subject, content);

            return user;
        }

        public PasswordResetRequest IssuePasswordReset(User user, string subject, string content)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            var mailContent = "";
            var reset = new PasswordResetRequest();
            if (content == null)
            {
                reset = GenerateResetRequest(user);
                var resetLink = _baseUrl + "#/reset-password/" + HttpUtility.UrlEncode(reset.Hash);
                mailContent = "<p>Du har bedt om at få nulstillet dit password.</p>" +
                              "<p><a href='" + resetLink +
                              "'>Klik her for at nulstille passwordet for din KITOS profil</a>.</p>" +
                              "<p>Linket udløber om " + _ttl.TotalDays + " dage.</p>" +
                              "<p><a href='" + _baseUrl + "docs/Vejledning%20til%20slutbrugeren.pdf'>Klik her for at få Hjælp til log ind og brugerkonto</a></p>";
            }
            const string mailSubject = "Nulstilning af dit KITOS password";

            var message = new MailMessage()
                {
                    Subject = subject ?? mailSubject,
                    Body = content ?? mailContent,
                    IsBodyHtml = true,
                    BodyEncoding = Encoding.UTF8,
                };
            message.To.Add(user.Email);

            _mailClient.Send(message);

            return reset;
        }

        private PasswordResetRequest GenerateResetRequest(User user)
        {
            var now = DateTime.Now;
            var hash = _cryptoService.Encrypt(now + user.Email);

            var request = new PasswordResetRequest { Hash = hash, Time = now, UserId = user.Id, ObjectOwner = user, LastChangedByUser = user};
{'fraction_non_alphanumeric': 0.08664336405041839, 'fraction_numerical': 0.0014828937612541043, 'mean_word_length': 1.9432668329177056, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 61, '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': '3384962', 'n_tokens_mistral': 2450, 'n_tokens_neox': 2389, 'n_words': 648}