Jump to content

Recommended Posts

Posted

As the title say i will share with you one password manager for Acis 370. Credits: Sweets( Ive just made the imports right  and the necessary changes in case that someone didnt know and have problem).

 

Go to : net.sf.l2j.gameserver.model.actor.instance and create a new class with name:  L2PasswordInstance

 

/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package net.sf.l2j.gameserver.model.actor.instance;
 
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Base64;
import java.util.StringTokenizer;
 
import net.sf.l2j.commons.concurrent.ThreadPool;
 
import net.sf.l2j.L2DatabaseFactory;
import net.sf.l2j.gameserver.model.actor.template.NpcTemplate;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
 
/**
 * @author SweeTs
 */
public class L2PasswordInstance extends Folk
{
    public L2PasswordInstance(int objectId, NpcTemplate template)
    {
        super(objectId, template);
    }
   
    @Override
    public void onBypassFeedback(Player player, String command)
    {
        if (command.startsWith("change_password"))
        {
            StringTokenizer st = new StringTokenizer(command);
            st.nextToken();
           
            String newPass = "";
            String repeatNewPass = "";
           
            try
            {
                if (st.hasMoreTokens())
                {
                    newPass = st.nextToken();
                    repeatNewPass = st.nextToken();
                }
            }
            catch (Exception e)
            {
                player.sendMessage("Please fill all the blanks before requesting for a password change.");
                return;
            }
           
            if (!conditions(newPass, repeatNewPass, player))
                return;
           
            changePassword(newPass, repeatNewPass, player);
        }
    }
   
    private static boolean conditions(String newPass, String repeatNewPass, Player player)
    {
        if (newPass.length() < 3)
        {
            player.sendMessage("The new password is too short!");
            return false;
        }
        else if (newPass.length() > 45)
        {
            player.sendMessage("The new password is too long!");
            return false;
        }
        else if (!newPass.equals(repeatNewPass))
        {
            player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.PASSWORD_ENTERED_INCORRECT2));
            return false;
        }
       
        return true;
    }
   
    @Override
    public void showChatWindow(Player activeChar)
    {
        final NpcHtmlMessage html = new NpcHtmlMessage(0);
        final StringBuilder sb = new StringBuilder();
       
        sb.append("<html><title>Account Manager</title>");
        sb.append("<body><center>");
        sb.append("<img src=\"L2UI_CH3.herotower_deco\" width=256 height=32><br>");
        sb.append("New password: <edit var=\"new\" width=100 height=15><br>");
        sb.append("Repeat: <edit var=\"repeatnew\" width=100 height=15><br>");
        sb.append("<img src=\"L2UI_CH3.herotower_deco\" width=256 height=32><br><br>");
        sb.append("<a action=\"bypass -h npc_%objectId%_change_password $new $repeatnew\">Change password</a>");
        sb.append("</center></body></html>");
       
        html.setHtml(sb.toString());
        html.replace("%objectId%", getObjectId());
        activeChar.sendPacket(html);
    }
   
    private static void changePassword(String newPass, String repeatNewPass, Player activeChar)
    {
        try (Connection con = L2DatabaseFactory.getInstance().getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE accounts SET password=? WHERE login=?"))
        {
            byte[] newPassword = MessageDigest.getInstance("SHA").digest(newPass.getBytes("UTF-8"));
           
            ps.setString(1, Base64.getEncoder().encodeToString(newPassword));
            ps.setString(2, activeChar.getAccountName());
            ps.executeUpdate();
           
            activeChar.sendMessage("Congratulations! Your password has been changed. You will now be disconnected for security reasons. Please login again.");
            ThreadPool.schedule(() -> activeChar.logout(false), 3000);
        }
        catch (Exception e)
        {
            _log.warning("There was an error while updating account:" + e);
        }
    }
}

 After you are passing this the only thing that you have to do is create a new npc with type: L2Password.

 

HAVE A NICE DAY GUYS :)

 

 

 

 

Posted
7 hours ago, thepsolartek said:

 Credits: Sweets

 

 

 

1 hour ago, Rootware said:

Forgot about credits and allowing rights for sharing.

 


/**
 * @author SweeTs
 */

 

he did actually

Posted

As you can see in the start of this topic i ve already told that the code didnt belong to me but Sweets. The only thing i did is to make the imports correct for acis 370 and do the necessary changes where the code has error. I did that for members that didnt know how to use eclipse very well and what changes are done in acis 370. 

  • 1 month later...
  • 3 months later...
Posted
2 hours ago, sacrifice said:

what is folk

Normally it's L2NpcInstance. Adjust to your pack - simply check another instance file, see what does it extends.

Posted

I compile with this code but when I use instance L2Password on a NPC I dont have interface in html windows

 

 

/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2jfree.gameserver.gameobjects.instance;
 
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Base64;
import java.util.StringTokenizer;
 
import com.l2jfree.gameserver.ThreadPoolManager;
import com.l2jfree.gameserver.gameobjects.L2Npc;
import com.l2jfree.gameserver.gameobjects.L2Player;
import com.l2jfree.L2DatabaseFactory;
import com.l2jfree.gameserver.gameobjects.templates.L2NpcTemplate;
import com.l2jfree.gameserver.network.SystemMessageId;
import com.l2jfree.gameserver.network.packets.server.NpcHtmlMessage;
import com.l2jfree.gameserver.network.SystemMessageId;
 

 
/**
 * @author SweeTs
 */
public class L2PasswordInstance extends L2Npc
{
    public L2PasswordInstance(int objectId, L2NpcTemplate template)
    {
        super(objectId, template);
    }
   
    @Override
    public void onBypassFeedback(L2Player player, String command)
    {
        if (command.startsWith("change_password"))
        {
            StringTokenizer st = new StringTokenizer(command);
            st.nextToken();
           
            String newPass = "";
            String repeatNewPass = "";
           
            try
            {
                if (st.hasMoreTokens())
                {
                    newPass = st.nextToken();
                    repeatNewPass = st.nextToken();
                }
            }
            catch (Exception e)
            {
                player.sendMessage("Please fill all the blanks before requesting for a password change.");
                return;
            }
           
            if (!conditions(newPass, repeatNewPass, player))
                return;
           
            changePassword(newPass, repeatNewPass, player);
        }
    }
   
    private static boolean conditions(String newPass, String repeatNewPass, L2Player player)
    {
        if (newPass.length() < 3)
        {
            player.sendMessage("The new password is too short!");
            return false;
        }
        else if (newPass.length() > 45)
        {
            player.sendMessage("The new password is too long!");
            return false;
        }
        else if (!newPass.equals(repeatNewPass))
        {
			player.sendPacket(SystemMessageId.REGISTRATION_PERIOD_OVER);
            return false;
        }
       
        return true;
    }
   
    @Override
    public void showChatWindow(L2Player activeChar)
    {
        final NpcHtmlMessage html = new NpcHtmlMessage(0);
        final StringBuilder sb = new StringBuilder();
       
        sb.append("<html><title>Account Manager</title>");
        sb.append("<body><center>");
        sb.append("<img src=\"L2UI_CH3.herotower_deco\" width=256 height=32><br>");
        sb.append("New password: <edit var=\"new\" width=100 height=15><br>");
        sb.append("Repeat: <edit var=\"repeatnew\" width=100 height=15><br>");
        sb.append("<img src=\"L2UI_CH3.herotower_deco\" width=256 height=32><br><br>");
        sb.append("<a action=\"bypass -h npc_%objectId%_change_password $new $repeatnew\">Change password</a>");
        sb.append("</center></body></html>");
       
        html.setHtml(sb.toString());
        html.replace("%objectId%", getObjectId());
        activeChar.sendPacket(html);
    }
   
    private static void changePassword(String newPass, String repeatNewPass, L2Player activeChar)
    {
        try (Connection con = L2DatabaseFactory.getInstance().getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE accounts SET password=? WHERE login=?"))
        {
            byte[] newPassword = MessageDigest.getInstance("SHA").digest(newPass.getBytes("UTF-8"));
           
            ps.setString(1, Base64.getEncoder().encodeToString(newPassword));
            ps.setString(2, activeChar.getAccountName());
            ps.executeUpdate();
           
            activeChar.sendMessage("Congratulations! Your password has been changed. You will now be disconnected for security reasons. Please login again.");
//            ThreadPool.schedule(() -> activeChar.logout(false), 3000);
        }
        catch (Exception e)
        {
            _log.warn("There was an error while updating account:" + e);
        }
    }
}

 

  • 5 months later...
  • 2 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • ⚡ PRIVATE L2 SOURCE CODE & CONTRACT BUILDS Essence / Classic / High Five / Main GOD Private enterprise-level Lineage 2 development for serious projects ENGLISH For many years our studio was known mostly for public Lineage 2 builds and public development services. However, for many years now our main focus has been private development for serious projects and investors. Over time we moved away from mass-market development and focused on quality, stability, deep detailing and long-term project support. This approach allowed us to create products of a completely different level designed for large live-projects and long-term operation. Today, in addition to our old public builds, we also offer private enterprise-level solutions developed by a full professional team with many years of Lineage 2 experience. We work only with serious teams, investors and projects that understand the value of quality private development. ◆ L2 Essence — Private Builds & Source Code Latest protocols: 557–559+ Available only on a long-term contract basis. Includes: • 100% official content implementation • Custom interface systems • Active protocol updates while the contract is active • Full access to the project source code • Full technical support for the project • Bug fixing and feature development • Help with launch and long-term server development • A full professional development team working on your project • Java developers, datapack developers and project management • Many years of experience with large live projects • Long-term private cooperation and support Contract terms: Start: 10,000 USD Monthly contract: 3,000 USD / month Older Essence source code available for direct purchase: • Protocols 507–520 — 10,000 USD • Protocols 474–502 — 7,000 USD • Protocols 447–464 Seven Signs — 5,000 USD • Protocol 388 Crusade — 2,500 USD Full details: https://mmore.dev/en/essense2.html ◆ L2 Classic — Private Builds & Source Code Latest protocols: 557–559+ Available only on a long-term contract basis. Includes: • 100% official content implementation • Custom interface systems • Active protocol updates while the contract is active • Full access to the project source code • Full technical support for the project • Bug fixing and feature development • Help with launch and long-term server development • A full professional development team working on your project • Java developers, datapack developers and project management • Many years of experience with large live projects • Long-term private cooperation and support Contract terms: Start: 10,000 USD Monthly contract: 3,000 USD / month Classic source code available for direct purchase: • Classic 542 protocol — 15,000 USD • Classic 520 protocol — 12,000 USD • Classic 507 protocol — 10,000 USD • Classic 286 protocol — 8,000 USD Negotiable. Contract support is available. Full details: https://mmore.dev/en/classic2.html ◆ High Five — Private Build Private High Five build with years of live-server experience. Includes: • 100% official content • Full access to the project source code • Full technical support for the project • Bug fixing and feature development • Help with launch and long-term server development • A full professional development team working on your project • Java developers, datapack developers and project management • Many years of experience with large live projects • Long-term private cooperation and support Contract terms: Start: 3,000 USD Monthly contract: 3,000 USD / month Full details: https://mmore.dev/en/hf2.html ◆ Main / GOD — In Development Development of the Main / GOD branch, protocol 559+, has started. Pre-orders and sponsorship discussions are open. We accept only a limited number of projects from different regions with maximum regional exclusivity for each partner. IMPORTANT The latest Essence and Classic protocols are available only through long-term private contracts. Direct source code sales are available only for older protocols. If you need the newest protocols, active development, updates and support — contract work is the correct option. РУССКИЙ Ранее наша студия в основном занималась публичными сборками Lineage 2 и массовыми услугами разработки. Однако уже много лет основное направление нашей работы — приватная разработка для серьёзных проектов и инвесторов. Со временем мы ушли от работы на массовость и сосредоточились на качестве, стабильности, глубокой детализации и долгосрочном развитии проектов. Именно такой подход позволил нам создать продукты совершенно другого уровня, рассчитанные на крупные live-проекты и долгосрочную эксплуатацию. Сегодня помимо наших старых публичных сборок мы также предлагаем приватные enterprise-level решения, над которыми работает полноценная команда профессиональных разработчиков с многолетним опытом работы в сфере Lineage 2. Мы работаем только с серьёзными командами, инвесторами и проектами, которые понимают ценность качественной приватной разработки. ◆ L2 Essence — приватные сборки и исходники Актуальные протоколы: 557–559+ Доступны только на контрактной основе. Входит: • 100% реализация официального контента • Кастомные интерфейсные системы • Обновления протоколов на время действия контракта • Полный доступ к исходному коду проекта • Полная техническая поддержка проекта • Исправление ошибок и доработка функционала • Помощь с запуском и развитием сервера • Работа целой команды профессионалов над вашим проектом • Java-разработчики, datapack-разработчики и project management • Многолетний опыт работы с крупными live-проектами • Долгосрочная приватная работа и сопровождение проекта Условия контракта: Стартовый взнос: 10,000 USD Ежемесячно: 3,000 USD / месяц Старые протоколы Essence для прямой покупки исходников: • Протоколы 507–520 — 10,000 USD • Протоколы 474–502 — 7,000 USD • Протоколы 447–464 Seven Signs — 5,000 USD • Протокол 388 Crusade — 2,500 USD Подробнее: https://mmore.dev/essense2.html ◆ L2 Classic — приватные сборки и исходники Актуальные протоколы: 557–559+ Доступны только на контрактной основе. Входит: • 100% реализация официального контента • Кастомные интерфейсные системы • Обновления протоколов на время действия контракта • Полный доступ к исходному коду проекта • Полная техническая поддержка проекта • Исправление ошибок и доработка функционала • Помощь с запуском и развитием сервера • Работа целой команды профессионалов над вашим проектом • Java-разработчики, datapack-разработчики и project management • Многолетний опыт работы с крупными live-проектами • Долгосрочная приватная работа и сопровождение проекта Условия контракта: Стартовый взнос: 10,000 USD Ежемесячно: 3,000 USD / месяц Исходники Classic для прямой покупки: • Classic 542 protocol — 15,000 USD • Classic 520 protocol — 12,000 USD • Classic 507 protocol — 10,000 USD • Classic 286 protocol — 8,000 USD Торг возможен. Контрактная поддержка доступна. Подробнее: https://mmore.dev/classic2.html ◆ High Five — приватная сборка Приватная High Five сборка с многолетним опытом работы на живых проектах. Входит: • 100% официальный контент • Полный доступ к исходному коду проекта • Полная техническая поддержка проекта • Исправление ошибок и доработка функционала • Помощь с запуском и развитием сервера • Работа целой команды профессионалов над вашим проектом • Java-разработчики, datapack-разработчики и project management • Многолетний опыт работы с крупными live-проектами • Долгосрочная приватная работа и сопровождение проекта Условия контракта: Стартовый взнос: 3,000 USD Ежемесячно: 3,000 USD / месяц Подробнее: https://mmore.dev/hf2.html ◆ Main / GOD — в разработке Мы начали разработку ветки Main / GOD, протокол 559+. Открыты предварительные обсуждения, предзаказы и спонсорские контракты. Принимается ограниченное количество проектов из разных регионов мира с максимальной региональной эксклюзивностью для каждого партнёра. ВАЖНО Самые актуальные протоколы Essence и Classic доступны только на долгосрочном контракте. Прямая продажа исходного кода доступна только для более старых протоколов. Если вам нужны самые свежие версии, развитие, обновления и поддержка — выбирайте контрактную работу с нашей командой. CONTACTS / КОНТАКТЫ Telegram:  @L2scripts Microsoft Teams:   l2-scripts.com@outlook.com      Old Skype account: Urchika E-mail:    L2scripts.com@gmail.com IMPORTANT All discussions, project details, examples, testing access, source code demonstrations, technical discussions and cooperation terms are discussed strictly in Telegram only. We do not discuss private development publicly on the forum. Telegram is the main and preferred communication platform for all serious inquiries. ВАЖНО Все обсуждения, детали проектов, примеры, предоставление тестирования, демонстрации исходников, технические вопросы и условия сотрудничества обсуждаются строго только в Telegram. Публично на форуме приватная разработка не обсуждается. Telegram — основная и приоритетная платформа для связи по всем серьёзным вопросам. All questions are discussable. We work for the best Lineage 2 projects in the world.
    • cRazy??? If i just say good job its not even fair....
    • τι εκανες εκει παλι ρε τρελάρα; 🤣   welcome back mate, happy seeing you online again, well thats beyond l2 needs for sure and It’s rare to see anyone pushing Interlude this far technically anymore without trying to monetize it. definitely interested in seeing the source whenever you're ready to share it! keep it up!
    • your only choice brother cmon https://www.l2jsunrise.com/
  • Topics

×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..