1
0
mirror of https://e.coding.net/circlecloud/AuthMe.git synced 2024-12-21 06:38:55 +00:00

init project...

Signed-off-by: 502647092 <jtb1@163.com>
This commit is contained in:
502647092 2015-10-12 15:26:15 +08:00
commit a1176afa15
165 changed files with 19619 additions and 0 deletions

125
.gitignore vendored Normal file
View File

@ -0,0 +1,125 @@
# Created by https://www.gitignore.io
### Java ###
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
#*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
### Eclipse ###
*.pydevproject
.metadata
.gradle
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# PDT-specific
.buildpath
# sbteclipse plugin
.target
# TeXlipse plugin
.texlipse
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
.nb-gradle/

19
.travis.yml Normal file
View File

@ -0,0 +1,19 @@
sudo: false
language: java
jdk: oraclejdk7
cache:
directories:
- '$HOME/.m2/repository'
script:
- mvn clean install -B && mvn clean -B
notifications:
webhooks:
urls:
- https://webhooks.gitter.im/e/952357dbd9d3cea70fd5
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: false # default: false

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

139
README.md Normal file
View File

@ -0,0 +1,139 @@
<p align="center"><img src="http://i61.tinypic.com/291dm49.png"></p>
<p align="center"><strong>The most used authentication plugin for CraftBukkit/Spigot!</strong></p>
<hr>
#####Development tools:
- DEVELOPMENT TEAM REPO (<strong>please send PRs here!</strong>): <a href="https://github.com/AuthMe-Team/AuthMeReloaded">Github Development Page</a>
- Developers ChatRoom: [![Join the chat at https://gitter.im/Xephi/AuthMeReloaded](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Xephi/AuthMeReloaded?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
- Build status: [![Build Status](https://travis-ci.org/Xephi/AuthMeReloaded.svg?branch=master)](https://travis-ci.org/Xephi/AuthMeReloaded) [![Dependency Status](https://www.versioneye.com/user/projects/55bab9e8653762002000190a/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55bab9e8653762002000190a)
- Build status (CircleCI): [![Circle CI](https://circleci.com/gh/Xephi/AuthMeReloaded.svg?style=svg)](https://circleci.com/gh/Xephi/AuthMeReloaded)
- Issue Tracking : [![Stories in Ready](https://badge.waffle.io/Xephi/AuthMeReloaded.png?label=ready&title=Ready)](https://waffle.io/Xephi/AuthMeReloaded) [![Stories in Bugs](https://badge.waffle.io/Xephi/AuthMeReloaded.png?label=bugs&title=Bugs)](https://waffle.io/Xephi/AuthMeReloaded) [![Stories in In%20Progress](https://badge.waffle.io/Xephi/AuthMeReloaded.png?label=in%20progress&title=In%20Progress)](https://waffle.io/Xephi/AuthMeReloaded)
- Build Server (<strong>DEVELOPMENT BUILDS</strong>): <a href="http://ci.xephi.fr/job/AuthMeReloaded">Xephi's Jenkins</a>
- JavaDocs: <a href="http://xephi.github.io/AuthMeReloaded/index.html">AuthMe Javadoc</a>
- Maven Repo: <a href="http://ci.xephi.fr/plugin/repository/everything/">AuthMe Repo</a>
#####Statistics:
McStats: http://mcstats.org/plugin/AuthMe
<img src="http://i.mcstats.org/AuthMe/Global+Statistics.borderless.png">
<img src="http://i.mcstats.org/AuthMe/Rank.borderless.png">
<img src="http://i.mcstats.org/AuthMe/Version+Demographics.borderless.png">
<hr>
#####Compiling Requirements:
>- JDK 1.7
>- Maven
>- Git/Github (Optional)
#####How to compile the project:
>- Clone the project with Git/Github
>- Execute command "mvn clean install"
#####Running Requirements:
>- Java 1.7 (should work also with Java 1.8)
>- Spigot or CraftBukkit (1.7.10 or 1.8.X)
>- Vault
>- Protocollib
<hr>
###Plugin Description:
#####"The best authentication plugin for the Bukkit/Spigot API!"
<p>Prevent username stealing on your server! Full compatible with UUIDs and Craftbukkit/Spigot 1.8.X!<br>
Use it to secure your Offline mode server or to incrase your Online mode server's protection!</p>
<p>AuthMeReloaded disallows players who aren't authenticated to do actions like placing blocks, moving,<br>
typing commands or use the inventory. It can also kick players with uncommon long or short player names or kick players from banned countries.</p>
<p>With the Session Login feature you don't have to execute the authentication command everytime you connect to the server! Each command and every feature can be enabled or disabled from our well structured configuration file.</p>
<p>You can also create your own translation file and, if you want, you can share it with us! :)</p>
####Features:
<ul>
<li><strong>E-Mail Recovery System !!!</strong></li>
<li>Username spoofing protection.</li>
<li>Countries Whitelist/Blacklist! <a href="http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/">(countries codes)</a></li>
<li><strong>Built-in AntiBot System!</strong></li>
<li><strong>ForceLogin Feature: Admins can login with all account via console command!</strong></li>
<li><strong>Avoid the "Logged in from another location" message!</strong></li>
<li>Session Login!</li>
<li>Editable translations and messages!</li>
<li><strong>MySQL and SQLite Backend support!</strong></li>
<li>Supported password encryption algorithms: MD5, SHA1, SHA256, <a href="https://github.com/CypherX/xAuth/wiki/Password-Hashing">xAuth</a>, <a href="http://en.wikipedia.org/wiki/Whirlpool_(cryptography)">Whirlpool</a></li>
<li>Supported alternative registration methods:<br>
<ul>
<li>PHPBB, VBullettin: MD5VB - PHPBB</li>
<li>MyBB: MYBB</li>
<li>IPB3: IPB3</li>
<li>PhpFusion: PHPFUSION</li>
<li><del>Xenforo SHA1: XFSHA1</del> <strong>(Deprecated)</strong></li>
<li><del>Xenforo SHA256: XFSHA256</del> <strong>(Deprecated)</strong></li>
<li>Joomla: JOOMLA</li>
<li>WBB3: WBB3*</li>
<li>SHA512: SHA512</li>
<li>DoubleSaltedMD5: SALTED2MD5</li>
<li>WordPress: WORDPRESS</li>
</ul></li>
<li>Custom MySQL tables/columns names (useful with forums databases)</li>
<li><strong>Cached database queries!</strong></li>
<li><strong>Full compatible with Citizens2, CombatTag, CombatTagPlus and ChestShop!</strong></li>
<li>Compatible with Minecraft mods like <strong>BuildCraft or RedstoneCraft</strong></li>
<li>Restricted users (associate a Username with an IP)</li>
<li>Protect player's inventory until a correct Authentication</li>
<li>Saves the quit location of the player</li>
<li>Automatic database Backup</li>
<li>Avariable languages: en, de, br, cz, pl, fr, uk, ru, hu, sk, es, fi, zhtw, zhhk, zhcn, lt, it, ko, pt, nl, gl, bg, eu, tr (feel free to send new translations)</li>
<li>Built-in Deprecated FlatFile (auths.db) to SQL (authme.sql) converter!</li>
<li><strong>Import your old database from other plugins like Rakamak, xAuth, CrazyLogin, RoyalAuth and vAuth!</strong></li>
</ul>
####Configuration
<a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/configure-auth-me/">How to Configure Authme</a>
####Email Recovery Dependency
<a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/how-to-configure-email-recovery-system/">How to configure email recovery system?</a>
####Commands
<a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/command/">Command list and usage</a>
####Permissions
<ul><li>authme.player.* - for all user command
</li><li>authme.admin.* - for all admin command
</li><li>authme.* - for all user and admin command
</li><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/permissions/">List of all single permissions</a>
</li></ul>
####How To
<ul><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/how-to-install-and-initial-configuration/">How to Install and Setup</a>
</li><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/how-to-import-database-from-xauth/">How to import database from xAuth</a>
</li><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/web-site-integration/">WebSite Integration</a>
</li><li><a href="https://raw.githubusercontent.com/Xephi/AuthMeReloaded/master/src/main/resources/config.yml">Click here for an example of the Config file</a>
</li><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/how-to-import-database-from-rakamak/">How to convert from Rakamak</a>
</li><li>Convert from FlatFile (auths.db but not the sqlite one ) to MySQL: /converter
</li></ul>
<hr>
#####GeoIP
<p>This product uses data from the GeoLite API created by MaxMind, available at <a href="http://www.maxmind.com">http://www.maxmind.com</a></p>
<hr>
#####Donate
<p>Do you like my work? Do you want to buy me a coffee? :)<br>
EUR: <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=QLMM9SNCX825Y"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif"></a>
USD: <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=PWQMYCP2SAH6L"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif"></a></p>
#####Sponsor
GameHosting.it is leader in Italy as Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware.
[![GameHosting](http://www.gamehosting.it/images/bn3.png)](http://www.gamehosting.it)
#####Credits
<p>Team members: look at the <a href="https://github.com/AuthMe-Team/AuthMeReloaded/blob/master/team.txt">team.txt file</a>
<p>Credit for old version of the plugin to: d4rkwarriors, fabe1337 , Whoami2 and pomo4ka</p>
<p>Thanks also to: AS1LV3RN1NJA, Hoeze and eprimex</p>

9
circle.yml Normal file
View File

@ -0,0 +1,9 @@
machine:
java:
version: oraclejdk7
general:
artifacts:
- "target/AuthMe-*.jar"
test:
override:
- mvn clean install -B

BIN
lib/Essentials.jar Normal file

Binary file not shown.

Binary file not shown.

BIN
lib/Vault.jar Normal file

Binary file not shown.

309
pom.xml Normal file
View File

@ -0,0 +1,309 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fr.xephi</groupId>
<artifactId>authme</artifactId>
<version>5.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AuthMeReloaded</name>
<description>Authentication plugin for CraftBukkit/Spigot!</description>
<inceptionYear>2013</inceptionYear>
<url>http://dev.bukkit.org/bukkit-plugins/authme-reloaded/</url>
<!-- See also: https://www.spigotmc.org/resources/authme-reloaded.6269/ -->
<organization>
<name>AuthMe-Team</name>
<url>https://github.com/AuthMe-Team</url>
</organization>
<scm>
<connection>scm:git:https://github.com/Xephi/AuthMeReloaded.git</connection>
<developerConnection>scm:git:git@github.com:Xephi/AuthMeReloaded.git</developerConnection>
<url>http://github.com/Xephi/AuthMeReloaded</url>
</scm>
<!-- Official Build Server -->
<ciManagement>
<system>jenkins</system>
<url>http://ci.xephi.fr/job/AuthMeReloaded/</url>
</ciManagement>
<issueManagement>
<system>GitHub</system>
<url>https://github.com/Xephi/AuthMeReloaded/issues</url>
</issueManagement>
<licenses>
<license>
<name>The GNU General Public Licence version 3 (GPLv3)</name>
<url>http://www.gnu.org/licenses/gpl-3.0.html</url>
</license>
</licenses>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Change Compiler Version (JDK) HERE! -->
<javaVersion>1.7</javaVersion>
<!-- Change MC Version HERE! -->
<bukkitVersion>1.8.8-R0.1-SNAPSHOT</bukkitVersion>
</properties>
<build>
<finalName>AuthMe-${project.version}</finalName>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>src/main/resources/</directory>
<includes>
<include>*.yml</include>
</includes>
</resource>
<resource>
<targetPath>./messages/</targetPath>
<filtering>false</filtering>
<directory>src/main/resources/messages/</directory>
<includes>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>${javaVersion}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>com.zaxxer:HikariCP</include>
<include>org.slf4j:slf4j-jdk14</include>
<include>org.slf4j:slf4j-api</include>
<include>com.maxmind.geoip:geoip-api</include>
<include>com.google.code.gson:gson</include>
</includes>
</artifactSet>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<!-- SpigotMC Repo (Bukkit and SpigotAPI) -->
<repository>
<id>spigot-repo</id>
<url>http://hub.spigotmc.org/nexus/content/groups/public</url>
</repository>
<!-- EssentialsX Repo -->
<!-- <repository> <id>ess-repo</id> <url>http://ci.drtshock.net/plugin/repository/everything</url>
</repository> -->
<!-- CombatTagPlus Repo -->
<!-- <repository> <id>minelink-thirdparty</id> <url>http://repo.minelink.net/content/repositories/public</url>
</repository> -->
<!-- Attribute Repo -->
<!-- <repository> <id>comphenix-snapshots</id> <url>http://repo.comphenix.net/content/repositories/public</url>
</repository> -->
<!-- Multiverse Repo -->
<!-- <repository> <id>onarandombox</id> <url>http://repo.onarandombox.com/content/groups/public</url>
</repository> -->
<!-- Vault Repo -->
<!-- <repository> <id>vault-repo</id> <url>http://nexus.theyeticave.net/content/repositories/pub_releases</url>
</repository> -->
<!-- XAuth Repo -->
<!-- <repository> <id>luricos-releases</id> <url>http://repo.luricos.de/content/repositories/releases</url>
</repository> -->
<!-- Xephi Repo <repository> <id>xephi-repo</id> <url>http://ci.xephi.fr/plugin/repository/everything/</url>
</repository> -->
<!-- Metrics Snapshots Repo -->
<!-- <repository> <id>mcstats-snapshots</id> <url>http://repo.mcstats.org/content/repositories/snapshots/</url>
</repository> -->
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<type>jar</type>
<version>1.8.8-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.citycraft</groupId>
<artifactId>PluginHelper</artifactId>
<type>jar</type>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.5</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/Vault.jar</systemPath>
</dependency>
<dependency>
<groupId>com.earth2me</groupId>
<artifactId>essentials</artifactId>
<version>2.9.6</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/Essentials.jar</systemPath>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.4.1</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.maxmind.geoip</groupId>
<artifactId>geoip-api</artifactId>
<version>1.2.15</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<!-- Log4J Logger (for the filter) -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta9</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.comphenix.protocol</groupId>
<artifactId>ProtocolLib</artifactId>
<version>3.6.5-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/ProtocolLib-3.6.5-SNAPSHOT.jar</systemPath>
</dependency>
<!-- Maven Dependencies -->
<!-- Database Connection Pool -->
<!-- <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId>
<version>2.4.1</version> <scope>compile</scope> <exclusions> <exclusion>
<artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion>
</exclusions> <optional>true</optional> </dependency> <dependency> <groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId> <version>1.7.12</version> <scope>compile</scope>
<optional>true</optional> </dependency> Log4J Logger (for the filter) <dependency>
<groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId>
<version>2.0-beta9</version> <scope>provided</scope> <optional>true</optional>
</dependency> SQLite Connector <dependency> <groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId> <version>3.8.11.2</version> <scope>compile</scope>
<optional>true</optional> </dependency> Java Email API and Implementation
<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId>
<version>1.5.4</version> <scope>compile</scope> <optional>true</optional>
</dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId>
<version>1.5.4</version> <scope>compile</scope> <exclusions> <exclusion>
<artifactId>activation</artifactId> <groupId>javax.activation</groupId> </exclusion>
</exclusions> <optional>true</optional> </dependency> GSON required for 1.7.X
compatibility <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId>
<version>2.4</version> <scope>compile</scope> <optional>true</optional> </dependency>
Maxmind GeoIp API <dependency> <groupId>com.maxmind.geoip</groupId> <artifactId>geoip-api</artifactId>
<version>1.2.15</version> <scope>compile</scope> <optional>true</optional>
</dependency> Metrics API <dependency> <groupId>org.mcstats.bukkit</groupId>
<artifactId>metrics</artifactId> <version>R8-SNAPSHOT</version> <scope>compile</scope>
<exclusions> <exclusion> <groupId>org.bukkit</groupId> <artifactId>bukkit</artifactId>
</exclusion> </exclusions> <optional>true</optional> </dependency> Bukkit
API, http://www.spigotmc.org/ or http://bukkit.org/ <dependency> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <version>${bukkitVersion}</version> <scope>provided</scope>
<optional>true</optional> <exclusions> <exclusion> <artifactId>junit</artifactId>
<groupId>junit</groupId> </exclusion> <exclusion> <artifactId>json-simple</artifactId>
<groupId>com.googlecode.json-simple</groupId> </exclusion> <exclusion> <artifactId>persistence-api</artifactId>
<groupId>javax.persistence</groupId> </exclusion> </exclusions> </dependency>
Attribute <dependency> <groupId>com.comphenix.attribute</groupId> <artifactId>AttributeStorage</artifactId>
<version>0.0.2-SNAPSHOT</version> <scope>compile</scope> <exclusions> <exclusion>
<groupId>org.bukkit</groupId> <artifactId>bukkit</artifactId> </exclusion>
<exclusion> <groupId>org.bukkit</groupId> <artifactId>craftbukkit</artifactId>
</exclusion> </exclusions> <optional>true</optional> </dependency> ProtocolLib
http://dev.bukkit.org/bukkit-plugins/protocollib/ <dependency> <groupId>com.comphenix.protocol</groupId>
<artifactId>ProtocolLib</artifactId> <version>3.4.0</version> <scope>provided</scope>
<optional>true</optional> <exclusions> <exclusion> <artifactId>cglib-nodep</artifactId>
<groupId>cglib</groupId> </exclusion> <exclusion> <artifactId>BukkitExecutors</artifactId>
<groupId>com.comphenix.executors</groupId> </exclusion> </exclusions> </dependency>
Vault, http://dev.bukkit.org/bukkit-plugins/vault/ <dependency> <groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId> <version>1.5</version> <scope>provided</scope>
<exclusions> <exclusion> <groupId>org.bukkit</groupId> <artifactId>bukkit</artifactId>
</exclusion> <exclusion> <groupId>org.bukkit</groupId> <artifactId>craftbukkit</artifactId>
</exclusion> </exclusions> <optional>true</optional> </dependency> Multi
World plugin, http://www.spigotmc.org/resources/multiverse-core.390/ <dependency>
<groupId>com.onarandombox.multiversecore</groupId> <artifactId>Multiverse-Core</artifactId>
<version>2.5</version> <type>jar</type> <scope>provided</scope> <exclusions>
<exclusion> <groupId>org.bukkit</groupId> <artifactId>bukkit</artifactId>
</exclusion> <exclusion> <groupId>org.bukkit</groupId> <artifactId>craftbukkit</artifactId>
</exclusion> <exclusion> <artifactId>AllPay</artifactId> <groupId>com.fernferret.allpay</groupId>
</exclusion> <exclusion> <artifactId>Vault</artifactId> <groupId>net.milkbowl.vault</groupId>
</exclusion> <exclusion> <artifactId>CommandHandler</artifactId> <groupId>com.pneumaticraft.commandhandler</groupId>
</exclusion> <exclusion> <artifactId>SerializationConfig</artifactId> <groupId>me.main__.util</groupId>
</exclusion> <exclusion> <artifactId>Logging</artifactId> <groupId>com.dumptruckman.minecraft</groupId>
</exclusion> <exclusion> <artifactId>metrics</artifactId> <groupId>org.mcstats.bukkit</groupId>
</exclusion> <exclusion> <artifactId>buscript</artifactId> <groupId>com.dumptruckman.minecraft</groupId>
</exclusion> <exclusion> <artifactId>junit</artifactId> <groupId>junit</groupId>
</exclusion> </exclusions> <optional>true</optional> </dependency> Essentials
plugin <dependency> <groupId>net.ess3</groupId> <artifactId>EssentialsX</artifactId>
<version>2.0.1-SNAPSHOT</version> <scope>provided</scope> <exclusions> <exclusion>
<groupId>org.spigotmc</groupId> <artifactId>spigot-api</artifactId> </exclusion>
</exclusions> <optional>true</optional> </dependency> Anti PvPLogging plugin,
https://github.com/MinelinkNetwork/CombatTagPlus <dependency> <groupId>net.minelink</groupId>
<artifactId>CombatTagPlus</artifactId> <version>1.2.1-SNAPSHOT</version>
<scope>provided</scope> <exclusions> <exclusion> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> </exclusion> <exclusion> <groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId> </exclusion> <exclusion> <artifactId>CombatTagPlusHook</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusFactions-v1_6</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusCompat-v1_7_R3</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusFactions-v1_8</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusCompat-v1_7_R4</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusWG-v5</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusWG-v6</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusCompat-API</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusFactions-v2_6</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusCompat-v1_8_R3</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusFactions-v2_7</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusCompat-v1_8_R2</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>CombatTagPlusCompat-v1_8_R1</artifactId>
<groupId>net.minelink</groupId> </exclusion> <exclusion> <artifactId>metrics-lite</artifactId>
<groupId>org.mcstats.bukkit</groupId> </exclusion> </exclusions> <optional>true</optional>
</dependency> XAuth, another authentication plugin, required by the database
converter <dependency> <groupId>de.luricos.bukkit</groupId> <artifactId>xAuth</artifactId>
<version>2.6</version> <scope>provided</scope> <exclusions> <exclusion> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> </exclusion> <exclusion> <groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId> </exclusion> <exclusion> <artifactId>updater</artifactId>
<groupId>net.gravitydevelopment.updater</groupId> </exclusion> <exclusion>
<artifactId>lombok</artifactId> <groupId>org.projectlombok</groupId> </exclusion>
<exclusion> <artifactId>EssentialsGroupManager</artifactId> <groupId>net.ess3</groupId>
</exclusion> <exclusion> <artifactId>PermissionsEx</artifactId> <groupId>ru.tehkode</groupId>
</exclusion> <exclusion> <artifactId>AccountsClient</artifactId> <groupId>com.mojang</groupId>
</exclusion> <exclusion> <artifactId>log4j-core</artifactId> <groupId>org.apache.logging.log4j</groupId>
</exclusion> </exclusions> <optional>true</optional> </dependency> -->
</dependencies>
</project>

View File

@ -0,0 +1,738 @@
package fr.xephi.authme;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import com.earth2me.essentials.Essentials;
import fr.xephi.authme.api.API;
import fr.xephi.authme.api.NewAPI;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.commands.AdminCommand;
import fr.xephi.authme.commands.CaptchaCommand;
import fr.xephi.authme.commands.ChangePasswordCommand;
import fr.xephi.authme.commands.ConverterCommand;
import fr.xephi.authme.commands.LoginCommand;
import fr.xephi.authme.commands.LogoutCommand;
import fr.xephi.authme.commands.RegisterCommand;
import fr.xephi.authme.commands.UnregisterCommand;
import fr.xephi.authme.converter.Converter;
import fr.xephi.authme.converter.ForceFlatToSqlite;
import fr.xephi.authme.datasource.CacheDataSource;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DatabaseCalls;
import fr.xephi.authme.datasource.FlatFile;
import fr.xephi.authme.datasource.MySQL;
import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.datasource.SQLite_HIKARI;
import fr.xephi.authme.listener.AuthMeBlockListener;
import fr.xephi.authme.listener.AuthMeEntityListener;
import fr.xephi.authme.listener.AuthMeInventoryPacketAdapter;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.listener.AuthMePlayerListener16;
import fr.xephi.authme.listener.AuthMePlayerListener18;
import fr.xephi.authme.listener.AuthMeServerListener;
import fr.xephi.authme.modules.ModuleManager;
import fr.xephi.authme.plugin.manager.BungeeCordMessage;
import fr.xephi.authme.plugin.manager.EssSpawn;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.OtherAccounts;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import net.milkbowl.vault.permission.Permission;
public class AuthMe extends JavaPlugin {
private static AuthMe authme;
private static Server server;
public boolean antibotMod = false;
public NewAPI api;
public ConcurrentHashMap<String, String> cap = new ConcurrentHashMap<>();
public ConcurrentHashMap<String, Integer> captcha = new ConcurrentHashMap<>();
public DataSource database;
public DataManager dataManager;
public boolean delayedAntiBot = true;
public Essentials ess;
public Location essentialsSpawn;
public AuthMeInventoryPacketAdapter inventoryProtector;
public Management management;
public OtherAccounts otherAccounts;
// Hooks TODO: move into modules
public Permission permission;
public ConcurrentHashMap<String, String> realIp = new ConcurrentHashMap<>();
// TODO: Create Manager for fields below
public ConcurrentHashMap<String, BukkitTask> sessions = new ConcurrentHashMap<>();
private Logger authmeLogger;
private Messages m;
// Module manager
private ModuleManager moduleManager;
private JsonCache playerBackup;
private Settings settings;
public static AuthMe getInstance() {
return authme;
}
public boolean authmePermissible(final CommandSender sender, final String perm) {
if (sender.hasPermission(perm)) {
return true;
} else if (permission != null) {
return permission.has(sender, perm);
}
return false;
}
// Check if a player/command sender have a permission
public boolean authmePermissible(final Player player, final String perm) {
if (player.hasPermission(perm)) {
return true;
} else if (permission != null) {
return permission.playerHas(player, perm);
}
return false;
}
// Get the Essentials plugin
public void checkEssentials() {
if (server.getPluginManager().isPluginEnabled("Essentials")) {
try {
ess = (Essentials) server.getPluginManager().getPlugin("Essentials");
ConsoleLogger.info("发现 Essentials 启用相关功能...");
} catch (Exception | NoClassDefFoundError ingnored) {
ess = null;
}
} else {
ess = null;
}
if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) {
try {
essentialsSpawn = new EssSpawn().getLocation();
ConsoleLogger.info("发现 EssentialsSpawn 读取重生点...");
} catch (final Exception e) {
essentialsSpawn = null;
ConsoleLogger.showError("无法读取文件 /plugins/Essentials/spawn.yml !");
}
} else {
essentialsSpawn = null;
}
}
// Check the presence of the ProtocolLib plugin
public void checkProtocolLib() {
if (Settings.protectInventoryBeforeLogInEnabled) {
if (server.getPluginManager().isPluginEnabled("ProtocolLib")) {
inventoryProtector = new AuthMeInventoryPacketAdapter(this);
inventoryProtector.register();
} else {
ConsoleLogger.showError("警告!!! 保护背包功能必须启用 ProtocolLib 插件 但是未找到! 关闭该功能...");
Settings.protectInventoryBeforeLogInEnabled = false;
}
}
}
// Check the presence of the Vault plugin and a permissions provider
public void checkVault() {
if (server.getPluginManager().isPluginEnabled("Vault")) {
final RegisteredServiceProvider<Permission> permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
ConsoleLogger.info("发现 Vault 使用经济系统: " + permission.getName());
} else {
ConsoleLogger.showError("发现 Vault, 但是 Vault 未找到权限系统...");
}
} else {
permission = null;
}
}
// Select the player to kick when a vip player join the server when full
public Player generateKickPlayer(final Collection<? extends Player> collection) {
Player player = null;
for (final Player p : collection) {
if (!(authmePermissible(p, "authme.vip"))) {
player = p;
break;
}
}
return player;
}
@Deprecated
public String getCountryCode(final String ip) {
return Utils.getCountryCode(ip);
}
@Deprecated
public String getCountryName(final String ip) {
return Utils.getCountryName(ip);
}
public String getIP(final Player player) {
final String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().getHostAddress();
if (Settings.bungee) {
if (realIp.containsKey(name)) {
ip = realIp.get(name);
}
}
if (Settings.checkVeryGames) {
if (getVeryGamesIP(player) != null) {
ip = getVeryGamesIP(player);
}
}
return ip;
}
public Messages getMessages() {
return m;
}
public ModuleManager getModuleManager() {
return moduleManager;
}
public Settings getSettings() {
return settings;
}
// Return the spawn location of a player
public Location getSpawnLocation(final Player player) {
final World world = player.getWorld();
final String[] spawnPriority = Settings.spawnPriority.split(",");
Location spawnLoc = world.getSpawnLocation();
for (int i = spawnPriority.length - 1; i >= 0; i--) {
final String s = spawnPriority[i];
if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) {
spawnLoc = getDefaultSpawn(world);
}
if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null) {
spawnLoc = getEssentialsSpawn();
}
if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) {
spawnLoc = getAuthMeSpawn(player);
}
}
if (spawnLoc == null) {
spawnLoc = world.getSpawnLocation();
}
return spawnLoc;
}
/**
* Get Player real IP through VeryGames method
*
* @param player
* player
*/
@Deprecated
public String getVeryGamesIP(final Player player) {
String realIP = player.getAddress().getAddress().getHostAddress();
String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%";
sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort());
try {
final URL url = new URL(sUrl);
final URLConnection urlc = url.openConnection();
final BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
final String inputLine = in.readLine();
if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) {
realIP = inputLine;
}
} catch (final Exception ignored) {
}
return realIP;
}
public boolean hasJoinedIp(final String name, final String ip) {
int count = 0;
for (final Player player : Utils.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name)) {
count++;
}
}
return count >= Settings.getMaxJoinPerIp;
}
public boolean isLoggedIp(final String name, final String ip) {
int count = 0;
for (final Player player : Utils.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) {
count++;
}
}
return count >= Settings.getMaxLoginPerIp;
}
@Override
public void onDisable() {
// Save player data
final Collection<? extends Player> players = Utils.getOnlinePlayers();
if (players != null) {
for (final Player player : players) {
this.savePlayer(player);
}
}
// Close the database
if (database != null) {
database.close();
}
// Do backup on stop if enabled
if (Settings.isBackupActivated && Settings.isBackupOnStop) {
final boolean Backup = new PerformBackup(this).doBackup();
if (Backup) {
ConsoleLogger.info("Backup performed correctly.");
} else {
ConsoleLogger.showError("Error while performing the backup!");
}
}
// Unload modules
moduleManager.unloadModules();
// Disabled correctly
ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
}
@SuppressWarnings("deprecation")
@Override
public void onEnable() {
// Set the Instance
server = getServer();
authmeLogger = Logger.getLogger("AuthMe");
authme = this;
// TODO: split the plugin in more modules
moduleManager = new ModuleManager(this);
@SuppressWarnings("unused")
final int loaded = moduleManager.loadModules();
// TODO: remove vault as hard dependency
final PluginManager pm = server.getPluginManager();
// Setup the Logger
if (authmeLogger == null) {
authmeLogger = this.getLogger();
} else {
authmeLogger.setParent(this.getLogger());
}
// Load settings and custom configurations
// TODO: new configuration style (more files)
try {
settings = new Settings(this);
Settings.reload();
} catch (final Exception e) {
ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!");
server.shutdown();
return;
}
// Setup otherAccounts file
otherAccounts = OtherAccounts.getInstance();
// Setup messages
m = Messages.getInstance();
// Set Console Filter
if (Settings.removePassword) {
final ConsoleFilter filter = new ConsoleFilter();
this.getLogger().setFilter(filter);
Bukkit.getLogger().setFilter(filter);
Logger.getLogger("Minecraft").setFilter(filter);
authmeLogger.setFilter(filter);
// Set Log4J Filter
try {
Class.forName("org.apache.logging.log4j.core.Filter");
setLog4JFilter();
} catch (ClassNotFoundException | NoClassDefFoundError e) {
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
}
}
// AntiBot delay
if (Settings.enableAntiBot) {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
delayedAntiBot = false;
}
}, 2400);
}
// Download GeoIp.dat file
Utils.checkGeoIP();
// Find Permissions
checkVault();
// Check Essentials
checkEssentials();
// Check if the protocollib is available. If so we could listen for
// inventory protection
checkProtocolLib();
// Do backup on start if enabled
if (Settings.isBackupActivated && Settings.isBackupOnStart) {
// Do backup and check return value!
if (new PerformBackup(this).doBackup()) {
ConsoleLogger.info("Backup performed correctly");
} else {
ConsoleLogger.showError("Error while performing the backup!");
}
}
// Connect to the database and setup tables
try {
setupDatabase();
} catch (final Exception e) {
ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError(e.getMessage());
ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!");
stopOrUnload();
return;
}
// Setup the inventory backup
playerBackup = new JsonCache();
// Set the DataManager
dataManager = new DataManager(this);
// Setup the new API
api = new NewAPI(this);
// Setup the old deprecated API
new API(this);
// Setup Management
management = new Management(this);
// Bungeecord hook
if (Settings.bungee) {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this));
}
// Reload support hook
if (Settings.reloadSupport) {
if (database != null) {
final int playersOnline = Utils.getOnlinePlayers().size();
if (playersOnline < 1) {
database.purgeLogged();
} else {
for (final PlayerAuth auth : database.getLoggedPlayers()) {
if (auth == null) {
continue;
}
auth.setLastLogin(new Date().getTime());
database.updateSession(auth);
PlayerCache.getInstance().addPlayer(auth);
}
}
}
}
// Register events
pm.registerEvents(new AuthMePlayerListener(this), this);
// Try to register 1.6 player listeners
try {
Class.forName("org.bukkit.event.player.PlayerEditBookEvent");
pm.registerEvents(new AuthMePlayerListener16(this), this);
} catch (final ClassNotFoundException ignore) {
}
// Try to register 1.8 player listeners
try {
Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent");
pm.registerEvents(new AuthMePlayerListener18(this), this);
} catch (final ClassNotFoundException ignore) {
}
pm.registerEvents(new AuthMeBlockListener(this), this);
pm.registerEvents(new AuthMeEntityListener(this), this);
pm.registerEvents(new AuthMeServerListener(this), this);
// Register commands
getCommand("authme").setExecutor(new AdminCommand(this));
getCommand("register").setExecutor(new RegisterCommand(this));
getCommand("login").setExecutor(new LoginCommand(this));
getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
getCommand("logout").setExecutor(new LogoutCommand(this));
getCommand("unregister").setExecutor(new UnregisterCommand(this));
getCommand("captcha").setExecutor(new CaptchaCommand(this));
getCommand("converter").setExecutor(new ConverterCommand(this));
// Purge on start if enabled
autoPurge();
// Start Email recall task if needed
recallEmail();
// Configuration Security Warnings
if (!Settings.isForceSingleSessionEnabled) {
ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
}
if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) {
ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!");
}
// Sponsor messages
ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!");
ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt.");
ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!");
// Successful message
ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!");
}
public String replaceAllInfos(String message, final Player player) {
final int playersOnline = Utils.getOnlinePlayers().size();
message = message.replace("&", "§");
message = message.replace("{PLAYER}", player.getName());
message = message.replace("{ONLINE}", "" + playersOnline);
message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers());
message = message.replace("{IP}", getIP(player));
message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
message = message.replace("{WORLD}", player.getWorld().getName());
message = message.replace("{SERVER}", server.getServerName());
message = message.replace("{VERSION}", server.getBukkitVersion());
message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player)));
return message;
}
// Save Player Data
public void savePlayer(final Player player) {
if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) {
return;
}
final String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(),
player.getName());
database.updateQuitLoc(auth);
}
if (LimboCache.getInstance().hasLimboPlayer(name)) {
final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (!Settings.noTeleport) {
player.teleport(limbo.getLoc());
}
Utils.addNormal(player, limbo.getGroup());
player.setOp(limbo.getOperator());
limbo.getTimeoutTaskId().cancel();
LimboCache.getInstance().deleteLimboPlayer(name);
if (this.playerBackup.doesCacheExist(player)) {
this.playerBackup.removeCache(player);
}
}
PlayerCache.getInstance().removePlayer(name);
database.setUnlogged(name);
player.saveData();
}
public void setMessages(final Messages m) {
this.m = m;
}
// Initialize and setup the database
public void setupDatabase() throws Exception {
if (database != null) {
database.close();
}
// Backend MYSQL - FILE - SQLITE - SQLITEHIKARI
boolean isSQLite = false;
switch (Settings.getDataSource) {
case FILE:
database = new FlatFile();
break;
case MYSQL:
database = new MySQL();
break;
case SQLITE:
database = new SQLite();
isSQLite = true;
break;
case SQLITEHIKARI:
database = new SQLite_HIKARI();
isSQLite = true;
break;
}
if (isSQLite) {
server.getScheduler().runTaskAsynchronously(this, new Runnable() {
@Override
public void run() {
final int accounts = database.getAccountsRegistered();
if (accounts >= 4000) {
ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!");
}
}
});
}
if (Settings.isCachingEnabled) {
database = new CacheDataSource(this, database);
} else {
database = new DatabaseCalls(database);
}
if (Settings.getDataSource == DataSource.DataSourceType.FILE) {
final Converter converter = new ForceFlatToSqlite(database, this);
server.getScheduler().runTaskAsynchronously(this, converter);
ConsoleLogger.showError(
"FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !");
ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart");
}
}
// Stop/unload the server/plugin as defined in the configuration
public void stopOrUnload() {
if (Settings.isStopEnabled) {
ConsoleLogger.showError("THE SERVER IS GOING TO SHUTDOWN AS DEFINED IN THE CONFIGURATION!");
server.shutdown();
} else {
server.getPluginManager().disablePlugin(AuthMe.getInstance());
}
}
// Show the exception message and stop/unload the server/plugin as defined
// in the configuration
public void stopOrUnload(final Exception e) {
ConsoleLogger.showError(e.getMessage());
stopOrUnload();
}
public void switchAntiBotMod(final boolean mode) {
this.antibotMod = mode;
Settings.switchAntiBotMod(mode);
}
// Purge inactive players from the database, as defined in the configuration
private void autoPurge() {
if (!Settings.usePurge) {
return;
}
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -(Settings.purgeDelay));
final long until = calendar.getTimeInMillis();
final List<String> cleared = database.autoPurgeDatabase(until);
if (cleared == null) {
return;
}
if (cleared.isEmpty()) {
return;
}
ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!");
if (Settings.purgeEssentialsFile && this.ess != null) {
dataManager.purgeEssentials(cleared); // name to UUID convertion
}
// needed with latest versions
if (Settings.purgePlayerDat) {
dataManager.purgeDat(cleared); // name to UUID convertion needed
}
// with latest versions of MC
if (Settings.purgeLimitedCreative) {
dataManager.purgeLimitedCreative(cleared);
}
if (Settings.purgeAntiXray) {
dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or
}
// names... (Actually it purges
// only names!)
if (Settings.purgePermissions) {
dataManager.purgePermissions(cleared, permission);
}
}
// Return the authme soawnpoint
private Location getAuthMeSpawn(final Player player) {
if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) {
return Spawn.getInstance().getFirstSpawn();
}
if (Spawn.getInstance().getSpawn() != null) {
return Spawn.getInstance().getSpawn();
}
return player.getWorld().getSpawnLocation();
}
// Return the default spawnpoint of a world
private Location getDefaultSpawn(final World world) {
return world.getSpawnLocation();
}
// Return the essentials spawnpoint
private Location getEssentialsSpawn() {
if (essentialsSpawn != null) {
return essentialsSpawn;
}
return null;
}
private void recallEmail() {
if (!Settings.recallEmail) {
return;
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
for (final Player player : Utils.getOnlinePlayers()) {
if (player.isOnline()) {
final String name = player.getName().toLowerCase();
if (database.isAuthAvailable(name)) {
if (PlayerCache.getInstance().isAuthenticated(name)) {
final String email = database.getAuth(name).getEmail();
if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) {
m.send(player, "add_email");
}
}
}
}
}
}
}, 1, 1200 * Settings.delayRecall);
}
// Set the console filter to remove the passwords
private void setLog4JFilter() {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
final org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
coreLogger.addFilter(new Log4JFilter());
}
});
}
}

View File

@ -0,0 +1,35 @@
package fr.xephi.authme;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
/**
*
* @author Xephi59
*/
public class ConsoleFilter implements Filter {
public ConsoleFilter() {
}
@Override
public boolean isLoggable(LogRecord record) {
try {
if (record == null || record.getMessage() == null)
return true;
String logM = record.getMessage().toLowerCase();
if (!logM.contains("issued server command:"))
return true;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ")
&& !logM.contains("/register "))
return true;
String playername = record.getMessage().split(" ")[0];
record.setMessage(playername + " issued an AuthMe command!");
return true;
} catch (NullPointerException npe) {
return true;
}
}
}

View File

@ -0,0 +1,61 @@
package fr.xephi.authme;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import com.google.common.base.Throwables;
import fr.xephi.authme.api.NewAPI;
import fr.xephi.authme.settings.Settings;
public class ConsoleLogger {
private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]");
private static final Logger log = AuthMe.getInstance().getLogger();
public static void info(final String message) {
if (AuthMe.getInstance().isEnabled()) {
log.info(message);
if (Settings.useLogging) {
String dateTime;
synchronized (df) {
dateTime = df.format(new Date());
}
writeLog(dateTime + " " + message);
}
}
}
public static void showError(final String message) {
if (AuthMe.getInstance().isEnabled()) {
log.warning(message);
if (Settings.useLogging) {
String dateTime;
synchronized (df) {
dateTime = df.format(new Date());
}
writeLog(dateTime + " ERROR: " + message);
}
}
}
public static void writeLog(final String message) {
try {
Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
} catch (final IOException ignored) {
}
}
public static void writeStackTrace(final Exception ex) {
String dateTime;
synchronized (df) {
dateTime = df.format(new Date());
}
writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex));
}
}

View File

@ -0,0 +1,201 @@
package fr.xephi.authme;
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import fr.xephi.authme.settings.Settings;
import net.milkbowl.vault.permission.Permission;
public class DataManager {
public AuthMe plugin;
public DataManager(final AuthMe plugin) {
this.plugin = plugin;
}
public synchronized OfflinePlayer getOfflinePlayer(final String name) {
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<OfflinePlayer> result = executor.submit(new Callable<OfflinePlayer>() {
@Override
public synchronized OfflinePlayer call() throws Exception {
OfflinePlayer result = null;
try {
for (final OfflinePlayer op : Bukkit.getOfflinePlayers()) {
if (op.getName().equalsIgnoreCase(name)) {
result = op;
break;
}
}
} catch (final Exception e) {
}
return result;
}
});
try {
return result.get();
} catch (final Exception e) {
return (null);
} finally {
executor.shutdown();
}
}
public boolean isOnline(final Player player, final String name) {
if (player.isOnline()) {
return true;
}
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<Boolean> result = executor.submit(new Callable<Boolean>() {
@Override
public synchronized Boolean call() throws Exception {
for (final OfflinePlayer op : Utils.getOnlinePlayers()) {
if (op.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
});
try {
return result.get();
} catch (final Exception e) {
return false;
} finally {
executor.shutdown();
}
}
public synchronized void purgeAntiXray(final List<String> cleared) {
int i = 0;
for (final String name : cleared) {
try {
final org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) {
continue;
}
final String playerName = player.getName();
final File playerFile = new File("." + File.separator + "plugins" + File.separator + "AntiXRayData" + File.separator + "PlayerData" + File.separator + playerName);
if (playerFile.exists()) {
playerFile.delete();
i++;
}
} catch (final Exception e) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " AntiXRayData Files");
}
public synchronized void purgeDat(final List<String> cleared) {
int i = 0;
for (final String name : cleared) {
try {
final org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
File playerFile = null;
if (player == null) {
continue;
}
try {
playerFile = new File(
plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getUniqueId() + ".dat");
} catch (final Exception ignore) {
}
if (playerFile != null && playerFile.exists()) {
playerFile.delete();
i++;
} else {
playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getName() + ".dat");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
}
} catch (final Exception ignore) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " .dat Files");
}
@SuppressWarnings("deprecation")
public void purgeEssentials(final List<String> cleared) {
int i = 0;
for (final String name : cleared) {
try {
File playerFile = null;
try {
playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + plugin.getServer().getOfflinePlayer(name).getUniqueId() + ".yml");
} catch (final Exception ignore) {
}
if (playerFile != null && playerFile.exists()) {
playerFile.delete();
i++;
} else {
playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
}
} catch (final Exception e) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " EssentialsFiles");
}
public synchronized void purgeLimitedCreative(final List<String> cleared) {
int i = 0;
for (final String name : cleared) {
try {
final org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
if (player == null) {
continue;
}
final String playerName = player.getName();
File playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + ".yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_creative.yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_adventure.yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
} catch (final Exception e) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " LimitedCreative Survival, Creative and Adventure files");
}
public synchronized void purgePermissions(final List<String> cleared, final Permission permission) {
int i = 0;
for (final String name : cleared) {
try {
final OfflinePlayer p = this.getOfflinePlayer(name);
for (final String group : permission.getPlayerGroups((Player) p)) {
permission.playerRemoveGroup(null, p, group);
}
i++;
} catch (final Exception e) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " Permissions");
}
public void run() {
}
}

View File

@ -0,0 +1,31 @@
package fr.xephi.authme;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class ImageGenerator {
private String pass;
public ImageGenerator(String pass) {
this.pass = pass;
}
public BufferedImage generateImage() {
BufferedImage image = new BufferedImage(200, 60, BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.BLACK);
graphics.fillRect(0, 0, 200, 40);
GradientPaint gradientPaint = new GradientPaint(10, 5, Color.WHITE, 20, 10, Color.WHITE, true);
graphics.setPaint(gradientPaint);
Font font = new Font("Comic Sans MS", Font.BOLD, 30);
graphics.setFont(font);
graphics.drawString(pass, 5, 30);
graphics.dispose();
image.flush();
return image;
}
}

View File

@ -0,0 +1,100 @@
package fr.xephi.authme;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.message.Message;
/**
*
* @author Xephi59
*/
public class Log4JFilter implements org.apache.logging.log4j.core.Filter {
public Log4JFilter() {
}
@Override
public Result filter(LogEvent record) {
try {
if (record == null || record.getMessage() == null)
return Result.NEUTRAL;
String logM = record.getMessage().getFormattedMessage().toLowerCase();
if (!logM.contains("issued server command:"))
return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ")
&& !logM.contains("/register "))
return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, Message message, Throwable arg4) {
try {
if (message == null)
return Result.NEUTRAL;
String logM = message.getFormattedMessage().toLowerCase();
if (!logM.contains("issued server command:"))
return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ")
&& !logM.contains("/register "))
return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, Object message, Throwable arg4) {
try {
if (message == null)
return Result.NEUTRAL;
String logM = message.toString().toLowerCase();
if (!logM.contains("issued server command:"))
return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ")
&& !logM.contains("/register "))
return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result filter(Logger arg0, Level arg1, Marker arg2, String message, Object... arg4) {
try {
if (message == null)
return Result.NEUTRAL;
String logM = message.toLowerCase();
if (!logM.contains("issued server command:"))
return Result.NEUTRAL;
if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ")
&& !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ")
&& !logM.contains("/register "))
return Result.NEUTRAL;
return Result.DENY;
} catch (NullPointerException npe) {
return Result.NEUTRAL;
}
}
@Override
public Result getOnMatch() {
return Result.NEUTRAL;
}
@Override
public Result getOnMismatch() {
return Result.NEUTRAL;
}
}

View File

@ -0,0 +1,148 @@
package fr.xephi.authme;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import fr.xephi.authme.settings.Settings;
/**
*
* @author stefano
*/
public class PerformBackup {
private final SimpleDateFormat aformat = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
private final String dateString = aformat.format(new Date());
private final String dbName = Settings.getMySQLDatabase;
private final String dbPassword = Settings.getMySQLPassword;
private final String dbUserName = Settings.getMySQLUsername;
private AuthMe instance;
private final String path = AuthMe.getInstance().getDataFolder() + File.separator + "backups" + File.separator + "backup" + dateString;
private final String tblname = Settings.getMySQLTablename;
public PerformBackup(final AuthMe instance) {
this.setInstance(instance);
}
public boolean doBackup() {
switch (Settings.getDataSource) {
case FILE:
return FileBackup("auths.db");
case MYSQL:
return MySqlBackup();
case SQLITEHIKARI:
case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db");
}
return false;
}
public AuthMe getInstance() {
return instance;
}
public void setInstance(final AuthMe instance) {
this.instance = instance;
}
/*
* Check if we are under Windows and correct location of mysqldump.exe
* otherwise return error.
*/
private boolean checkWindows(final String windowsPath) {
final String isWin = System.getProperty("os.name").toLowerCase();
if (isWin.indexOf("win") >= 0) {
if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
return true;
} else {
ConsoleLogger.showError("Mysql Windows Path is incorrect please check it");
return true;
}
} else {
return false;
}
}
private boolean FileBackup(final String backend) {
final File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");
if (!dirBackup.exists()) {
dirBackup.mkdir();
}
try {
copy(new File("plugins" + File.separator + "AuthMe" + File.separator + backend), new File(path + ".db"));
return true;
} catch (final Exception ex) {
ex.printStackTrace();
}
return false;
}
private boolean MySqlBackup() {
final File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");
if (!dirBackup.exists()) {
dirBackup.mkdir();
}
if (checkWindows(Settings.backupWindowsPath)) {
final String executeCmd = Settings.backupWindowsPath + "\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
final int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully.");
return true;
} else {
ConsoleLogger.showError("Could not create the backup!");
}
} catch (final Exception ex) {
ex.printStackTrace();
}
} else {
final String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
final int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully.");
return true;
} else {
ConsoleLogger.showError("Could not create the backup!");
}
} catch (final Exception ex) {
ex.printStackTrace();
}
}
return false;
}
/*
* Copyr src bytefile into dst file
*/
void copy(final File src, final File dst) throws IOException {
final InputStream in = new FileInputStream(src);
final OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
final byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}

View File

@ -0,0 +1,295 @@
package fr.xephi.authme;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.zip.GZIPInputStream;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import com.maxmind.geoip.LookupService;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.settings.Settings;
public class Utils {
public static AuthMe plugin;
private static Method getOnlinePlayers;
private static boolean getOnlinePlayersIsCollection;
private static LookupService lookupService;
static {
plugin = AuthMe.getInstance();
checkGeoIP();
try {
final Method m = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
getOnlinePlayersIsCollection = m.getReturnType() == Collection.class;
} catch (final Exception ignored) {
}
}
public static boolean addNormal(final Player player, final String group) {
if (!useGroupSystem()) {
return false;
}
if (plugin.permission == null) {
return false;
}
try {
if (plugin.permission.playerRemoveGroup(player, Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(player, group)) {
return true;
}
} catch (final UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
plugin.permission = null;
return false;
}
return false;
}
// TODO: Move to a Manager
public static boolean checkAuth(final Player player) {
if (player == null || Utils.isUnrestricted(player)) {
return true;
}
final String name = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name)) {
return true;
}
if (!Settings.isForcedRegistrationEnabled) {
if (!plugin.database.isAuthAvailable(name)) {
return true;
}
}
return false;
}
// Check and Download GeoIP data if not exist
public static boolean checkGeoIP() {
if (lookupService != null) {
return true;
}
ConsoleLogger.info("[LICENSE] IP数据来自 CityCraft 的 Yum 源 原始数据来自 http://www.maxmind.com");
final File file = new File(Settings.APLUGIN_FOLDER, "GeoIP.dat");
try {
if (file.exists()) {
if (lookupService == null) {
lookupService = new LookupService(file);
return true;
}
}
final String url = "http://citycraft.cn/downloads/authme/GeoIP.dat.gz";
final URL downloadUrl = new URL(url);
final URLConnection conn = downloadUrl.openConnection();
conn.setConnectTimeout(10000);
conn.connect();
InputStream input = conn.getInputStream();
if (conn.getURL().toString().endsWith(".gz")) {
input = new GZIPInputStream(input);
}
final OutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[2048];
int length = input.read(buffer);
while (length >= 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
output.close();
input.close();
} catch (final Exception e) {
ConsoleLogger.writeStackTrace(e);
return false;
}
return checkGeoIP();
}
/*
* Used for force player GameMode
*/
public static void forceGM(final Player player) {
if (!plugin.authmePermissible(player, "authme.bypassforcesurvival")) {
player.setGameMode(GameMode.SURVIVAL);
}
}
public static String getCountryCode(final String ip) {
if (checkGeoIP()) {
return lookupService.getCountry(ip).getCode();
}
return "--";
}
public static String getCountryName(final String ip) {
if (checkGeoIP()) {
return lookupService.getCountry(ip).getName();
}
return "N/A";
}
@SuppressWarnings("unchecked")
public static Collection<? extends Player> getOnlinePlayers() {
if (getOnlinePlayersIsCollection) {
return Bukkit.getOnlinePlayers();
}
try {
if (getOnlinePlayers == null) {
getOnlinePlayers = Bukkit.class.getMethod("getOnlinePlayers");
}
final Object obj = getOnlinePlayers.invoke(null);
if (obj instanceof Collection) {
return (Collection<? extends Player>) obj;
}
return Arrays.asList((Player[]) obj);
} catch (final Exception ignored) {
}
return Collections.emptyList();
}
// TODO: remove if not needed
public static void hasPermOnJoin(final Player player) {
if (plugin.permission == null) {
return;
}
for (final String permission : Settings.getJoinPermissions) {
if (plugin.permission.playerHas(player, permission)) {
plugin.permission.playerAddTransient(player, permission);
}
}
}
public static boolean isNPC(final Entity player) {
return player.hasMetadata("NPC");
}
public static boolean isUnrestricted(final Player player) {
return Settings.isAllowRestrictedIp && !Settings.getUnrestrictedName.isEmpty() && (Settings.getUnrestrictedName.contains(player.getName()));
}
public static void packCoords(final double x, final double y, final double z, final String w, final Player pl) {
World theWorld;
if (w.equals("unavailableworld")) {
theWorld = pl.getWorld();
} else {
theWorld = Bukkit.getWorld(w);
}
if (theWorld == null) {
theWorld = pl.getWorld();
}
final World world = theWorld;
final Location locat = new Location(world, x, y, z);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
final AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getChunk().isLoaded()) {
tpEvent.getTo().getChunk().load();
}
pl.teleport(tpEvent.getTo());
}
}
});
}
public static void purgeDirectory(final File file) {
if (!file.isDirectory()) {
return;
}
final File[] files = file.listFiles();
if (files == null) {
return;
}
for (final File target : files) {
if (target.isDirectory()) {
purgeDirectory(target);
target.delete();
} else {
target.delete();
}
}
}
public static void setGroup(final Player player, final GroupType group) {
if (!Settings.isPermissionCheckEnabled) {
return;
}
if (plugin.permission == null) {
return;
}
String currentGroup;
try {
currentGroup = plugin.permission.getPrimaryGroup(player);
} catch (final UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission plugin (" + plugin.permission.getName() + ") doesn't support the Group system... unhook!");
plugin.permission = null;
return;
}
switch (group) {
case UNREGISTERED: {
plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(player, Settings.unRegisteredGroup);
break;
}
case REGISTERED: {
plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(player, Settings.getRegisteredGroup);
break;
}
case NOTLOGGEDIN: {
if (!useGroupSystem()) {
break;
}
plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(player, Settings.getUnloggedinGroup);
break;
}
case LOGGEDIN: {
if (!useGroupSystem()) {
break;
}
final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
if (limbo == null) {
break;
}
final String realGroup = limbo.getGroup();
plugin.permission.playerRemoveGroup(player, currentGroup);
plugin.permission.playerAddGroup(player, realGroup);
break;
}
}
}
private static boolean useGroupSystem() {
return Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty();
}
public enum GroupType {
LOGGEDIN,
NOTLOGGEDIN,
REGISTERED,
UNREGISTERED
}
}

View File

@ -0,0 +1,183 @@
package fr.xephi.authme.api;
import java.security.NoSuchAlgorithmException;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
public class API {
public static AuthMe instance;
public static final String newline = System.getProperty("line.separator");
@Deprecated
public API(final AuthMe instance) {
API.instance = instance;
}
/**
* @param String
* playerName, String passwordToCheck
* @return true if the password is correct , false else
*/
@Deprecated
public static boolean checkPassword(final String playerName, final String passwordToCheck) {
if (!isRegistered(playerName)) {
return false;
}
final String player = playerName.toLowerCase();
final PlayerAuth auth = instance.database.getAuth(player);
try {
return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
} catch (final NoSuchAlgorithmException e) {
return false;
}
}
/**
* Force a player to login
*
* @param Player
* player
*/
@Deprecated
public static void forceLogin(final Player player) {
instance.management.performLogin(player, "dontneed", true);
}
@Deprecated
public static Location getLastLocation(final Player player) {
try {
final PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
if (auth != null) {
final Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
return loc;
} else {
return null;
}
} catch (final NullPointerException ex) {
return null;
}
}
/**
* Hook into AuthMe
*
* @return AuthMe instance
*/
@Deprecated
public static AuthMe hookAuthMe() {
if (instance != null) {
return instance;
}
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
if (plugin == null || !(plugin instanceof AuthMe)) {
return null;
}
instance = (AuthMe) plugin;
return instance;
}
/**
*
* @param player
* @return true if player is authenticate
*/
@Deprecated
public static boolean isAuthenticated(final Player player) {
return PlayerCache.getInstance().isAuthenticated(player.getName());
}
/**
*
* @param playerName
* @return true if player is registered
*/
@Deprecated
public static boolean isRegistered(final String playerName) {
final String player = playerName.toLowerCase();
return instance.database.isAuthAvailable(player);
}
/**
*
* @param player
* @return true if the player is unrestricted
*/
@Deprecated
public static boolean isUnrestricted(final Player player) {
return Utils.isUnrestricted(player);
}
/**
* Register a player
*
* @param String
* playerName, String password
* @return true if the player is register correctly
*/
@Deprecated
public static boolean registerPlayer(final String playerName, final String password) {
try {
final String name = playerName.toLowerCase();
final String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
if (isRegistered(name)) {
return false;
}
final PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", playerName);
if (!instance.database.saveAuth(auth)) {
return false;
}
return true;
} catch (final NoSuchAlgorithmException ex) {
return false;
}
}
@Deprecated
public static void setPlayerInventory(final Player player, final ItemStack[] content, final ItemStack[] armor) {
try {
player.getInventory().setContents(content);
player.getInventory().setArmorContents(armor);
} catch (final NullPointerException npe) {
}
}
@Deprecated
public AuthMe getPlugin() {
return instance;
}
/**
*
* @param player
* @return true if player is a npc
*/
@Deprecated
public boolean isaNPC(final Player player) {
return Utils.isNPC(player);
}
/**
*
* @param player
* @return true if player is a npc
*/
@Deprecated
public boolean isNPC(final Player player) {
return Utils.isNPC(player);
}
}

View File

@ -0,0 +1,155 @@
package fr.xephi.authme.api;
import java.security.NoSuchAlgorithmException;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
public class NewAPI {
public static final String newline = System.getProperty("line.separator");
public static NewAPI singleton;
public AuthMe plugin;
public NewAPI(final AuthMe plugin) {
this.plugin = plugin;
}
public NewAPI(final Server serv) {
this.plugin = (AuthMe) serv.getPluginManager().getPlugin("AuthMe");
}
/**
* Hook into AuthMe
*
* @return AuthMe plugin
*/
public static NewAPI getInstance() {
if (singleton != null) {
return singleton;
}
final Plugin p = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
if (p == null || !(p instanceof AuthMe)) {
return null;
}
final AuthMe authme = (AuthMe) p;
singleton = (new NewAPI(authme));
return singleton;
}
/**
* @param String
* playerName, String passwordToCheck
* @return true if the password is correct , false else
*/
public boolean checkPassword(final String playerName, final String passwordToCheck) {
if (!isRegistered(playerName)) {
return false;
}
final String player = playerName.toLowerCase();
final PlayerAuth auth = plugin.database.getAuth(player);
try {
return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
} catch (final NoSuchAlgorithmException e) {
return false;
}
}
/**
* Force a player to login
*
* @param Player
* player
*/
public void forceLogin(final Player player) {
plugin.management.performLogin(player, "dontneed", true);
}
public Location getLastLocation(final Player player) {
try {
final PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
if (auth != null) {
return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
} else {
return null;
}
} catch (final NullPointerException ex) {
return null;
}
}
public AuthMe getPlugin() {
return plugin;
}
/**
*
* @param player
* @return true if player is authenticate
*/
public boolean isAuthenticated(final Player player) {
return PlayerCache.getInstance().isAuthenticated(player.getName());
}
/**
*
* @param player
* @return true if player is a npc
*/
public boolean isNPC(final Player player) {
return Utils.isNPC(player);
}
/**
*
* @param playerName
* @return true if player is registered
*/
public boolean isRegistered(final String playerName) {
final String player = playerName.toLowerCase();
return plugin.database.isAuthAvailable(player);
}
/**
*
* @param player
* @return true if the player is unrestricted
*/
public boolean isUnrestricted(final Player player) {
return Utils.isUnrestricted(player);
}
/**
* Register a player
*
* @param String
* playerName, String password
* @return true if the player is register correctly
*/
public boolean registerPlayer(final String playerName, final String password) {
try {
final String name = playerName.toLowerCase();
final String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
if (isRegistered(name)) {
return false;
}
final PlayerAuth auth = new PlayerAuth(name, hash, "127.0.0.1", 0, "mc@mc.com", playerName);
return plugin.database.saveAuth(auth);
} catch (final NoSuchAlgorithmException ex) {
return false;
}
}
}

View File

@ -0,0 +1,263 @@
package fr.xephi.authme.cache.auth;
import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.settings.Settings;
public class PlayerAuth {
private String email = "your@email.com";
private int groupId = -1;
private String hash = "";
private String ip = "192.168.0.1";
private long lastLogin = 0;
private String nickname = "";
private String realName;
private String salt = "";
private String vBhash = null;
private String world = "world";
private double x = 0;
private double y = 0;
private double z = 0;
public PlayerAuth(String nickname, double x, double y, double z, String world, String realName) {
this.nickname = nickname;
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.realName = realName;
this.lastLogin = System.currentTimeMillis();
}
public PlayerAuth(String nickname, String ip, long lastLogin, String realName) {
this.nickname = nickname;
this.ip = ip;
this.lastLogin = lastLogin;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.salt = salt;
this.groupId = groupId;
this.email = email;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.salt = salt;
this.groupId = groupId;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.email = email;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String realName) {
this.nickname = nickname;
this.ip = ip;
this.lastLogin = lastLogin;
this.hash = hash;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.email = email;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.salt = salt;
this.email = email;
this.realName = realName;
}
public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, String realName) {
this.nickname = nickname;
this.hash = hash;
this.ip = ip;
this.lastLogin = lastLogin;
this.salt = salt;
this.realName = realName;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PlayerAuth)) {
return false;
}
PlayerAuth other = (PlayerAuth) obj;
return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname);
}
public String getEmail() {
return email;
}
public int getGroupId() {
return groupId;
}
public String getHash() {
if (Settings.getPasswordHash == HashAlgorithm.MD5VB) {
if (salt != null && !salt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MD5VB) {
vBhash = "$MD5vb$" + salt + "$" + hash;
return vBhash;
}
}
return hash;
}
public String getIp() {
if (ip == null || ip.isEmpty())
ip = "127.0.0.1";
return ip;
}
public long getLastLogin() {
try {
if (Long.valueOf(lastLogin) == null)
lastLogin = 0L;
} catch (NullPointerException e) {
lastLogin = 0L;
}
return lastLogin;
}
public String getNickname() {
return nickname;
}
public double getQuitLocX() {
return x;
}
public double getQuitLocY() {
return y;
}
public double getQuitLocZ() {
return z;
}
public String getRealName() {
return realName;
}
public String getSalt() {
return this.salt;
}
public String getWorld() {
return world;
}
@Override
public int hashCode() {
int hashCode = 7;
hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0);
hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0);
return hashCode;
}
public void set(PlayerAuth auth) {
this.setEmail(auth.getEmail());
this.setHash(auth.getHash());
this.setIp(auth.getIp());
this.setLastLogin(auth.getLastLogin());
this.setName(auth.getNickname());
this.setQuitLocX(auth.getQuitLocX());
this.setQuitLocY(auth.getQuitLocY());
this.setQuitLocZ(auth.getQuitLocZ());
this.setSalt(auth.getSalt());
this.setWorld(auth.getWorld());
this.setRealName(auth.getRealName());
}
public void setEmail(String email) {
this.email = email;
}
public void setHash(String hash) {
this.hash = hash;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setLastLogin(long lastLogin) {
this.lastLogin = lastLogin;
}
public void setName(String nickname) {
this.nickname = nickname;
}
public void setQuitLocX(double d) {
this.x = d;
}
public void setQuitLocY(double d) {
this.y = d;
}
public void setQuitLocZ(double d) {
this.z = d;
}
public void setRealName(String realName) {
this.realName = realName;
}
public void setSalt(String salt) {
this.salt = salt;
}
public void setWorld(String world) {
this.world = world;
}
@Override
public String toString() {
String s = "Player : " + nickname + " | " + realName + " ! IP : " + ip + " ! LastLogin : " + lastLogin + " ! LastPosition : " + x + "," + y + "," + z + "," + world + " ! Email : " + email
+ " ! Hash : " + hash + " ! Salt : " + salt;
return s;
}
}

View File

@ -0,0 +1,50 @@
package fr.xephi.authme.cache.auth;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerCache {
private volatile static PlayerCache singleton = null;
private ConcurrentHashMap<String, PlayerAuth> cache;
private PlayerCache() {
cache = new ConcurrentHashMap<>();
}
public static PlayerCache getInstance() {
if (singleton == null) {
singleton = new PlayerCache();
}
return singleton;
}
public void addPlayer(PlayerAuth auth) {
cache.put(auth.getNickname().toLowerCase(), auth);
}
public PlayerAuth getAuth(String user) {
return cache.get(user.toLowerCase());
}
public ConcurrentHashMap<String, PlayerAuth> getCache() {
return this.cache;
}
public int getLogged() {
return cache.size();
}
public boolean isAuthenticated(String user) {
return cache.containsKey(user.toLowerCase());
}
public void removePlayer(String user) {
cache.remove(user.toLowerCase());
}
public void updatePlayer(PlayerAuth auth) {
cache.remove(auth.getNickname().toLowerCase());
cache.put(auth.getNickname().toLowerCase(), auth);
}
}

View File

@ -0,0 +1,26 @@
package fr.xephi.authme.cache.backup;
public class DataFileCache {
private boolean flying;
private String group;
private boolean operator;
public DataFileCache(String group, boolean operator, boolean flying) {
this.group = group;
this.operator = operator;
this.flying = flying;
}
public String getGroup() {
return group;
}
public boolean getOperator() {
return operator;
}
public boolean isFlying() {
return flying;
}
}

View File

@ -0,0 +1,158 @@
package fr.xephi.authme.cache.backup;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import org.bukkit.entity.Player;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.settings.Settings;
public class JsonCache {
private final File cacheDir;
private final Gson gson;
public JsonCache() {
cacheDir = Settings.CACHE_FOLDER;
if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) {
ConsoleLogger.showError("Failed to create cache directory.");
}
gson = new GsonBuilder()
.registerTypeAdapter(DataFileCache.class, new PlayerDataSerializer())
.registerTypeAdapter(DataFileCache.class, new PlayerDataDeserializer())
.setPrettyPrinting()
.create();
}
public void createCache(Player player, DataFileCache playerData) {
if (player == null) {
return;
}
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path + File.separator + "cache.json");
if (file.exists()) {
return;
}
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
return;
}
try {
String data = gson.toJson(playerData);
Files.touch(file);
Files.write(data, file, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean doesCacheExist(Player player) {
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path + File.separator + "cache.json");
return file.exists();
}
public DataFileCache readCache(Player player) {
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path + File.separator + "cache.json");
if (!file.exists()) {
return null;
}
try {
String str = Files.toString(file, Charsets.UTF_8);
return gson.fromJson(str, DataFileCache.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void removeCache(Player player) {
String path;
try {
path = player.getUniqueId().toString();
} catch (Exception | Error e) {
path = player.getName().toLowerCase();
}
File file = new File(cacheDir, path);
if (file.exists()) {
Utils.purgeDirectory(file);
if (!file.delete()) {
ConsoleLogger.showError("Failed to remove" + player.getName() + "cache.");
}
}
}
private static class PlayerDataDeserializer implements JsonDeserializer<DataFileCache> {
@Override
public DataFileCache deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject == null) {
return null;
}
JsonElement e;
String group = null;
boolean operator = false;
boolean flying = false;
if ((e = jsonObject.get("group")) != null) {
group = e.getAsString();
}
if ((e = jsonObject.get("operator")) != null) {
operator = e.getAsBoolean();
}
if ((e = jsonObject.get("flying")) != null) {
flying = e.getAsBoolean();
}
return new DataFileCache(group, operator, flying);
}
}
private class PlayerDataSerializer implements JsonSerializer<DataFileCache> {
@Override
public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("group", dataFileCache.getGroup());
jsonObject.addProperty("operator", dataFileCache.getOperator());
jsonObject.addProperty("flying", dataFileCache.isFlying());
return jsonObject;
}
}
}

View File

@ -0,0 +1,123 @@
package fr.xephi.authme.cache.limbo;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.backup.DataFileCache;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.events.ResetInventoryEvent;
import fr.xephi.authme.events.StoreInventoryEvent;
import fr.xephi.authme.settings.Settings;
public class LimboCache {
private volatile static LimboCache singleton;
public ConcurrentHashMap<String, LimboPlayer> cache;
public AuthMe plugin;
private JsonCache playerData;
private LimboCache(AuthMe plugin) {
this.plugin = plugin;
this.cache = new ConcurrentHashMap<>();
this.playerData = new JsonCache();
}
public static LimboCache getInstance() {
if (singleton == null) {
singleton = new LimboCache(AuthMe.getInstance());
}
return singleton;
}
public void addLimboPlayer(Player player) {
String name = player.getName().toLowerCase();
Location loc = player.getLocation();
GameMode gameMode = player.getGameMode();
boolean operator = false;
String playerGroup = "";
boolean flying = false;
if (playerData.doesCacheExist(player)) {
final StoreInventoryEvent event = new StoreInventoryEvent(player, playerData);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
player.getInventory().setContents(event.getInventory());
player.getInventory().setArmorContents(event.getArmor());
}
DataFileCache cache = playerData.readCache(player);
if (cache != null) {
playerGroup = cache.getGroup();
operator = cache.getOperator();
flying = cache.isFlying();
}
} else {
StoreInventoryEvent event = new StoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
player.getInventory().setContents(event.getInventory());
player.getInventory().setArmorContents(event.getArmor());
}
operator = player.isOp();
flying = player.isFlying();
if (plugin.permission != null) {
try {
playerGroup = plugin.permission.getPrimaryGroup(player);
} catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
plugin.permission = null;
}
}
}
if (Settings.isForceSurvivalModeEnabled) {
if (Settings.isResetInventoryIfCreative && gameMode == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
player.getInventory().clear();
player.sendMessage("Your inventory has been cleaned!");
}
}
if (gameMode == GameMode.CREATIVE) {
flying = false;
}
gameMode = GameMode.SURVIVAL;
}
if (player.isDead()) {
loc = plugin.getSpawnLocation(player);
}
cache.put(name, new LimboPlayer(name, loc, gameMode, operator, playerGroup, flying));
}
public void addLimboPlayer(Player player, String group) {
cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group));
}
public void deleteLimboPlayer(String name) {
cache.remove(name);
}
public LimboPlayer getLimboPlayer(String name) {
return cache.get(name);
}
public boolean hasLimboPlayer(String name) {
return cache.containsKey(name);
}
public void updateLimboPlayer(Player player) {
if (this.hasLimboPlayer(player.getName().toLowerCase())) {
this.deleteLimboPlayer(player.getName().toLowerCase());
}
addLimboPlayer(player);
}
}

View File

@ -0,0 +1,75 @@
package fr.xephi.authme.cache.limbo;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.scheduler.BukkitTask;
public class LimboPlayer {
private boolean flying = false;
private GameMode gameMode = GameMode.SURVIVAL;
private String group = "";
private Location loc = null;
private BukkitTask messageTaskId = null;
private String name;
private boolean operator = false;
private BukkitTask timeoutTaskId = null;
public LimboPlayer(String name, Location loc, GameMode gameMode, boolean operator, String group, boolean flying) {
this.name = name;
this.loc = loc;
this.gameMode = gameMode;
this.operator = operator;
this.group = group;
this.flying = flying;
}
public LimboPlayer(String name, String group) {
this.name = name;
this.group = group;
}
public GameMode getGameMode() {
return gameMode;
}
public String getGroup() {
return group;
}
public Location getLoc() {
return loc;
}
public BukkitTask getMessageTaskId() {
return messageTaskId;
}
public String getName() {
return name;
}
public boolean getOperator() {
return operator;
}
public BukkitTask getTimeoutTaskId() {
return timeoutTaskId;
}
public boolean isFlying() {
return flying;
}
public void setMessageTaskId(BukkitTask messageTaskId) {
if (this.messageTaskId != null)
this.messageTaskId.cancel();
this.messageTaskId = messageTaskId;
}
public void setTimeoutTaskId(BukkitTask i) {
if (this.timeoutTaskId != null)
this.timeoutTaskId.cancel();
this.timeoutTaskId = i;
}
}

View File

@ -0,0 +1,613 @@
package fr.xephi.authme.commands;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class AdminCommand implements CommandExecutor {
public AuthMe plugin;
private final Messages m = Messages.getInstance();
public AdminCommand(final AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(final CommandSender sender, final Command cmnd, final String label, final String[] args) {
if (args.length == 0) {
sender.sendMessage("Usage:");
sender.sendMessage("/authme reload - Reload the config");
sender.sendMessage("/authme version - Get AuthMe version info");
sender.sendMessage("/authme register <playername> <password> - Register a player");
sender.sendMessage("/authme unregister <playername> - Unregister a player");
sender.sendMessage("/authme changepassword <playername> <password> - Change a player's password");
sender.sendMessage("/authme chgemail <playername> <email> - Change a player's email");
sender.sendMessage("/authme getemail <playername> - Get a player's email");
sender.sendMessage("/authme getip <onlineplayername> - Display a player's IP if he's online");
sender.sendMessage("/authme lastlogin <playername> - Display the date of a player's last login");
sender.sendMessage("/authme accounts <playername> - Display all player's accounts");
sender.sendMessage("/authme purge <days> - Purge database");
sender.sendMessage("/authme purgebannedplayers - Purge database from banned players");
sender.sendMessage("/authme purgelastpos <playername> - Purge last position infos for a player");
sender.sendMessage("/authme setspawn - Set player's spawn to your current position");
sender.sendMessage("/authme setfirstspawn - Set player's first spawn to your current position");
sender.sendMessage("/authme spawn - Teleport yourself to the spawn point");
sender.sendMessage("/authme firstspawn - Teleport yourself to the first spawn point");
sender.sendMessage("/authme switchantibot on/off - Enable/Disable AntiBot feature");
sender.sendMessage("/authme forcelogin <playername> - Enforce the login of a connected player");
return true;
}
if (!plugin.authmePermissible(sender, "authme.admin." + args[0].toLowerCase())) {
m.send(sender, "no_perm");
return true;
}
if (args[0].equalsIgnoreCase("version")) {
sender.sendMessage("AuthMe Version: " + AuthMe.getInstance().getDescription().getVersion());
return true;
}
if (args[0].equalsIgnoreCase("purge")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme purge <days>");
return true;
}
if (Integer.parseInt(args[1]) < 30) {
sender.sendMessage("You can only purge data older than 30 days");
return true;
}
try {
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -(Integer.parseInt(args[1])));
final long until = calendar.getTimeInMillis();
final List<String> purged = plugin.database.autoPurgeDatabase(until);
sender.sendMessage("Deleted " + purged.size() + " user accounts");
if (Settings.purgeEssentialsFile && plugin.ess != null) {
plugin.dataManager.purgeEssentials(purged);
}
if (Settings.purgePlayerDat) {
plugin.dataManager.purgeDat(purged);
}
if (Settings.purgeLimitedCreative) {
plugin.dataManager.purgeLimitedCreative(purged);
}
if (Settings.purgeAntiXray) {
plugin.dataManager.purgeAntiXray(purged);
}
sender.sendMessage("[AuthMe] Database has been purged correctly");
return true;
} catch (final NumberFormatException e) {
sender.sendMessage("Usage: /authme purge <days>");
return true;
}
} else if (args[0].equalsIgnoreCase("reload")) {
try {
Settings.reload();
plugin.getModuleManager().reloadModules();
m.reloadMessages();
plugin.setupDatabase();
} catch (final Exception e) {
ConsoleLogger.showError("Fatal error occurred! Authme instance ABORTED!");
ConsoleLogger.writeStackTrace(e);
plugin.stopOrUnload();
return false;
}
m.send(sender, "reload");
} else if (args[0].equalsIgnoreCase("lastlogin")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme lastlogin <playername>");
return true;
}
PlayerAuth auth;
try {
auth = plugin.database.getAuth(args[1].toLowerCase());
} catch (final NullPointerException e) {
m.send(sender, "unknown_user");
return true;
}
if (auth == null) {
m.send(sender, "user_unknown");
return true;
}
final long lastLogin = auth.getLastLogin();
final Date d = new Date(lastLogin);
final long diff = System.currentTimeMillis() - lastLogin;
final String msg = (int) (diff / 86400000) + " days " + (int) (diff / 3600000 % 24) + " hours " + (int) (diff / 60000 % 60) + " mins " + (int) (diff / 1000 % 60) + " secs.";
final String lastIP = auth.getIp();
sender.sendMessage("[AuthMe] " + args[1] + " lastlogin : " + d.toString());
sender.sendMessage("[AuthMe] The player " + auth.getNickname() + " is unlogged since " + msg);
sender.sendMessage("[AuthMe] Last Player's IP: " + lastIP);
} else if (args[0].equalsIgnoreCase("accounts")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme accounts <playername>");
sender.sendMessage("Or: /authme accounts <ip>");
return true;
}
if (!args[1].contains(".")) {
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
PlayerAuth auth;
final StringBuilder message = new StringBuilder("[AuthMe] ");
try {
auth = plugin.database.getAuth(arguments[1].toLowerCase());
} catch (final NullPointerException npe) {
m.send(sender, "unknown_user");
return;
}
if (auth == null) {
m.send(sender, "unknown_user");
return;
}
final List<String> accountList = plugin.database.getAllAuthsByName(auth);
if (accountList == null || accountList.isEmpty()) {
m.send(sender, "user_unknown");
return;
}
if (accountList.size() == 1) {
sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return;
}
int i = 0;
for (final String account : accountList) {
i++;
message.append(account);
if (i != accountList.size()) {
message.append(", ");
} else {
message.append(".");
}
}
sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
sender.sendMessage(message.toString());
}
});
return true;
} else {
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
final StringBuilder message = new StringBuilder("[AuthMe] ");
if (arguments[1] == null) {
sender.sendMessage("[AuthMe] Please put a valid IP");
return;
}
final List<String> accountList = plugin.database.getAllAuthsByIp(arguments[1]);
if (accountList == null || accountList.isEmpty()) {
sender.sendMessage("[AuthMe] This IP does not exist in the database");
return;
}
if (accountList.size() == 1) {
sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return;
}
int i = 0;
for (final String account : accountList) {
i++;
message.append(account);
if (i != accountList.size()) {
message.append(", ");
} else {
message.append(".");
}
}
sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
sender.sendMessage(message.toString());
}
});
return true;
}
} else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme register <playername> <password>");
return true;
}
final String name = args[1].toLowerCase();
final String lowpass = args[2].toLowerCase();
if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select")
|| lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
m.send(sender, "password_error");
return true;
}
if (lowpass.equalsIgnoreCase(args[1])) {
m.send(sender, "password_error_nick");
return true;
}
if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
m.send(sender, "pass_len");
return true;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(lowpass)) {
m.send(sender, "password_error_unsafe");
return true;
}
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
if (plugin.database.isAuthAvailable(name)) {
m.send(sender, "user_regged");
return;
}
final String hash = PasswordSecurity.getHash(Settings.getPasswordHash, lowpass, name);
final PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com", name);
if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) {
auth.setSalt(PasswordSecurity.userSalt.get(name));
} else {
auth.setSalt("");
}
if (!plugin.database.saveAuth(auth)) {
m.send(sender, "error");
return;
}
m.send(sender, "registered");
ConsoleLogger.info(name + " registered");
} catch (final NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(sender, "error");
}
}
});
return true;
} else if (args[0].equalsIgnoreCase("getemail")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme getemail <playername>");
return true;
}
final String playername = args[1].toLowerCase();
final PlayerAuth auth = plugin.database.getAuth(playername);
if (auth == null) {
m.send(sender, "unknown_user");
return true;
}
sender.sendMessage("[AuthMe] " + args[1] + "'s email: " + auth.getEmail());
return true;
} else if (args[0].equalsIgnoreCase("chgemail")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme chgemail <playername> <email>");
return true;
}
if (!Settings.isEmailCorrect(args[2])) {
m.send(sender, "email_invalid");
return true;
}
final String playername = args[1].toLowerCase();
final PlayerAuth auth = plugin.database.getAuth(playername);
if (auth == null) {
m.send(sender, "unknown_user");
return true;
}
auth.setEmail(args[2]);
if (!plugin.database.updateEmail(auth)) {
m.send(sender, "error");
return true;
}
if (PlayerCache.getInstance().getAuth(playername) != null) {
PlayerCache.getInstance().updatePlayer(auth);
}
m.send(sender, "email_changed");
return true;
} else if (args[0].equalsIgnoreCase("setspawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setSpawn(((Player) sender).getLocation())) {
sender.sendMessage("[AuthMe] Correctly defined new spawn point");
} else {
sender.sendMessage("[AuthMe] SetSpawn has failed, please retry");
}
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (final NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("setfirstspawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation())) {
sender.sendMessage("[AuthMe] Correctly defined new first spawn point");
} else {
sender.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry");
}
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (final NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("purgebannedplayers")) {
final List<String> bannedPlayers = new ArrayList<>();
for (final OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(off.getName().toLowerCase());
}
plugin.database.purgeBanned(bannedPlayers);
if (Settings.purgeEssentialsFile && plugin.ess != null) {
plugin.dataManager.purgeEssentials(bannedPlayers);
}
if (Settings.purgePlayerDat) {
plugin.dataManager.purgeDat(bannedPlayers);
}
if (Settings.purgeLimitedCreative) {
plugin.dataManager.purgeLimitedCreative(bannedPlayers);
}
if (Settings.purgeAntiXray) {
plugin.dataManager.purgeAntiXray(bannedPlayers);
}
sender.sendMessage("[AuthMe] Database has been purged correctly");
return true;
} else if (args[0].equalsIgnoreCase("spawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getSpawn() != null) {
((Player) sender).teleport(Spawn.getInstance().getSpawn());
} else {
sender.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn");
}
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (final NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("firstspawn")) {
try {
if (sender instanceof Player) {
if (Spawn.getInstance().getFirstSpawn() != null) {
((Player) sender).teleport(Spawn.getInstance().getFirstSpawn());
} else {
sender.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn");
}
} else {
sender.sendMessage("[AuthMe] Please use that command in game");
}
} catch (final NullPointerException ex) {
ConsoleLogger.showError(ex.getMessage());
}
return true;
} else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme changepassword <playername> <newpassword>");
return true;
}
final String lowpass = args[2].toLowerCase();
if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select")
|| lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
m.send(sender, "password_error");
return true;
}
if (lowpass.equalsIgnoreCase(args[1])) {
m.send(sender, "password_error_nick");
return true;
}
if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
m.send(sender, "pass_len");
return true;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(lowpass)) {
m.send(sender, "password_error_unsafe");
return true;
}
}
final String name = args[1].toLowerCase();
final String raw = args[2];
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
String hash;
try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, raw, name);
} catch (final NoSuchAlgorithmException e) {
m.send(sender, "error");
return;
}
PlayerAuth auth = null;
if (PlayerCache.getInstance().isAuthenticated(name)) {
auth = PlayerCache.getInstance().getAuth(name);
} else if (plugin.database.isAuthAvailable(name)) {
auth = plugin.database.getAuth(name);
}
if (auth == null) {
m.send(sender, "unknown_user");
return;
}
auth.setHash(hash);
if (PasswordSecurity.userSalt.containsKey(name)) {
auth.setSalt(PasswordSecurity.userSalt.get(name));
plugin.database.updateSalt(auth);
}
if (!plugin.database.updatePassword(auth)) {
m.send(sender, "error");
return;
}
sender.sendMessage("pwd_changed");
ConsoleLogger.info(name + "'s password changed");
}
});
return true;
} else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme unregister <playername>");
return true;
}
final String name = args[1].toLowerCase();
if (!plugin.database.isAuthAvailable(name)) {
m.send(sender, "user_unknown");
return true;
}
if (!plugin.database.removeAuth(name)) {
m.send(sender, "error");
return true;
}
final Player target = Bukkit.getPlayer(name);
PlayerCache.getInstance().removePlayer(name);
Utils.setGroup(target, GroupType.UNREGISTERED);
if (target != null) {
if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
final Location spawn = plugin.getSpawnLocation(target);
final SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
target.teleport(tpEvent.getTo());
}
}
LimboCache.getInstance().addLimboPlayer(target);
final int delay = Settings.getRegistrationTimeout * 20;
final int interval = Settings.getWarnMessageInterval;
final BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) {
final BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, target), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
if (Settings.applyBlindEffect) {
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
}
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
target.setWalkSpeed(0.0f);
target.setFlySpeed(0.0f);
}
m.send(target, "unregistered");
}
}
m.send(sender, "unregistered");
ConsoleLogger.info(args[1] + " unregistered");
return true;
} else if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme purgelastpos <playername>");
return true;
}
try {
final String name = args[1].toLowerCase();
final PlayerAuth auth = plugin.database.getAuth(name);
if (auth == null) {
m.send(sender, "unknown_user");
return true;
}
auth.setQuitLocX(0D);
auth.setQuitLocY(0D);
auth.setQuitLocZ(0D);
auth.setWorld("world");
plugin.database.updateQuitLoc(auth);
sender.sendMessage(name + "'s last position location is now reset");
} catch (final Exception e) {
ConsoleLogger.showError("An error occured while trying to reset location or player do not exist, please see below: ");
ConsoleLogger.showError(e.getMessage());
if (sender instanceof Player) {
sender.sendMessage("An error occured while trying to reset location or player do not exist, please see logs");
}
}
return true;
} else if (args[0].equalsIgnoreCase("switchantibot")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme switchantibot on/off");
return true;
}
if (args[1].equalsIgnoreCase("on")) {
plugin.switchAntiBotMod(true);
sender.sendMessage("[AuthMe] AntiBotMod enabled");
return true;
}
if (args[1].equalsIgnoreCase("off")) {
plugin.switchAntiBotMod(false);
sender.sendMessage("[AuthMe] AntiBotMod disabled");
return true;
}
sender.sendMessage("Usage: /authme switchantibot on/off");
return true;
} else if (args[0].equalsIgnoreCase("getip")) {
if (args.length < 2) {
sender.sendMessage("Usage: /authme getip <onlineplayername>");
return true;
}
final Player player = Bukkit.getPlayer(args[1]);
if (player == null) {
sender.sendMessage("This player is not actually online");
sender.sendMessage("Usage: /authme getip <onlineplayername>");
return true;
}
sender.sendMessage(player.getName() + "'s actual IP is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort());
sender.sendMessage(player.getName() + "'s real IP is : " + plugin.getIP(player));
return true;
} else if (args[0].equalsIgnoreCase("forcelogin")) {
if (args.length < 2) {
sender.sendMessage("Usage: /authme forcelogin <playername>");
return true;
}
try {
final Player player = Bukkit.getPlayer(args[1]);
if (player == null || !player.isOnline()) {
sender.sendMessage("Player needs to be online!");
return true;
}
if (!plugin.authmePermissible(player, "authme.canbeforced")) {
sender.sendMessage("You cannot force login for this player!");
return true;
}
plugin.management.performLogin(player, "dontneed", true);
sender.sendMessage("Force Login performed!");
} catch (final Exception e) {
sender.sendMessage("An error occured while trying to get that player!");
}
} else if (args[0].equalsIgnoreCase("resetname")) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
final List<PlayerAuth> auths = plugin.database.getAllAuths();
for (final PlayerAuth auth : auths) {
auth.setRealName("Player");
plugin.database.updateSession(auth);
}
}
});
} else {
sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername");
}
return true;
}
}

View File

@ -0,0 +1,77 @@
package fr.xephi.authme.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class CaptchaCommand implements CommandExecutor {
public static RandomString rdm = new RandomString(Settings.captchaLength);
public AuthMe plugin;
private Messages m = Messages.getInstance();
public CaptchaCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if (args.length == 0) {
m.send(player, "usage_captcha");
return true;
}
if (PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "logged_in");
return true;
}
if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
m.send(player, "no_perm");
return true;
}
if (!Settings.useCaptcha) {
m.send(player, "usage_log");
return true;
}
if (!plugin.cap.containsKey(name)) {
m.send(player, "usage_log");
return true;
}
if (Settings.useCaptcha && !args[0].equals(plugin.cap.get(name))) {
plugin.cap.remove(name);
plugin.cap.put(name, rdm.nextString());
for (String s : m.send("wrong_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)));
}
return true;
}
try {
plugin.captcha.remove(name);
plugin.cap.remove(name);
} catch (NullPointerException npe) {
}
m.send(player, "valid_captcha");
m.send(player, "login_msg");
return true;
}
}

View File

@ -0,0 +1,69 @@
package fr.xephi.authme.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.ChangePasswordTask;
public class ChangePasswordCommand implements CommandExecutor {
public AuthMe plugin;
private Messages m = Messages.getInstance();
public ChangePasswordCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m.send(sender, "no_perm");
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "not_logged_in");
return true;
}
if (args.length != 2) {
m.send(player, "usage_changepassword");
return true;
}
String lowpass = args[1].toLowerCase();
if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select")
|| lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
m.send(player, "password_error");
return true;
}
if (lowpass.equalsIgnoreCase(name)) {
m.send(player, "password_error_nick");
return true;
}
if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
m.send(player, "pass_len");
return true;
}
if (!Settings.unsafePasswords.isEmpty()) {
if (Settings.unsafePasswords.contains(lowpass)) {
m.send(player, "password_error_unsafe");
return true;
}
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0], args[1]));
return true;
}
}

View File

@ -0,0 +1,110 @@
package fr.xephi.authme.commands;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.converter.Converter;
import fr.xephi.authme.converter.CrazyLoginConverter;
import fr.xephi.authme.converter.FlatToSql;
import fr.xephi.authme.converter.FlatToSqlite;
import fr.xephi.authme.converter.RakamakConverter;
import fr.xephi.authme.converter.RoyalAuthConverter;
import fr.xephi.authme.converter.SqlToFlat;
import fr.xephi.authme.converter.vAuthConverter;
import fr.xephi.authme.settings.Messages;
public class ConverterCommand implements CommandExecutor {
private final Messages m = Messages.getInstance();
private final AuthMe plugin;
public ConverterCommand(final AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(final CommandSender sender, final Command cmnd, final String label, final String[] args) {
if (!plugin.authmePermissible(sender, "authme.admin.converter")) {
m.send(sender, "no_perm");
return true;
}
if (args.length == 0) {
sender.sendMessage("Usage : /converter flattosql | flattosqlite | xauth | crazylogin | rakamak | royalauth | vauth | sqltoflat");
return true;
}
final ConvertType type = ConvertType.fromName(args[0]);
if (type == null) {
m.send(sender, "error");
return true;
}
Converter converter = null;
switch (type) {
case ftsql:
converter = new FlatToSql();
break;
case ftsqlite:
converter = new FlatToSqlite(sender);
break;
case crazylogin:
converter = new CrazyLoginConverter(plugin, sender);
break;
case rakamak:
converter = new RakamakConverter(plugin, sender);
break;
case royalauth:
converter = new RoyalAuthConverter(plugin);
break;
case vauth:
converter = new vAuthConverter(plugin, sender);
break;
case sqltoflat:
converter = new SqlToFlat(plugin, sender);
break;
default:
break;
}
if (converter == null) {
m.send(sender, "error");
return true;
}
Bukkit.getScheduler().runTaskAsynchronously(plugin, converter);
sender.sendMessage("[AuthMe] Successfully converted from " + args[0]);
return true;
}
public enum ConvertType {
crazylogin("crazylogin"),
ftsql("flattosql"),
ftsqlite("flattosqlite"),
rakamak("rakamak"),
royalauth("royalauth"),
sqltoflat("sqltoflat"),
vauth("vauth"),
xauth("xauth");
String name;
ConvertType(final String name) {
this.name = name;
}
public static ConvertType fromName(final String name) {
for (final ConvertType type : ConvertType.values()) {
if (type.getName().equalsIgnoreCase(name)) {
return type;
}
}
return null;
}
String getName() {
return this.name;
}
}
}

View File

@ -0,0 +1,40 @@
package fr.xephi.authme.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.settings.Messages;
public class LoginCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
private AuthMe plugin;
public LoginCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) {
if (!(sender instanceof Player)) {
return true;
}
final Player player = (Player) sender;
if (args.length == 0) {
m.send(player, "usage_log");
return true;
}
if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
m.send(player, "no_perm");
return true;
}
plugin.management.performLogin(player, args[0], false);
return true;
}
}

View File

@ -0,0 +1,36 @@
package fr.xephi.authme.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.settings.Messages;
public class LogoutCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
private AuthMe plugin;
public LogoutCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m.send(sender, "no_perm");
return true;
}
final Player player = (Player) sender;
plugin.management.performLogout(player);
return true;
}
}

View File

@ -0,0 +1,64 @@
package fr.xephi.authme.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class RegisterCommand implements CommandExecutor {
public PlayerAuth auth;
public AuthMe plugin;
private Messages m = Messages.getInstance();
public RegisterCommand(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Player Only! Use 'authme register <playername> <password>' instead");
return true;
}
final Player player = (Player) sender;
if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
m.send(player, "usage_reg");
return true;
}
if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
m.send(player, "no_perm");
return true;
}
if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
if (Settings.doubleEmailCheck) {
if (args.length < 2 || !args[0].equals(args[1])) {
m.send(player, "usage_reg");
return true;
}
}
final String email = args[0];
if (!Settings.isEmailCorrect(email)) {
m.send(player, "email_invalid");
return true;
}
RandomString rand = new RandomString(Settings.getRecoveryPassLength);
final String thePass = rand.nextString();
plugin.management.performRegister(player, thePass, email);
return true;
}
if (args.length > 1 && Settings.getEnablePasswordVerifier)
if (!args[0].equals(args[1])) {
m.send(player, "password_error");
return true;
}
plugin.management.performRegister(player, args[0], "");
return true;
}
}

View File

@ -0,0 +1,139 @@
package fr.xephi.authme.commands;
import java.security.NoSuchAlgorithmException;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class UnregisterCommand implements CommandExecutor {
public AuthMe plugin;
private Messages m = Messages.getInstance();
private JsonCache playerCache;
public UnregisterCommand(AuthMe plugin) {
this.plugin = plugin;
this.playerCache = new JsonCache();
}
@Override
public boolean onCommand(final CommandSender sender, Command cmnd, String label, final String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
m.send(sender, "no_perm");
return true;
}
final Player player = (Player) sender;
final String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "not_logged_in");
return true;
}
if (args.length != 1) {
m.send(player, "usage_unreg");
return true;
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
if (!plugin.database.removeAuth(name)) {
player.sendMessage("error");
return;
}
if (Settings.isForcedRegistrationEnabled) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
player.teleport(tpEvent.getTo());
}
}
player.saveData();
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
if (!Settings.getRegisteredGroup.isEmpty())
Utils.setGroup(player, GroupType.UNREGISTERED);
LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = sender.getServer().getScheduler();
if (delay != 0) {
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
m.send(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
return;
}
if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.setGroup(player, Utils.GroupType.UNREGISTERED);
}
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
// check if Player cache File Exist and delete it, preventing
// duplication of items
if (playerCache.doesCacheExist(player)) {
playerCache.removeCache(player);
}
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.0f);
player.setFlySpeed(0.0f);
}
m.send(player, "unregistered");
ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
}
player.teleport(tpEvent.getTo());
}
}
return;
} else {
m.send(player, "wrong_pwd");
}
} catch (NoSuchAlgorithmException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Internal Error please read the server log");
}
}
});
return true;
}
}

View File

@ -0,0 +1,4 @@
package fr.xephi.authme.converter;
public interface Converter extends Runnable {
}

View File

@ -0,0 +1,69 @@
package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings;
/**
* @author Xephi59
*/
public class CrazyLoginConverter implements Converter {
public DataSource database;
public AuthMe instance;
public CommandSender sender;
public CrazyLoginConverter(AuthMe instance, CommandSender sender) {
this.instance = instance;
this.database = instance.database;
this.sender = sender;
}
public CrazyLoginConverter getInstance() {
return this;
}
@Override
public void run() {
String fileName = Settings.crazyloginFileName;
try {
File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
if (!source.exists()) {
sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!");
return;
}
String line;
BufferedReader users = new BufferedReader(new FileReader(source));
while ((line = users.readLine()) != null) {
if (line.contains("|")) {
String[] args = line.split("\\|");
if (args.length < 2)
continue;
if (args[0].equalsIgnoreCase("name"))
continue;
String playerName = args[0].toLowerCase();
String psw = args[1];
if (psw != null) {
PlayerAuth auth = new PlayerAuth(playerName, psw, "127.0.0.1", System.currentTimeMillis(), playerName);
database.saveAuth(auth);
}
}
}
users.close();
ConsoleLogger.info("CrazyLogin database has been imported correctly");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
ConsoleLogger.showError("Can't open the crazylogin database file! Does it exist?");
}
}
}

View File

@ -0,0 +1,96 @@
package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
/**
* @author Xephi59
*/
public class FlatToSql implements Converter {
private static String columnEmail;
private static String columnID;
private static String columnIp;
private static String columnLastLogin;
private static String columnLogged;
private static String columnName;
private static String columnPassword;
private static String lastlocWorld;
private static String lastlocX;
private static String lastlocY;
private static String lastlocZ;
private static String tableName;
public FlatToSql() {
tableName = Settings.getMySQLTablename;
columnName = Settings.getMySQLColumnName;
columnPassword = Settings.getMySQLColumnPassword;
columnIp = Settings.getMySQLColumnIp;
columnLastLogin = Settings.getMySQLColumnLastLogin;
lastlocX = Settings.getMySQLlastlocX;
lastlocY = Settings.getMySQLlastlocY;
lastlocZ = Settings.getMySQLlastlocZ;
lastlocWorld = Settings.getMySQLlastlocWorld;
columnEmail = Settings.getMySQLColumnEmail;
columnLogged = Settings.getMySQLColumnLogged;
columnID = Settings.getMySQLColumnId;
}
@Override
public void run() {
try {
File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
source.createNewFile();
File output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql");
output.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(source));
BufferedWriter sql = new BufferedWriter(new FileWriter(output));
String createDB = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "',"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld
+ " VARCHAR(255) DEFAULT 'world'," + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged + " SMALLINT NOT NULL DEFAULT '0',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));";
sql.write(createDB);
String line;
String newline;
while ((line = br.readLine()) != null) {
sql.newLine();
String[] args = line.split(":");
if (args.length == 4)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + ","
+ lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3]
+ ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);";
else if (args.length == 7)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + ","
+ lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5]
+ ", " + args[6] + ", 'world', 'your@email.com', 0);";
else if (args.length == 8)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + ","
+ lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5]
+ ", " + args[6] + ", '" + args[7] + "', 'your@email.com', 0);";
else if (args.length == 9)
newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + ","
+ lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5]
+ ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "', 0);";
else
newline = "";
if (!newline.equals(""))
sql.write(newline);
}
sql.close();
br.close();
ConsoleLogger.info("The FlatFile has been converted to authme.sql file");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
ConsoleLogger.showError("Can't open the flat database file! Does it exist?");
}
}
}

View File

@ -0,0 +1,177 @@
package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
public class FlatToSqlite implements Converter {
public CommandSender sender;
private String columnEmail;
private String columnID;
private String columnIp;
private String columnLastLogin;
private String columnName;
private String columnPassword;
private Connection con;
private String database;
private String lastlocWorld;
private String lastlocX;
private String lastlocY;
private String lastlocZ;
private String tableName;
public FlatToSqlite(CommandSender sender) {
this.sender = sender;
}
private static void close(AutoCloseable o) {
if (o != null) {
try {
o.close();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
@Override
public void run() {
database = Settings.getMySQLDatabase;
tableName = Settings.getMySQLTablename;
columnName = Settings.getMySQLColumnName;
columnPassword = Settings.getMySQLColumnPassword;
columnIp = Settings.getMySQLColumnIp;
columnLastLogin = Settings.getMySQLColumnLastLogin;
lastlocX = Settings.getMySQLlastlocX;
lastlocY = Settings.getMySQLlastlocY;
lastlocZ = Settings.getMySQLlastlocZ;
lastlocWorld = Settings.getMySQLlastlocWorld;
columnEmail = Settings.getMySQLColumnEmail;
columnID = Settings.getMySQLColumnId;
File source = new File(Settings.APLUGIN_FOLDER, "auths.db");
if (!source.exists()) {
sender.sendMessage("Source file for FlatFile database not found... Aborting");
return;
}
try {
connect();
setup();
} catch (Exception e) {
sender.sendMessage("Some error appeared while trying to setup and connect to sqlite database... Aborting");
return;
}
try (BufferedReader reader = new BufferedReader(new FileReader(source))) {
String line;
int i = 1;
String newline;
while ((line = reader.readLine()) != null) {
String[] args = line.split(":");
if (args.length == 4)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');";
else if (args.length == 7)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6]
+ ", 'world', 'your@email.com');";
else if (args.length == 8)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6]
+ ", '" + args[7] + "', 'your@email.com');";
else if (args.length == 9)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6]
+ ", '" + args[7] + "', '" + args[8] + "');";
else
newline = "";
if (!newline.equals(""))
saveAuth(newline);
i = i + 1;
}
String resp = "The FlatFile has been converted to " + database + ".db file";
ConsoleLogger.info(resp);
sender.sendMessage(resp);
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Can't open the flat database file!");
} finally {
close(con);
}
}
private synchronized void connect() throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
}
private synchronized boolean saveAuth(String s) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement(s);
pst.executeUpdate();
} catch (SQLException e) {
ConsoleLogger.showError(e.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
private synchronized void setup() throws SQLException {
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnIp);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
}
} finally {
close(rs);
close(st);
}
}
}

View File

@ -0,0 +1,36 @@
package fr.xephi.authme.converter;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.settings.Settings;
public class ForceFlatToSqlite implements Converter {
private DataSource data;
public ForceFlatToSqlite(DataSource data, AuthMe plugin) {
this.data = data;
}
@Override
public void run() {
DataSource sqlite = null;
try {
sqlite = new SQLite();
for (PlayerAuth auth : data.getAllAuths()) {
auth.setRealName("Player");
sqlite.saveAuth(auth);
}
Settings.setValue("DataSource.backend", "sqlite");
ConsoleLogger.info("Database successfully converted to sqlite !");
} catch (Exception e) {
ConsoleLogger.showError("An error appeared while trying to convert flatfile to sqlite ...");
} finally {
if (sqlite != null)
sqlite.close();
}
}
}

View File

@ -0,0 +1,98 @@
package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map.Entry;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
/**
* @author Xephi59
*/
public class RakamakConverter implements Converter {
public DataSource database;
public AuthMe instance;
public CommandSender sender;
public RakamakConverter(AuthMe instance, CommandSender sender) {
this.instance = instance;
this.database = instance.database;
this.sender = sender;
}
public RakamakConverter getInstance() {
return this;
}
@Override
public void run() {
HashAlgorithm hash = Settings.getPasswordHash;
boolean useIP = Settings.rakamakUseIp;
String fileName = Settings.rakamakUsers;
String ipFileName = Settings.rakamakUsersIp;
File source = new File(Settings.APLUGIN_FOLDER, fileName);
File ipfiles = new File(Settings.APLUGIN_FOLDER, ipFileName);
HashMap<String, String> playerIP = new HashMap<>();
HashMap<String, String> playerPSW = new HashMap<>();
try {
BufferedReader users;
BufferedReader ipFile;
ipFile = new BufferedReader(new FileReader(ipfiles));
String line;
if (useIP) {
String tempLine;
while ((tempLine = ipFile.readLine()) != null) {
if (tempLine.contains("=")) {
String[] args = tempLine.split("=");
playerIP.put(args[0], args[1]);
}
}
}
ipFile.close();
users = new BufferedReader(new FileReader(source));
while ((line = users.readLine()) != null) {
if (line.contains("=")) {
String[] arguments = line.split("=");
try {
playerPSW.put(arguments[0], PasswordSecurity.getHash(hash, arguments[1], arguments[0]));
} catch (NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
}
}
}
users.close();
for (Entry<String, String> m : playerPSW.entrySet()) {
String playerName = m.getKey();
String psw = playerPSW.get(playerName);
String ip;
if (useIP) {
ip = playerIP.get(playerName);
} else {
ip = "127.0.0.1";
}
PlayerAuth auth = new PlayerAuth(playerName, psw, ip, System.currentTimeMillis(), playerName);
if (PasswordSecurity.userSalt.containsKey(playerName))
auth.setSalt(PasswordSecurity.userSalt.get(playerName));
database.saveAuth(auth);
}
ConsoleLogger.info("Rakamak database has been imported correctly");
sender.sendMessage("Rakamak database has been imported correctly");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
sender.sendMessage("Can't open the rakamak database file! Does it exist?");
}
}
}

View File

@ -0,0 +1,43 @@
package fr.xephi.authme.converter;
import java.io.File;
import org.bukkit.OfflinePlayer;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
public class RoyalAuthConverter implements Converter {
public AuthMe plugin;
private DataSource data;
public RoyalAuthConverter(AuthMe plugin) {
this.plugin = plugin;
this.data = plugin.database;
}
@Override
public void run() {
for (OfflinePlayer o : plugin.getServer().getOfflinePlayers()) {
try {
String name = o.getName().toLowerCase();
String sp = File.separator;
File file = new File("." + sp + "plugins" + sp + "RoyalAuth" + sp + "userdata" + sp + name + ".yml");
if (data.isAuthAvailable(name))
continue;
if (!file.exists())
continue;
RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file);
PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName());
data.saveAuth(auth);
} catch (Exception e) {
ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Error while trying to import " + o.getName() + " RoyalAuth datas");
}
}
}
}

View File

@ -0,0 +1,22 @@
package fr.xephi.authme.converter;
import java.io.File;
import fr.xephi.authme.settings.CustomConfiguration;
public class RoyalAuthYamlReader extends CustomConfiguration {
public RoyalAuthYamlReader(File file) {
super(file);
load();
save();
}
public String getHash() {
return getString("login.password");
}
public long getLastLogin() {
return getLong("timestamps.quit");
}
}

View File

@ -0,0 +1,47 @@
package fr.xephi.authme.converter;
import java.util.List;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.FlatFile;
import fr.xephi.authme.settings.Messages;
public class SqlToFlat implements Converter {
public DataSource database;
public AuthMe plugin;
public CommandSender sender;
public SqlToFlat(AuthMe plugin, CommandSender sender) {
this.plugin = plugin;
this.database = plugin.database;
this.sender = sender;
}
@Override
public void run() {
try {
FlatFile flat = new FlatFile();
List<PlayerAuth> auths = database.getAllAuths();
int i = 0;
final int size = auths.size();
for (PlayerAuth auth : auths) {
flat.saveAuth(auth);
i++;
if ((i % 100) == 0) {
sender.sendMessage("Conversion Status : " + i + " / " + size);
}
}
sender.sendMessage("Successfully convert from SQL table to file auths.db");
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
Messages.getInstance().send(sender, "error");
}
}
}

View File

@ -0,0 +1,31 @@
package fr.xephi.authme.converter;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource;
public class vAuthConverter implements Converter {
public DataSource database;
public AuthMe plugin;
public CommandSender sender;
public vAuthConverter(AuthMe plugin, CommandSender sender) {
this.plugin = plugin;
this.database = plugin.database;
this.sender = sender;
}
@Override
public void run() {
try {
new vAuthFileReader(plugin, sender).convert();
} catch (Exception e) {
sender.sendMessage(e.getMessage());
ConsoleLogger.showError(e.getMessage());
}
}
}

View File

@ -0,0 +1,77 @@
package fr.xephi.authme.converter;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
public class vAuthFileReader {
public DataSource database;
public AuthMe plugin;
public CommandSender sender;
public vAuthFileReader(AuthMe plugin, CommandSender sender) {
this.plugin = plugin;
this.database = plugin.database;
this.sender = sender;
}
public void convert() throws IOException {
final File file = new File(plugin.getDataFolder().getParent() + "" + File.separator + "vAuth" + File.separator + "passwords.yml");
Scanner scanner;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String name = line.split(": ")[0];
String password = line.split(": ")[1];
PlayerAuth auth;
if (isUUIDinstance(password)) {
String pname;
try {
pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName();
} catch (Exception | NoSuchMethodError e) {
pname = getName(UUID.fromString(name));
}
if (pname == null)
continue;
auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname);
} else {
auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", name);
}
database.saveAuth(auth);
}
} catch (Exception e) {
ConsoleLogger.writeStackTrace(e);
}
}
private String getName(UUID uuid) {
try {
for (OfflinePlayer op : Bukkit.getOfflinePlayers()) {
if (op.getUniqueId().compareTo(uuid) == 0)
return op.getName();
}
} catch (Exception ignored) {
}
return null;
}
private boolean isUUIDinstance(String s) {
if (String.valueOf(s.charAt(8)).equalsIgnoreCase("-"))
return true;
return true;
}
}

View File

@ -0,0 +1,387 @@
package fr.xephi.authme.datasource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
public class CacheDataSource implements DataSource {
private final ConcurrentHashMap<String, PlayerAuth> cache = new ConcurrentHashMap<>();
private final ExecutorService exec;
private final DataSource source;
public CacheDataSource(AuthMe pl, DataSource src) {
this.source = src;
this.exec = Executors.newCachedThreadPool();
/*
* We need to load all players in cache ... It will took more time to
* load the server, but it will be much easier to check for an
* isAuthAvailable !
*/
exec.execute(new Runnable() {
@Override
public void run() {
for (PlayerAuth auth : source.getAllAuths()) {
cache.put(auth.getNickname().toLowerCase(), auth);
}
}
});
}
@Override
public List<String> autoPurgeDatabase(long until) {
List<String> cleared = source.autoPurgeDatabase(until);
if (cleared.size() > 0) {
for (PlayerAuth auth : cache.values()) {
if (auth.getLastLogin() < until) {
cache.remove(auth.getNickname());
}
}
}
return cleared;
}
@Override
public synchronized void close() {
exec.shutdown();
source.close();
}
@Override
public int getAccountsRegistered() {
return cache.size();
}
@Override
public List<PlayerAuth> getAllAuths() {
return new ArrayList<>(cache.values());
}
@Override
public synchronized List<String> getAllAuthsByEmail(String email) {
List<String> result = new ArrayList<>();
for (Map.Entry<String, PlayerAuth> stringPlayerAuthEntry : cache.entrySet()) {
PlayerAuth p = stringPlayerAuthEntry.getValue();
if (p.getEmail().equals(email))
result.add(p.getNickname());
}
return result;
}
@Override
public synchronized List<String> getAllAuthsByIp(String ip) {
List<String> result = new ArrayList<>();
for (Map.Entry<String, PlayerAuth> stringPlayerAuthEntry : cache.entrySet()) {
PlayerAuth p = stringPlayerAuthEntry.getValue();
if (p.getIp().equals(ip))
result.add(p.getNickname());
}
return result;
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
List<String> result = new ArrayList<>();
for (Map.Entry<String, PlayerAuth> stringPlayerAuthEntry : cache.entrySet()) {
PlayerAuth p = stringPlayerAuthEntry.getValue();
if (p.getIp().equals(auth.getIp()))
result.add(p.getNickname());
}
return result;
}
@Override
public synchronized PlayerAuth getAuth(String user) {
user = user.toLowerCase();
if (cache.containsKey(user)) {
return cache.get(user);
}
return null;
}
@Override
public int getIps(String ip) {
int count = 0;
for (Map.Entry<String, PlayerAuth> p : cache.entrySet()) {
if (p.getValue().getIp().equals(ip)) {
count++;
}
}
return count;
}
@Override
public List<PlayerAuth> getLoggedPlayers() {
return new ArrayList<>(PlayerCache.getInstance().getCache().values());
}
@Override
public DataSourceType getType() {
return source.getType();
}
@Override
public synchronized boolean isAuthAvailable(String user) {
return cache.containsKey(user.toLowerCase());
}
@Override
public boolean isLogged(String user) {
user = user.toLowerCase();
return PlayerCache.getInstance().getCache().containsKey(user);
}
@Override
public synchronized void purgeBanned(final List<String> banned) {
exec.execute(new Runnable() {
@Override
public void run() {
source.purgeBanned(banned);
for (PlayerAuth auth : cache.values()) {
if (banned.contains(auth.getNickname())) {
cache.remove(auth.getNickname());
}
}
}
});
}
@Override
public int purgeDatabase(long until) {
int cleared = source.purgeDatabase(until);
if (cleared > 0) {
for (PlayerAuth auth : cache.values()) {
if (auth.getLastLogin() < until) {
cache.remove(auth.getNickname());
}
}
}
return cleared;
}
@Override
public void purgeLogged() {
exec.execute(new Runnable() {
@Override
public void run() {
source.purgeLogged();
}
});
}
@Override
public void reload() {
exec.execute(new Runnable() {
@Override
public void run() {
cache.clear();
source.reload();
for (Player player : Utils.getOnlinePlayers()) {
String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) {
PlayerAuth auth = source.getAuth(user);
cache.put(user, auth);
}
}
}
});
}
@Override
public synchronized boolean removeAuth(String username) {
final String user = username.toLowerCase();
final PlayerAuth auth = cache.get(user);
cache.remove(user);
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.removeAuth(user)) {
cache.put(user, auth);
}
}
});
return true;
}
@Override
public synchronized boolean saveAuth(final PlayerAuth auth) {
cache.put(auth.getNickname(), auth);
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.saveAuth(auth)) {
cache.remove(auth.getNickname());
}
}
});
return true;
}
@Override
public void setLogged(final String user) {
exec.execute(new Runnable() {
@Override
public void run() {
source.setLogged(user.toLowerCase());
}
});
}
@Override
public void setUnlogged(final String user) {
exec.execute(new Runnable() {
@Override
public void run() {
source.setUnlogged(user.toLowerCase());
}
});
}
@Override
public synchronized boolean updateEmail(final PlayerAuth auth) {
if (!cache.containsKey(auth.getNickname())) {
return false;
}
PlayerAuth cachedAuth = cache.get(auth.getNickname());
final String oldEmail = cachedAuth.getEmail();
cachedAuth.setEmail(auth.getEmail());
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname())) {
cache.get(auth.getNickname()).setEmail(oldEmail);
}
}
}
});
return true;
}
@Override
public void updateName(final String oldone, final String newone) {
if (cache.containsKey(oldone)) {
cache.put(newone, cache.get(oldone));
cache.remove(oldone);
}
exec.execute(new Runnable() {
@Override
public void run() {
source.updateName(oldone, newone);
}
});
}
@Override
public synchronized boolean updatePassword(final PlayerAuth auth) {
if (!cache.containsKey(auth.getNickname())) {
return false;
}
final String oldHash = cache.get(auth.getNickname()).getHash();
cache.get(auth.getNickname()).setHash(auth.getHash());
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.updatePassword(auth)) {
if (cache.containsKey(auth.getNickname())) {
cache.get(auth.getNickname()).setHash(oldHash);
}
}
}
});
return true;
}
@Override
public boolean updateQuitLoc(final PlayerAuth auth) {
if (!cache.containsKey(auth.getNickname())) {
return false;
}
final PlayerAuth cachedAuth = cache.get(auth.getNickname());
final double oldX = cachedAuth.getQuitLocX();
final double oldY = cachedAuth.getQuitLocY();
final double oldZ = cachedAuth.getQuitLocZ();
final String oldWorld = cachedAuth.getWorld();
cachedAuth.setQuitLocX(auth.getQuitLocX());
cachedAuth.setQuitLocY(auth.getQuitLocY());
cachedAuth.setQuitLocZ(auth.getQuitLocZ());
cachedAuth.setWorld(auth.getWorld());
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.updateQuitLoc(auth)) {
if (cache.containsKey(auth.getNickname())) {
PlayerAuth cachedAuth = cache.get(auth.getNickname());
cachedAuth.setQuitLocX(oldX);
cachedAuth.setQuitLocY(oldY);
cachedAuth.setQuitLocZ(oldZ);
cachedAuth.setWorld(oldWorld);
}
}
}
});
return true;
}
@Override
public synchronized boolean updateSalt(final PlayerAuth auth) {
if (!cache.containsKey(auth.getNickname())) {
return false;
}
PlayerAuth cachedAuth = cache.get(auth.getNickname());
final String oldSalt = cachedAuth.getSalt();
cachedAuth.setSalt(auth.getSalt());
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname())) {
cache.get(auth.getNickname()).setSalt(oldSalt);
}
}
}
});
return true;
}
@Override
public boolean updateSession(final PlayerAuth auth) {
if (!cache.containsKey(auth.getNickname())) {
return false;
}
PlayerAuth cachedAuth = cache.get(auth.getNickname());
final String oldIp = cachedAuth.getIp();
final long oldLastLogin = cachedAuth.getLastLogin();
final String oldRealName = cachedAuth.getRealName();
cachedAuth.setIp(auth.getIp());
cachedAuth.setLastLogin(auth.getLastLogin());
cachedAuth.setRealName(auth.getRealName());
exec.execute(new Runnable() {
@Override
public void run() {
if (!source.updateSession(auth)) {
if (cache.containsKey(auth.getNickname())) {
PlayerAuth cachedAuth = cache.get(auth.getNickname());
cachedAuth.setIp(oldIp);
cachedAuth.setLastLogin(oldLastLogin);
cachedAuth.setRealName(oldRealName);
}
}
}
});
return true;
}
}

View File

@ -0,0 +1,70 @@
package fr.xephi.authme.datasource;
import java.util.List;
import fr.xephi.authme.cache.auth.PlayerAuth;
public interface DataSource {
List<String> autoPurgeDatabase(long until);
void close();
int getAccountsRegistered();
List<PlayerAuth> getAllAuths();
List<String> getAllAuthsByEmail(String email);
List<String> getAllAuthsByIp(String ip);
List<String> getAllAuthsByName(PlayerAuth auth);
PlayerAuth getAuth(String user);
int getIps(String ip);
List<PlayerAuth> getLoggedPlayers();
DataSourceType getType();
boolean isAuthAvailable(String user);
boolean isLogged(String user);
void purgeBanned(List<String> banned);
int purgeDatabase(long until);
void purgeLogged();
void reload();
boolean removeAuth(String user);
boolean saveAuth(PlayerAuth auth);
void setLogged(String user);
void setUnlogged(String user);
boolean updateEmail(PlayerAuth auth);
void updateName(String oldone, String newone);
boolean updatePassword(PlayerAuth auth);
boolean updateQuitLoc(PlayerAuth auth);
boolean updateSalt(PlayerAuth auth);
boolean updateSession(PlayerAuth auth);
enum DataSourceType {
FILE,
MYSQL,
SQLITE,
SQLITEHIKARI
}
}

View File

@ -0,0 +1,330 @@
package fr.xephi.authme.datasource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import fr.xephi.authme.cache.auth.PlayerAuth;
public class DatabaseCalls implements DataSource {
private DataSource database;
private final ExecutorService exec;
public DatabaseCalls(DataSource database) {
this.database = database;
this.exec = Executors.newCachedThreadPool();
}
@Override
public synchronized List<String> autoPurgeDatabase(final long until) {
try {
return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception {
return database.autoPurgeDatabase(until);
}
}).get();
} catch (Exception e) {
return new ArrayList<>();
}
}
@Override
public synchronized void close() {
exec.shutdown();
database.close();
}
@Override
public synchronized int getAccountsRegistered() {
try {
return exec.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return database.getAccountsRegistered();
}
}).get();
} catch (Exception e) {
return -1;
}
}
@Override
public synchronized List<PlayerAuth> getAllAuths() {
try {
return exec.submit(new Callable<List<PlayerAuth>>() {
public List<PlayerAuth> call() throws Exception {
return database.getAllAuths();
}
}).get();
} catch (Exception e) {
return new ArrayList<>();
}
}
@Override
public synchronized List<String> getAllAuthsByEmail(final String email) {
try {
return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception {
return database.getAllAuthsByEmail(email);
}
}).get();
} catch (Exception e) {
return new ArrayList<>();
}
}
@Override
public synchronized List<String> getAllAuthsByIp(final String ip) {
try {
return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception {
return database.getAllAuthsByIp(ip);
}
}).get();
} catch (Exception e) {
return new ArrayList<>();
}
}
@Override
public synchronized List<String> getAllAuthsByName(final PlayerAuth auth) {
try {
return exec.submit(new Callable<List<String>>() {
public List<String> call() throws Exception {
return database.getAllAuthsByName(auth);
}
}).get();
} catch (Exception e) {
return new ArrayList<>();
}
}
@Override
public synchronized PlayerAuth getAuth(final String user) {
try {
return exec.submit(new Callable<PlayerAuth>() {
public PlayerAuth call() throws Exception {
return database.getAuth(user);
}
}).get();
} catch (Exception e) {
return null;
}
}
@Override
public synchronized int getIps(final String ip) {
try {
return exec.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return database.getIps(ip);
}
}).get();
} catch (Exception e) {
return -1;
}
}
@Override
public List<PlayerAuth> getLoggedPlayers() {
try {
return exec.submit(new Callable<List<PlayerAuth>>() {
public List<PlayerAuth> call() throws Exception {
return database.getLoggedPlayers();
}
}).get();
} catch (Exception e) {
return new ArrayList<>();
}
}
@Override
public synchronized DataSourceType getType() {
return database.getType();
}
@Override
public synchronized boolean isAuthAvailable(final String user) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.isAuthAvailable(user);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized boolean isLogged(final String user) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.isLogged(user);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized void purgeBanned(final List<String> banned) {
new Thread(new Runnable() {
public synchronized void run() {
database.purgeBanned(banned);
}
}).start();
}
@Override
public synchronized int purgeDatabase(final long until) {
try {
return exec.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return database.purgeDatabase(until);
}
}).get();
} catch (Exception e) {
return -1;
}
}
@Override
public synchronized void purgeLogged() {
exec.execute(new Runnable() {
public synchronized void run() {
database.purgeLogged();
}
});
}
@Override
public synchronized void reload() {
database.reload();
}
@Override
public synchronized boolean removeAuth(final String user) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.removeAuth(user);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized boolean saveAuth(final PlayerAuth auth) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.saveAuth(auth);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized void setLogged(final String user) {
exec.execute(new Runnable() {
public synchronized void run() {
database.setLogged(user);
}
});
}
@Override
public synchronized void setUnlogged(final String user) {
exec.execute(new Runnable() {
public synchronized void run() {
database.setUnlogged(user);
}
});
}
@Override
public synchronized boolean updateEmail(final PlayerAuth auth) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.updateEmail(auth);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized void updateName(final String oldone, final String newone) {
exec.execute(new Runnable() {
public synchronized void run() {
database.updateName(oldone, newone);
}
});
}
@Override
public synchronized boolean updatePassword(final PlayerAuth auth) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.updatePassword(auth);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized boolean updateQuitLoc(final PlayerAuth auth) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.updateQuitLoc(auth);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized boolean updateSalt(final PlayerAuth auth) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.updateSalt(auth);
}
}).get();
} catch (Exception e) {
return false;
}
}
@Override
public synchronized boolean updateSession(final PlayerAuth auth) {
try {
return exec.submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
return database.updateSession(auth);
}
}).get();
} catch (Exception e) {
return false;
}
}
}

View File

@ -0,0 +1,770 @@
package fr.xephi.authme.datasource;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Settings;
public class FlatFile implements DataSource {
/*
* file layout:
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:
* LASTPOSWORLD:EMAIL
*
* Old but compatible:
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY
* :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS
* PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM
*/
private File source;
public FlatFile() {
source = Settings.AUTH_FILE;
try {
source.createNewFile();
} catch (IOException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled) {
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
}
e.printStackTrace();
}
}
@Override
public List<String> autoPurgeDatabase(long until) {
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<>();
List<String> cleared = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length >= 4) {
if (Long.parseLong(args[3]) >= until) {
lines.add(line);
continue;
}
}
cleared.add(args[0]);
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
bw.write(l + "\n");
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return cleared;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return cleared;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException ex) {
}
}
}
return cleared;
}
@Override
public synchronized void close() {
}
@Override
public int getAccountsRegistered() {
BufferedReader br = null;
int result = 0;
try {
br = new BufferedReader(new FileReader(source));
while ((br.readLine()) != null) {
result++;
}
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
return result;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
return result;
}
@Override
public List<PlayerAuth> getAllAuths() {
BufferedReader br = null;
List<PlayerAuth> auths = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
switch (args.length) {
case 2:
auths.add(new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0]));
break;
case 3:
auths.add(new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0]));
break;
case 4:
auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0]));
break;
case 7:
auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]),
"unavailableworld", "your@email.com", args[0]));
break;
case 8:
auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
"your@email.com", args[0]));
break;
case 9:
auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
args[8], args[0]));
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return auths;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return auths;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
return auths;
}
@Override
public List<String> getAllAuthsByEmail(String email) {
BufferedReader br = null;
List<String> countEmail = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 8 && args[8].equals(email)) {
countEmail.add(args[0]);
}
}
return countEmail;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
BufferedReader br = null;
List<String> countIp = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 3 && args[2].equals(ip)) {
countIp.add(args[0]);
}
}
return countIp;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
BufferedReader br = null;
List<String> countIp = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 3 && args[2].equals(auth.getIp())) {
countIp.add(args[0]);
}
}
return countIp;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
}
@Override
public synchronized PlayerAuth getAuth(String user) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equalsIgnoreCase(user)) {
switch (args.length) {
case 2:
return new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0]);
case 3:
return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0]);
case 4:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0]);
case 7:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]),
"unavailableworld", "your@email.com", args[0]);
case 8:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
"your@email.com", args[0]);
case 9:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
args[8], args[0]);
}
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return null;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
return null;
}
@Override
public int getIps(String ip) {
BufferedReader br = null;
int countIp = 0;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 3 && args[2].equals(ip)) {
countIp++;
}
}
return countIp;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
}
@Override
public List<PlayerAuth> getLoggedPlayers() {
return new ArrayList<>();
}
@Override
public DataSourceType getType() {
return DataSourceType.FILE;
}
@Override
public synchronized boolean isAuthAvailable(String user) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 1 && args[0].equalsIgnoreCase(user)) {
return true;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
return false;
}
@Override
public boolean isLogged(String user) {
return PlayerCache.getInstance().isAuthenticated(user);
}
@Override
public void purgeBanned(List<String> banned) {
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
try {
if (banned.contains(args[0])) {
lines.add(line);
}
} catch (NullPointerException | ArrayIndexOutOfBoundsException exc) {
}
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
bw.write(l + "\n");
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException ex) {
}
}
}
return;
}
@Override
public int purgeDatabase(long until) {
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<>();
int cleared = 0;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length >= 4) {
if (Long.parseLong(args[3]) >= until) {
lines.add(line);
continue;
}
}
cleared++;
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
bw.write(l + "\n");
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return cleared;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return cleared;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException ex) {
}
}
}
return cleared;
}
@Override
public void purgeLogged() {
}
@Override
public void reload() {
}
@Override
public synchronized boolean removeAuth(String user) {
if (!isAuthAvailable(user)) {
return false;
}
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 1 && !args[0].equals(user)) {
lines.add(line);
}
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
bw.write(l + "\n");
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException ex) {
}
}
}
return true;
}
@Override
public synchronized boolean saveAuth(PlayerAuth auth) {
if (isAuthAvailable(auth.getNickname())) {
return false;
}
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(source, true));
bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":"
+ auth.getWorld() + ":" + auth.getEmail() + "\n");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ex) {
}
}
}
return true;
}
@Override
public void setLogged(String user) {
}
@Override
public void setUnlogged(String user) {
}
@Override
public boolean updateEmail(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line = "";
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
auth.getEmail(), args[0]);
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
if (newAuth != null) {
removeAuth(auth.getNickname());
saveAuth(newAuth);
}
return true;
}
@Override
public void updateName(String oldone, String newone) {
PlayerAuth auth = this.getAuth(oldone);
auth.setName(newone);
this.saveAuth(auth);
this.removeAuth(oldone);
}
@Override
public synchronized boolean updatePassword(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", args[0]);
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]),
"world", "your@email.com", args[0]);
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]),
args[7], "your@email.com", args[0]);
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]),
args[7], args[8], args[0]);
break;
}
default: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", args[0]);
break;
}
}
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
if (newAuth != null) {
removeAuth(auth.getNickname());
saveAuth(newAuth);
}
return true;
}
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equalsIgnoreCase(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), args[0]);
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
if (newAuth != null) {
removeAuth(auth.getNickname());
saveAuth(newAuth);
}
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
return false;
}
@Override
public boolean updateSession(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equalsIgnoreCase(auth.getNickname())) {
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]);
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world",
"your@email.com", args[0]);
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
"your@email.com", args[0]);
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7],
args[8], args[0]);
break;
}
default: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]);
break;
}
}
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
if (newAuth != null) {
removeAuth(auth.getNickname());
saveAuth(newAuth);
}
return true;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,675 @@
package fr.xephi.authme.datasource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings;
public class SQLite implements DataSource {
private String columnEmail;
private String columnGroup;
private String columnID;
private String columnIp;
private String columnLastLogin;
private String columnLogged;
private String columnName;
private String columnPassword;
private String columnRealName;
private String columnSalt;
private Connection con;
private String database;
private String lastlocWorld;
private String lastlocX;
private String lastlocY;
private String lastlocZ;
private String tableName;
public SQLite() throws ClassNotFoundException, SQLException {
this.database = Settings.getMySQLDatabase;
this.tableName = Settings.getMySQLTablename;
this.columnName = Settings.getMySQLColumnName;
this.columnPassword = Settings.getMySQLColumnPassword;
this.columnIp = Settings.getMySQLColumnIp;
this.columnLastLogin = Settings.getMySQLColumnLastLogin;
this.columnSalt = Settings.getMySQLColumnSalt;
this.columnGroup = Settings.getMySQLColumnGroup;
this.lastlocX = Settings.getMySQLlastlocX;
this.lastlocY = Settings.getMySQLlastlocY;
this.lastlocZ = Settings.getMySQLlastlocZ;
this.lastlocWorld = Settings.getMySQLlastlocWorld;
this.columnEmail = Settings.getMySQLColumnEmail;
this.columnID = Settings.getMySQLColumnId;
this.columnLogged = Settings.getMySQLColumnLogged;
this.columnRealName = Settings.getMySQLColumnRealName;
try {
this.connect();
this.setup();
} catch (ClassNotFoundException | SQLException cnf) {
ConsoleLogger.showError("Can't use SQLITE... !");
throw cnf;
}
}
@Override
public List<String> autoPurgeDatabase(long until) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> list = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until);
rs = pst.executeQuery();
while (rs.next()) {
list.add(rs.getString(columnName));
}
return list;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} finally {
close(rs);
close(pst);
}
}
@Override
public synchronized void close() {
try {
con.close();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
@Override
public int getAccountsRegistered() {
int result = 0;
PreparedStatement pst = null;
ResultSet rs;
try {
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
rs = pst.executeQuery();
if (rs != null && rs.next()) {
result = rs.getInt(1);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return result;
} finally {
close(pst);
}
return result;
}
@Override
public List<PlayerAuth> getAllAuths() {
List<PlayerAuth> auths = new ArrayList<>();
PreparedStatement pst = null;
ResultSet rs;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery();
while (rs.next()) {
PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
if (!columnSalt.isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail),
rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX),
rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
auths.add(pAuth);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return auths;
} finally {
close(pst);
}
return auths;
}
@Override
public List<String> getAllAuthsByEmail(String email) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countEmail = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
pst.setString(1, email);
rs = pst.executeQuery();
while (rs.next()) {
countEmail.add(rs.getString(columnName));
}
return countEmail;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally {
close(rs);
close(pst);
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally {
close(rs);
close(pst);
}
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, auth.getIp());
rs = pst.executeQuery();
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally {
close(rs);
close(pst);
}
}
@Override
public synchronized PlayerAuth getAuth(String user) {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user);
rs = pst.executeQuery();
if (rs.next()) {
if (rs.getString(columnIp).isEmpty()) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
if (!columnSalt.isEmpty()) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail),
rs.getString(columnRealName));
} else {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX),
rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
} else {
return null;
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return null;
} finally {
close(rs);
close(pst);
}
}
@Override
public int getIps(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
int countIp = 0;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while (rs.next()) {
countIp++;
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
close(rs);
close(pst);
}
}
@Override
public List<PlayerAuth> getLoggedPlayers() {
List<PlayerAuth> auths = new ArrayList<>();
PreparedStatement pst = null;
ResultSet rs;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery();
while (rs.next()) {
PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
if (!columnSalt.isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail),
rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX),
rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
auths.add(pAuth);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return auths;
} finally {
close(pst);
}
return auths;
}
@Override
public DataSourceType getType() {
return DataSourceType.SQLITE;
}
@Override
public synchronized boolean isAuthAvailable(String user) {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user);
rs = pst.executeQuery();
return rs.next();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(rs);
close(pst);
}
}
@Override
public boolean isLogged(String user) {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, user);
rs = pst.executeQuery();
if (rs.next())
return (rs.getInt(columnLogged) == 1);
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(rs);
close(pst);
}
return false;
}
@Override
public void purgeBanned(List<String> banned) {
PreparedStatement pst = null;
try {
for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, name);
pst.executeUpdate();
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
@Override
public int purgeDatabase(long until) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until);
return pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
close(pst);
}
}
@Override
public void purgeLogged() {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0);
pst.setInt(2, 1);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
@Override
public void reload() {
}
@Override
public synchronized boolean removeAuth(String user) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, user);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
@Override
public synchronized boolean saveAuth(PlayerAuth auth) {
PreparedStatement pst = null;
try {
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
pst = con.prepareStatement(
"INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnRealName + ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin());
pst.setString(5, auth.getRealName());
pst.executeUpdate();
} else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + "," + columnRealName
+ ") VALUES (?,?,?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin());
pst.setString(5, auth.getSalt());
pst.setString(6, auth.getRealName());
pst.executeUpdate();
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
@Override
public void setLogged(String user) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 1);
pst.setString(2, user);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
@Override
public void setUnlogged(String user) {
PreparedStatement pst = null;
if (user != null)
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 0);
pst.setString(2, user);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
@Override
public boolean updateEmail(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
@Override
public void updateName(String oldone, String newone) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE " + columnName + "=?;");
pst.setString(1, newone);
pst.setString(2, oldone);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
@Override
public synchronized boolean updatePassword(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ());
pst.setString(4, auth.getWorld());
pst.setString(5, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
if (columnSalt.isEmpty()) {
return false;
}
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
@Override
public boolean updateSession(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getRealName());
pst.setString(4, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
}
return true;
}
private void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
private void close(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
private synchronized void connect() throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
}
private synchronized void setup() throws SQLException {
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnIp);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT DEFAULT '0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLogged);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLogged + " BIGINT DEFAULT '0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnRealName);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnRealName + " VARCHAR(255) NOT NULL DEFAULT 'Player';");
}
} finally {
close(rs);
close(st);
}
ConsoleLogger.info("SQLite Setup finished");
}
}

View File

@ -0,0 +1,777 @@
package fr.xephi.authme.datasource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings;
public class SQLite_HIKARI implements DataSource {
private String columnEmail;
private String columnGroup;
private String columnID;
private String columnIp;
private String columnLastLogin;
private String columnLogged;
private String columnName;
private String columnPassword;
private String columnRealName;
private String columnSalt;
private String database;
private HikariDataSource ds;
private String lastlocWorld;
private String lastlocX;
private String lastlocY;
private String lastlocZ;
private String tableName;
public SQLite_HIKARI() throws ClassNotFoundException, SQLException {
this.database = Settings.getMySQLDatabase;
this.tableName = Settings.getMySQLTablename;
this.columnName = Settings.getMySQLColumnName;
this.columnPassword = Settings.getMySQLColumnPassword;
this.columnIp = Settings.getMySQLColumnIp;
this.columnLastLogin = Settings.getMySQLColumnLastLogin;
this.columnSalt = Settings.getMySQLColumnSalt;
this.columnGroup = Settings.getMySQLColumnGroup;
this.lastlocX = Settings.getMySQLlastlocX;
this.lastlocY = Settings.getMySQLlastlocY;
this.lastlocZ = Settings.getMySQLlastlocZ;
this.lastlocWorld = Settings.getMySQLlastlocWorld;
this.columnEmail = Settings.getMySQLColumnEmail;
this.columnID = Settings.getMySQLColumnId;
this.columnLogged = Settings.getMySQLColumnLogged;
this.columnRealName = Settings.getMySQLColumnRealName;
// Set the connection arguments
try {
this.setConnectionArguments();
} catch (RuntimeException rt) {
ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer!");
throw rt;
}
// Initialize the database
try {
this.setupConnection();
} catch (SQLException e) {
this.close();
ConsoleLogger.showError("Can't initialize the SQLite database... Please check your database settings in the config.yml file! SHUTDOWN...");
ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
throw e;
}
}
@Override
public List<String> autoPurgeDatabase(long until) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<String> list = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until);
rs = pst.executeQuery();
while (rs.next()) {
list.add(rs.getString(columnName));
}
return list;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public synchronized void close() {
if (ds != null)
ds.close();
}
@Override
public int getAccountsRegistered() {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs;
int result = 0;
try {
con = getConnection();
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
rs = pst.executeQuery();
if (rs != null && rs.next()) {
result = rs.getInt(1);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return result;
} finally {
close(pst);
close(con);
}
return result;
}
@Override
public List<PlayerAuth> getAllAuths() {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs;
List<PlayerAuth> auths = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery();
while (rs.next()) {
PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
if (!columnSalt.isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail),
rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX),
rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
auths.add(pAuth);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return auths;
} finally {
close(pst);
close(con);
}
return auths;
}
@Override
public List<String> getAllAuthsByEmail(String email) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countEmail = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
pst.setString(1, email);
rs = pst.executeQuery();
while (rs.next()) {
countEmail.add(rs.getString(columnName));
}
return countEmail;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, auth.getIp());
rs = pst.executeQuery();
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (NullPointerException npe) {
return new ArrayList<>();
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public synchronized PlayerAuth getAuth(String user) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user);
rs = pst.executeQuery();
if (rs.next()) {
if (rs.getString(columnIp).isEmpty()) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
if (!columnSalt.isEmpty()) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail),
rs.getString(columnRealName));
} else {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX),
rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
} else {
return null;
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return null;
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public int getIps(String ip) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
int countIp = 0;
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while (rs.next()) {
countIp++;
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public List<PlayerAuth> getLoggedPlayers() {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs;
List<PlayerAuth> auths = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery();
while (rs.next()) {
PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
if (!columnSalt.isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp),
rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail),
rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX),
rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
auths.add(pAuth);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
close(con);
}
return auths;
}
@Override
public DataSourceType getType() {
return DataSourceType.SQLITEHIKARI;
}
@Override
public synchronized boolean isAuthAvailable(String user) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user);
rs = pst.executeQuery();
return rs.next();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(rs);
close(pst);
close(con);
}
}
@Override
public boolean isLogged(String user) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, user);
rs = pst.executeQuery();
if (rs.next())
return (rs.getInt(columnLogged) == 1);
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(rs);
close(pst);
close(con);
}
return false;
}
@Override
public void purgeBanned(List<String> banned) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, name);
pst.executeUpdate();
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
close(con);
}
}
@Override
public int purgeDatabase(long until) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst.setLong(1, until);
return pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
close(pst);
close(con);
}
}
@Override
public void purgeLogged() {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0);
pst.setInt(2, 1);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
close(con);
}
}
@Override
public void reload() {
try {
reloadArguments();
} catch (Exception e) {
ConsoleLogger.showError(e.getMessage());
ConsoleLogger.showError("Can't reconnect to SQLite database... Please check your SQLite informations ! SHUTDOWN...");
if (Settings.isStopEnabled) {
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
}
}
@Override
public synchronized boolean removeAuth(String user) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, user);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
@Override
public synchronized boolean saveAuth(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
pst = con.prepareStatement(
"INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnRealName + ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin());
pst.setString(5, auth.getRealName());
pst.executeUpdate();
} else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + "," + columnRealName
+ ") VALUES (?,?,?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin());
pst.setString(5, auth.getSalt());
pst.setString(6, auth.getRealName());
pst.executeUpdate();
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
@Override
public void setLogged(String user) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 1);
pst.setString(2, user);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
close(con);
}
}
@Override
public void setUnlogged(String user) {
Connection con = null;
PreparedStatement pst = null;
if (user != null)
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 0);
pst.setString(2, user);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
close(con);
}
}
@Override
public boolean updateEmail(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
@Override
public void updateName(String oldone, String newone) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE " + columnName + "=?;");
pst.setString(1, newone);
pst.setString(2, oldone);
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
close(con);
}
}
@Override
public synchronized boolean updatePassword(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ());
pst.setString(4, auth.getWorld());
pst.setString(5, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
if (columnSalt.isEmpty()) {
return false;
}
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
@Override
public boolean updateSession(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getRealName());
pst.setString(4, auth.getNickname());
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
close(pst);
close(con);
}
return true;
}
private void close(AutoCloseable o) {
if (o != null) {
try {
o.close();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
}
}
}
private synchronized Connection getConnection() throws SQLException {
return ds.getConnection();
}
private synchronized void reloadArguments() throws ClassNotFoundException, IllegalArgumentException {
if (ds != null) {
ds.close();
}
setConnectionArguments();
ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!");
}
private synchronized void setConnectionArguments() throws RuntimeException {
HikariConfig config = new HikariConfig();
config.setPoolName("AuthMeSQLitePool");
config.setDriverClassName("org.sqlite.JDBC"); // RuntimeException
config.setJdbcUrl("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
config.setConnectionTestQuery("SELECT 1");
config.setMaxLifetime(180000); // 3 Min
config.setIdleTimeout(60000); // 1 Min
config.setMaximumPoolSize(50); // 50 (including idle connections)
ds = new HikariDataSource(config);
ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}
private synchronized void setupConnection() throws SQLException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = getConnection();
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnIp);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT DEFAULT '0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLogged);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLogged + " BIGINT DEFAULT '0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnRealName);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnRealName + " VARCHAR(255) NOT NULL DEFAULT 'Player';");
}
} finally {
close(rs);
close(st);
close(con);
}
ConsoleLogger.info("SQLite Setup finished");
}
}

View File

@ -0,0 +1,41 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
*
* This event is call when a player try to /login
*
* @author Xephi59
*/
public class AuthMeAsyncPreLoginEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private boolean canLogin = true;
private Player player;
public AuthMeAsyncPreLoginEvent(Player player) {
super(true);
this.player = player;
}
public boolean canLogin() {
return canLogin;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public Player getPlayer() {
return player;
}
public void setCanLogin(boolean canLogin) {
this.canLogin = canLogin;
}
}

View File

@ -0,0 +1,40 @@
package fr.xephi.authme.events;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* This event is call when AuthMe try to teleport a player
*
* @author Xephi59
*/
public class AuthMeTeleportEvent extends CustomEvent {
private Location from;
private Player player;
private Location to;
public AuthMeTeleportEvent(Player player, Location to) {
this.player = player;
this.from = player.getLocation();
this.to = to;
}
public Location getFrom() {
return from;
}
public Player getPlayer() {
return player;
}
public Location getTo() {
return to;
}
public void setTo(Location to) {
this.to = to;
}
}

View File

@ -0,0 +1,40 @@
package fr.xephi.authme.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
*
* @author Xephi59
*/
public class CustomEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean isCancelled;
public CustomEvent() {
super(false);
}
public CustomEvent(boolean b) {
super(b);
}
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() {
return handlers;
}
public boolean isCancelled() {
return this.isCancelled;
}
public void setCancelled(boolean cancelled) {
this.isCancelled = cancelled;
}
}

View File

@ -0,0 +1,41 @@
package fr.xephi.authme.events;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* Called if a player is teleported to the authme first spawn
*
* @author Xephi59
*/
public class FirstSpawnTeleportEvent extends CustomEvent {
private Location from;
private Player player;
private Location to;
public FirstSpawnTeleportEvent(Player player, Location from, Location to) {
super(true);
this.player = player;
this.from = from;
this.to = to;
}
public Location getFrom() {
return from;
}
public Player getPlayer() {
return player;
}
public Location getTo() {
return to;
}
public void setTo(Location to) {
this.to = to;
}
}

View File

@ -0,0 +1,51 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
*
* This event is called when a player login or register through AuthMe. The
* boolean 'isLogin' will be false if, and only if, login/register failed.
*
* @author Xephi59
*/
public class LoginEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private boolean isLogin;
private Player player;
public LoginEvent(Player player, boolean isLogin) {
this.player = player;
this.isLogin = isLogin;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public Player getPlayer() {
return this.player;
}
public boolean isLogin() {
return isLogin;
}
@Deprecated
public void setLogin(boolean isLogin) {
this.isLogin = isLogin;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -0,0 +1,39 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
*
* This event is called when a player logout through AuthMe.
*
* @author Xephi59
*/
public class LogoutEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Player player;
public LogoutEvent(Player player) {
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public Player getPlayer() {
return this.player;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -0,0 +1,51 @@
package fr.xephi.authme.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import fr.xephi.authme.security.crypts.EncryptionMethod;
/**
* <p>
* This event is called when we need to compare or get an hash password, for set
* a custom EncryptionMethod
* </p>
*
* @see fr.xephi.authme.security.crypts.EncryptionMethod
*
* @author Xephi59
*/
public class PasswordEncryptionEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private EncryptionMethod method = null;
private String playerName = "";
public PasswordEncryptionEvent(EncryptionMethod method, String playerName) {
super(false);
this.method = method;
this.playerName = playerName;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public EncryptionMethod getMethod() {
return method;
}
public String getPlayerName() {
return playerName;
}
public void setMethod(EncryptionMethod method) {
this.method = method;
}
}

View File

@ -0,0 +1,58 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
*
* This event is call just after store inventory into cache and will empty the
* player inventory.
*
* @author Xephi59
*/
public class ProtectInventoryEvent extends CustomEvent {
private ItemStack[] emptyArmor = null;
private ItemStack[] emptyInventory = null;
private Player player;
private ItemStack[] storedarmor;
private ItemStack[] storedinventory;
public ProtectInventoryEvent(Player player) {
super(true);
this.player = player;
this.storedinventory = player.getInventory().getContents();
this.storedarmor = player.getInventory().getArmorContents();
this.emptyInventory = new ItemStack[36];
this.emptyArmor = new ItemStack[4];
}
public ItemStack[] getEmptyArmor() {
return this.emptyArmor;
}
public ItemStack[] getEmptyInventory() {
return this.emptyInventory;
}
public Player getPlayer() {
return this.player;
}
public ItemStack[] getStoredArmor() {
return this.storedarmor;
}
public ItemStack[] getStoredInventory() {
return this.storedinventory;
}
public void setNewArmor(ItemStack[] emptyArmor) {
this.emptyArmor = emptyArmor;
}
public void setNewInventory(ItemStack[] emptyInventory) {
this.emptyInventory = emptyInventory;
}
}

View File

@ -0,0 +1,41 @@
package fr.xephi.authme.events;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* This event is call if, and only if, a player is teleported just after a
* register.
*
* @author Xephi59
*/
public class RegisterTeleportEvent extends CustomEvent {
private Location from;
private Player player;
private Location to;
public RegisterTeleportEvent(Player player, Location to) {
this.player = player;
this.from = player.getLocation();
this.to = to;
}
public Location getFrom() {
return from;
}
public Player getPlayer() {
return player;
}
public Location getTo() {
return to;
}
public void setTo(Location to) {
this.to = to;
}
}

View File

@ -0,0 +1,28 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
/**
*
* This event is call when a creative inventory is reseted.
*
* @author Xephi59
*/
public class ResetInventoryEvent extends CustomEvent {
private Player player;
public ResetInventoryEvent(Player player) {
super(true);
this.player = player;
}
public Player getPlayer() {
return this.player;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -0,0 +1,30 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
/**
* This event restore the inventory.
*
* @author Xephi59
*/
public class RestoreInventoryEvent extends CustomEvent {
private Player player;
public RestoreInventoryEvent(Player player) {
this.player = player;
}
public RestoreInventoryEvent(Player player, boolean async) {
super(async);
this.player = player;
}
public Player getPlayer() {
return this.player;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -0,0 +1,46 @@
package fr.xephi.authme.events;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
*
* Called if a player is teleported to a specific spawn
*
* @author Xephi59
*/
public class SpawnTeleportEvent extends CustomEvent {
private Location from;
private boolean isAuthenticated;
private Player player;
private Location to;
public SpawnTeleportEvent(Player player, Location from, Location to, boolean isAuthenticated) {
this.player = player;
this.from = from;
this.to = to;
this.isAuthenticated = isAuthenticated;
}
public Location getFrom() {
return from;
}
public Player getPlayer() {
return player;
}
public Location getTo() {
return to;
}
public boolean isAuthenticated() {
return isAuthenticated;
}
public void setTo(Location to) {
this.to = to;
}
}

View File

@ -0,0 +1,54 @@
package fr.xephi.authme.events;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import fr.xephi.authme.cache.backup.JsonCache;
/**
* This event is call just before write inventory content to cache
*
* @author Xephi59
*/
public class StoreInventoryEvent extends CustomEvent {
private ItemStack[] armor;
private ItemStack[] inventory;
private Player player;
public StoreInventoryEvent(Player player) {
this.player = player;
this.inventory = player.getInventory().getContents();
this.armor = player.getInventory().getArmorContents();
}
public StoreInventoryEvent(Player player, JsonCache jsonCache) {
this.player = player;
this.inventory = player.getInventory().getContents();
this.armor = player.getInventory().getArmorContents();
}
public ItemStack[] getArmor() {
return this.armor;
}
public ItemStack[] getInventory() {
return this.inventory;
}
public Player getPlayer() {
return this.player;
}
public void setArmor(ItemStack[] armor) {
this.armor = armor;
}
public void setInventory(ItemStack[] inventory) {
this.inventory = inventory;
}
public void setPlayer(Player player) {
this.player = player;
}
}

View File

@ -0,0 +1,37 @@
package fr.xephi.authme.listener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
public class AuthMeBlockListener implements Listener {
public AuthMe instance;
public AuthMeBlockListener(AuthMe instance) {
this.instance = instance;
}
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (Utils.checkAuth(event.getPlayer()))
return;
event.setCancelled(true);
}
}

View File

@ -0,0 +1,191 @@
package fr.xephi.authme.listener;
import java.lang.reflect.Method;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.projectiles.ProjectileSource;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
public class AuthMeEntityListener implements Listener {
private static Method getShooter;
private static boolean shooterIsProjectileSource;
public AuthMe instance;
public AuthMeEntityListener(AuthMe instance) {
this.instance = instance;
try {
Method m = Projectile.class.getDeclaredMethod("getShooter");
shooterIsProjectileSource = m.getReturnType() != LivingEntity.class;
} catch (Exception ignored) {
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void entityRegainHealthEvent(EntityRegainHealthEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) entity)) {
return;
}
event.setAmount(0);
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onDmg(EntityDamageByEntityEvent event) {
Entity entity = event.getDamager();
if (entity == null || !(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
if (Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
if (Utils.checkAuth(player)) {
return;
}
player.setFireTicks(0);
event.setDamage(0);
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) entity)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityTarget(EntityTargetEvent event) {
Entity entity = event.getTarget();
if (entity == null || !(entity instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) entity)) {
return;
}
event.setTarget(null);
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) entity)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onLowestEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) entity)) {
return;
}
event.setCancelled(true);
}
// TODO: Need to check this, player can't throw snowball but the item is taken.
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
Projectile projectile = event.getEntity();
Player player = null;
if (projectile == null) {
return;
}
if (shooterIsProjectileSource) {
ProjectileSource shooter = projectile.getShooter();
if (shooter == null || !(shooter instanceof Player)) {
return;
}
player = (Player) shooter;
} else {
try {
if (getShooter == null) {
getShooter = Projectile.class.getMethod("getShooter");
}
Object obj = getShooter.invoke(null);
player = (Player) obj;
} catch (Exception ignored) {
}
}
if (Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onShoot(EntityShootBowEvent event) {
Entity entity = event.getEntity();
if (entity == null || !(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
if (Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (C) 2015 AuthMe-Team
*
* 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 fr.xephi.authme.listener;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.logging.Level;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Settings;
public class AuthMeInventoryPacketAdapter extends PacketAdapter {
private static final int HOTBAR_SIZE = 9;
// http://wiki.vg/Inventory#Inventory (0-4 crafting, 5-8 armor, 9-35 main inventory, 36-44 inventory)
// +1 because an index starts with 0
private static final int PLAYER_CRAFTING_SIZE = 5;
private static final int PLAYER_INVENTORY = 0;
public AuthMeInventoryPacketAdapter(AuthMe plugin) {
super(plugin, PacketType.Play.Server.SET_SLOT, PacketType.Play.Server.WINDOW_ITEMS);
}
@Override
public void onPacketSending(PacketEvent packetEvent) {
Player player = packetEvent.getPlayer();
PacketContainer packet = packetEvent.getPacket();
byte windowId = packet.getIntegers().read(0).byteValue();
if (windowId == PLAYER_INVENTORY && Settings.protectInventoryBeforeLogInEnabled && !PlayerCache.getInstance().isAuthenticated(player.getName())) {
packetEvent.setCancelled(true);
}
}
public void register() {
ProtocolLibrary.getProtocolManager().addPacketListener(this);
}
public void sendInventoryPacket(Player player) {
ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
PacketContainer inventoryPacket = protocolManager.createPacket(PacketType.Play.Server.WINDOW_ITEMS);
// we are sending our own inventory
inventoryPacket.getIntegers().write(0, PLAYER_INVENTORY);
ItemStack[] playerCrafting = new ItemStack[PLAYER_CRAFTING_SIZE];
Arrays.fill(playerCrafting, new ItemStack(Material.AIR));
ItemStack[] armorContents = player.getInventory().getArmorContents();
ItemStack[] mainInventory = player.getInventory().getContents();
// bukkit saves the armor in reversed order
Collections.reverse(Arrays.asList(armorContents));
// same main inventory. The hotbar is at the beginning but it should be at the end of the array
ItemStack[] hotbar = Arrays.copyOfRange(mainInventory, 0, HOTBAR_SIZE);
ItemStack[] storedInventory = Arrays.copyOfRange(mainInventory, HOTBAR_SIZE, mainInventory.length);
// concat all parts of the inventory together
int inventorySize = playerCrafting.length + armorContents.length + mainInventory.length;
ItemStack[] completeInventory = new ItemStack[inventorySize];
System.arraycopy(playerCrafting, 0, completeInventory, 0, playerCrafting.length);
System.arraycopy(armorContents, 0, completeInventory, playerCrafting.length, armorContents.length);
// storedInventory and hotbar
System.arraycopy(storedInventory, 0, completeInventory, playerCrafting.length + armorContents.length, storedInventory.length);
System.arraycopy(hotbar, 0, completeInventory, playerCrafting.length + armorContents.length + storedInventory.length, hotbar.length);
inventoryPacket.getItemArrayModifier().write(0, completeInventory);
try {
protocolManager.sendServerPacket(player, inventoryPacket, false);
} catch (InvocationTargetException invocationExc) {
plugin.getLogger().log(Level.WARNING, "Error during inventory recovery", invocationExc);
}
}
}

View File

@ -0,0 +1,573 @@
package fr.xephi.authme.listener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.PatternSyntaxException;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerShearEntityEvent;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class AuthMePlayerListener implements Listener {
public static ConcurrentHashMap<String, Boolean> causeByAuthMe = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, GameMode> gameMode = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> joinMessage = new ConcurrentHashMap<>();
public AuthMe plugin;
private final List<String> antibot = new ArrayList<>();
private final Messages m = Messages.getInstance();
public AuthMePlayerListener(final AuthMe plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerBedEnter(final PlayerBedEnterEvent event) {
if (Utils.checkAuth(event.getPlayer())) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerChat(final AsyncPlayerChatEvent event) {
handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) {
final String msg = event.getMessage();
if (msg.equalsIgnoreCase("/worldedit cui")) {
return;
}
final String cmd = msg.split(" ")[0];
if (cmd.equalsIgnoreCase("/login") || cmd.equalsIgnoreCase("/register") || cmd.equalsIgnoreCase("/l") || cmd.equalsIgnoreCase("/reg") || cmd.equalsIgnoreCase("/email")
|| cmd.equalsIgnoreCase("/captcha")) {
return;
}
if (Settings.useEssentialsMotd && cmd.equalsIgnoreCase("/motd")) {
return;
}
if (Settings.allowCommands.contains(cmd)) {
return;
}
if (!Utils.checkAuth(event.getPlayer())) {
event.setMessage("/notloggedin");
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerConsumeItem(final PlayerItemConsumeEvent event) {
if (Utils.checkAuth(event.getPlayer())) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerDropItem(final PlayerDropItemEvent event) {
if (Utils.checkAuth(event.getPlayer())) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerEarlyChat(final AsyncPlayerChatEvent event) {
handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerFish(final PlayerFishEvent event) {
final Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerGameModeChange(final PlayerGameModeChangeEvent event) {
final Player player = event.getPlayer();
if (player == null) {
return;
}
if (plugin.authmePermissible(player, "authme.bypassforcesurvival")) {
return;
}
if (Utils.checkAuth(player)) {
return;
}
final String name = player.getName().toLowerCase();
if (causeByAuthMe.containsKey(name)) {
causeByAuthMe.remove(name);
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerHighChat(final AsyncPlayerChatEvent event) {
handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerHighestChat(final AsyncPlayerChatEvent event) {
handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerInteract(final PlayerInteractEvent event) {
final Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerInteractEntity(final PlayerInteractEntityEvent event) {
final Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerInventoryClick(final InventoryClickEvent event) {
if (event.getWhoClicked() == null) {
return;
}
if (!(event.getWhoClicked() instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) event.getWhoClicked())) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerInventoryOpen(final InventoryOpenEvent event) {
final Player player = (Player) event.getPlayer();
if (Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
/*
* @note little hack cause InventoryOpenEvent cannot be cancelled for
* real, cause no packet is send to server by client for the main inv
*/
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
player.closeInventory();
}
}, 1);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(final PlayerJoinEvent event) {
if (event.getPlayer() == null) {
return;
}
// Shedule login task so works after the prelogin
// (Fix found by Koolaid5000)
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
plugin.management.performJoin(player);
// Remove the join message while the player isn't logging in
if ((Settings.enableProtection || Settings.delayJoinMessage) && event.getJoinMessage() != null) {
joinMessage.put(name, event.getJoinMessage());
event.setJoinMessage(null);
}
}
});
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerKick(final PlayerKickEvent event) {
if (event.getPlayer() == null) {
return;
}
if ((!Settings.isForceSingleSessionEnabled) && (event.getReason().contains(m.getString("same_nick")))) {
event.setCancelled(true);
return;
}
final Player player = event.getPlayer();
plugin.management.performQuit(player, true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogin(final PlayerLoginEvent event) {
final Player player = event.getPlayer();
if (player == null) {
return;
}
final String name = player.getName().toLowerCase();
final boolean isAuthAvailable = plugin.database.isAuthAvailable(name);
if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return;
}
if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) {
return;
}
if (!Settings.countriesBlacklist.isEmpty() && !isAuthAvailable && !plugin.authmePermissible(player, "authme.bypassantibot")) {
final String code = Utils.getCountryCode(event.getAddress().getHostAddress());
if (((code == null) || Settings.countriesBlacklist.contains(code))) {
event.setKickMessage(m.send("country_banned")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
}
}
if (Settings.enableProtection && !Settings.countries.isEmpty() && !isAuthAvailable && !plugin.authmePermissible(player, "authme.bypassantibot")) {
final String code = Utils.getCountryCode(event.getAddress().getHostAddress());
if (((code == null) || !Settings.countries.contains(code))) {
event.setKickMessage(m.send("country_banned")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
}
}
// TODO: Add message to the messages file!!!
if (Settings.isKickNonRegisteredEnabled && !isAuthAvailable) {
if (Settings.antiBotInAction) {
event.setKickMessage("AntiBot service in action! You actually need to be registered!");
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
} else {
event.setKickMessage(m.send("reg_only")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
}
}
final int min = Settings.getMinNickLength;
final int max = Settings.getMaxNickLength;
final String regex = Settings.getNickRegex;
if (name.length() > max || name.length() < min) {
event.setKickMessage(Arrays.toString(m.send("name_len")));
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
}
try {
if (!player.getName().matches(regex) || name.equalsIgnoreCase("Player")) {
try {
event.setKickMessage(m.send("regex")[0].replace("REG_EX", regex));
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
} catch (final Exception exc) {
event.setKickMessage("allowed char : " + regex);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
}
return;
}
} catch (final PatternSyntaxException pse) {
if (regex == null || regex.isEmpty()) {
event.setKickMessage("Your nickname do not match");
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
}
try {
event.setKickMessage(m.send("regex")[0].replace("REG_EX", regex));
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
} catch (final Exception exc) {
event.setKickMessage("allowed char : " + regex);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
}
return;
}
if (event.getResult() == PlayerLoginEvent.Result.ALLOWED) {
checkAntiBotMod(player);
if (Settings.bungee) {
final ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("IP");
player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
}
return;
}
if (event.getResult() != PlayerLoginEvent.Result.KICK_FULL) {
return;
}
if (!plugin.authmePermissible(player, "authme.vip")) {
event.setKickMessage(m.send("kick_fullserver")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_FULL);
return;
}
final int playersOnline = Utils.getOnlinePlayers().size();
if (playersOnline > plugin.getServer().getMaxPlayers()) {
event.allow();
} else {
final Player pl = plugin.generateKickPlayer(Utils.getOnlinePlayers());
if (pl != null) {
pl.kickPlayer(m.send("kick_forvip")[0]);
event.allow();
} else {
ConsoleLogger.info("The player " + player.getName() + " tryed to join, but the server was full");
event.setKickMessage(m.send("kick_fullserver")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_FULL);
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void onPlayerLowChat(final AsyncPlayerChatEvent event) {
handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerMove(final PlayerMoveEvent event) {
final Player player = event.getPlayer();
if (Utils.checkAuth(player)) {
return;
}
if (!Settings.isMovementAllowed) {
if (!event.getFrom().getBlock().equals(event.getTo().getBlock())) {
event.setTo(event.getFrom());
}
return;
}
if (Settings.getMovementRadius == 0) {
return;
}
final int radius = Settings.getMovementRadius;
final Location spawn = plugin.getSpawnLocation(player);
if (spawn != null && spawn.getWorld() != null) {
if (!event.getPlayer().getWorld().equals(spawn.getWorld())) {
event.getPlayer().teleport(spawn);
return;
}
if ((spawn.distance(player.getLocation()) > radius)) {
event.getPlayer().teleport(spawn);
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerNormalChat(final AsyncPlayerChatEvent event) {
handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerPickupItem(final PlayerPickupItemEvent event) {
if (Utils.checkAuth(event.getPlayer())) {
return;
}
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(final PlayerQuitEvent event) {
if (event.getPlayer() == null) {
return;
}
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
plugin.management.performQuit(player, false);
if (!PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) {
event.setQuitMessage(null);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(final PlayerRespawnEvent event) {
final Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player)) {
return;
}
final String name = player.getName().toLowerCase();
final Location spawn = plugin.getSpawnLocation(player);
if (Settings.isSaveQuitLocationEnabled && plugin.database.isAuthAvailable(name)) {
final PlayerAuth auth = new PlayerAuth(name, spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getWorld().getName(), player.getName());
plugin.database.updateQuitLoc(auth);
}
if (spawn != null && spawn.getWorld() != null) {
event.setRespawnLocation(spawn);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerShear(final PlayerShearEntityEvent event) {
final Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player)) {
return;
}
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPreLogin(final AsyncPlayerPreLoginEvent event) {
final String name = event.getName().toLowerCase();
final Player player = Bukkit.getServer().getPlayer(name);
if (player == null) {
return;
}
// Check if forceSingleSession is set to true, so kick player that has
// joined with same nick of online player
if (Settings.isForceSingleSessionEnabled && plugin.dataManager.isOnline(player, name)) {
event.setKickMessage(m.send("same_nick")[0]);
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
if (LimboCache.getInstance().hasLimboPlayer(name)) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
if (limbo != null && PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
Utils.addNormal(player, limbo.getGroup());
LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase());
}
}
});
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onSignChange(final SignChangeEvent event) {
if (Utils.checkAuth(event.getPlayer())) {
return;
}
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void playerHitPlayerEvent(final EntityDamageByEntityEvent event) {
final Entity damager = event.getDamager();
if (!(damager instanceof Player)) {
return;
}
if (Utils.checkAuth((Player) damager)) {
return;
}
event.setCancelled(true);
}
private void checkAntiBotMod(final Player player) {
if (plugin.delayedAntiBot || plugin.antibotMod) {
return;
}
if (plugin.authmePermissible(player, "authme.bypassantibot")) {
return;
}
if (antibot.size() > Settings.antiBotSensibility) {
plugin.switchAntiBotMod(true);
for (final String s : m.send("antibot_auto_enabled")) {
Bukkit.broadcastMessage(s);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (plugin.antibotMod) {
plugin.switchAntiBotMod(false);
antibot.clear();
for (final String s : m.send("antibot_auto_disabled")) {
Bukkit.broadcastMessage(s.replace("%m", "" + Settings.antiBotDuration));
}
}
}
}, Settings.antiBotDuration * 1200);
return;
}
antibot.add(player.getName().toLowerCase());
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
antibot.remove(player.getName().toLowerCase());
}
}, 300);
}
private void handleChat(final AsyncPlayerChatEvent event) {
final Player player = event.getPlayer();
if (!Utils.checkAuth(player)) {
final String cmd = event.getMessage().split(" ")[0];
if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
event.setCancelled(true);
}
if (plugin.database.isAuthAvailable(player.getName().toLowerCase())) {
m.send(player, "login_msg");
} else {
if (Settings.emailRegistration) {
m.send(player, "reg_email_msg");
} else {
m.send(player, "reg_msg");
}
}
}
}
}

View File

@ -0,0 +1,28 @@
package fr.xephi.authme.listener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerEditBookEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
public class AuthMePlayerListener16 implements Listener {
public AuthMe plugin;
public AuthMePlayerListener16(AuthMe plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerEditBook(PlayerEditBookEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return;
event.setCancelled(true);
}
}

View File

@ -0,0 +1,28 @@
package fr.xephi.authme.listener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
public class AuthMePlayerListener18 implements Listener {
public AuthMe plugin;
public AuthMePlayerListener18(AuthMe plugin) {
this.plugin = plugin;
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
Player player = event.getPlayer();
if (player == null || Utils.checkAuth(player))
return;
event.setCancelled(true);
}
}

View File

@ -0,0 +1,81 @@
package fr.xephi.authme.listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerListPingEvent;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class AuthMeServerListener implements Listener {
public AuthMe plugin;
private final Messages m = Messages.getInstance();
public AuthMeServerListener(final AuthMe plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPluginDisable(final PluginDisableEvent event) {
final String pluginName = event.getPlugin().getName();
if (pluginName.equalsIgnoreCase("Essentials")) {
plugin.ess = null;
ConsoleLogger.info("Essentials has been disabled, unhook!");
return;
}
if (pluginName.equalsIgnoreCase("EssentialsSpawn")) {
plugin.essentialsSpawn = null;
ConsoleLogger.info("EssentialsSpawn has been disabled, unhook!");
return;
}
if (pluginName.equalsIgnoreCase("Vault")) {
plugin.permission = null;
ConsoleLogger.showError("Vault has been disabled, unhook permissions!");
}
if (pluginName.equalsIgnoreCase("ProtocolLib")) {
plugin.inventoryProtector = null;
ConsoleLogger.showError("ProtocolLib has been disabled, unhook packet inventory protection!");
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPluginEnable(final PluginEnableEvent event) {
final String pluginName = event.getPlugin().getName();
if (pluginName.equalsIgnoreCase("Essentials") || pluginName.equalsIgnoreCase("EssentialsSpawn")) {
plugin.checkEssentials();
}
if (pluginName.equalsIgnoreCase("Vault")) {
plugin.checkVault();
}
if (pluginName.equalsIgnoreCase("ProtocolLib")) {
plugin.checkProtocolLib();
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onServerPing(final ServerListPingEvent event) {
if (!Settings.enableProtection) {
return;
}
if (Settings.countries.isEmpty()) {
return;
}
if (!Settings.countriesBlacklist.isEmpty()) {
if (Settings.countriesBlacklist.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) {
event.setMotd(m.send("country_banned")[0]);
}
}
if (Settings.countries.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) {
event.setMotd(plugin.getServer().getMotd());
} else {
event.setMotd(m.send("country_banned")[0]);
}
}
}

View File

@ -0,0 +1,24 @@
package fr.xephi.authme.modules;
public abstract class Module {
public abstract String getName();
public abstract ModuleType getType();
public void load() {
}
public void unload() {
}
enum ModuleType {
ACTIONS,
CONVERTERS,
CUSTOM,
EMAILS,
MANAGER,
MYSQL,
REDIS
}
}

View File

@ -0,0 +1,140 @@
package fr.xephi.authme.modules;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
public class ModuleManager {
private List<Module> modules = new ArrayList<>();
public ModuleManager(AuthMe plugin) {
}
public Module getModule(Module.ModuleType type) {
for (Module m : modules) {
if (m.getType() == type)
return m;
}
return null;
}
public Module getModule(String name) {
for (Module m : modules) {
if (m.getName().equalsIgnoreCase(name))
return m;
}
return null;
}
public boolean isModuleEnabled(Module.ModuleType type) {
for (Module m : modules) {
if (m.getType() == type)
return true;
}
return false;
}
public boolean isModuleEnabled(String name) {
for (Module m : modules) {
if (m.getName().equalsIgnoreCase(name))
return true;
}
return false;
}
public int loadModules() {
File dir = Settings.MODULE_FOLDER;
int count = 0;
if (!dir.isDirectory()) {
dir.mkdirs();
return count;
}
File[] files = dir.listFiles();
if (files == null) {
return count;
}
for (File pathToJar : files) {
JarFile jarFile = null;
URLClassLoader cl = null;
try {
jarFile = new JarFile(pathToJar);
URL[] urls = { new URL("jar:file:" + pathToJar.getAbsolutePath() + "!/") };
cl = URLClassLoader.newInstance(urls);
Enumeration<?> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith("Main.class")) {
continue;
}
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
Class<?> c = cl.loadClass(className);
if (!Module.class.isAssignableFrom(c)) {
continue;
}
Module mod = (Module) c.newInstance();
mod.load();
modules.add(mod);
count++;
break;
}
} catch (Exception ex) {
ConsoleLogger.writeStackTrace(ex);
ConsoleLogger.showError("Cannot load " + pathToJar.getName() + " jar file !");
} finally {
try {
if (jarFile != null) {
jarFile.close();
}
if (cl != null) {
cl.close();
}
} catch (IOException ignored) {
}
}
}
return count;
}
public void reloadModules() {
unloadModules();
loadModules();
}
public void unloadModule(String name) {
Iterator<Module> it = modules.iterator();
while (it.hasNext()) {
Module m = it.next();
if (m.getName().equalsIgnoreCase(name)) {
m.unload();
it.remove();
return;
}
}
}
public void unloadModules() {
Iterator<Module> it = modules.iterator();
while (it.hasNext()) {
it.next().unload();
it.remove();
}
}
}

View File

@ -0,0 +1,33 @@
package fr.xephi.authme.plugin.manager;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import fr.xephi.authme.AuthMe;
public class BungeeCordMessage implements PluginMessageListener {
public AuthMe plugin;
public BungeeCordMessage(AuthMe plugin) {
this.plugin = plugin;
}
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
if (!channel.equals("BungeeCord")) {
return;
}
ByteArrayDataInput in = ByteStreams.newDataInput(message);
String subChannel = in.readUTF();
if (subChannel.equals("IP")) { // We need only the IP channel
String ip = in.readUTF();
// Put the IP (only the ip not the port) in the hashMap
plugin.realIp.put(player.getName().toLowerCase(), ip);
}
}
}

View File

@ -0,0 +1,41 @@
package fr.xephi.authme.plugin.manager;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import fr.xephi.authme.settings.CustomConfiguration;
public class EssSpawn extends CustomConfiguration {
private static EssSpawn spawn;
public EssSpawn() {
super(new File("." + File.separator + "plugins" + File.separator + "Essentials" + File.separator + "spawn.yml"));
spawn = this;
load();
}
public static EssSpawn getInstance() {
if (spawn == null) {
spawn = new EssSpawn();
}
return spawn;
}
public Location getLocation() {
try {
if (!this.contains("spawns.default.world"))
return null;
if (this.getString("spawns.default.world").isEmpty() || this.getString("spawns.default.world").equals(""))
return null;
Location location = new Location(Bukkit.getWorld(this.getString("spawns.default.world")), this.getDouble("spawns.default.x"), this.getDouble("spawns.default.y"),
this.getDouble("spawns.default.z"), Float.parseFloat(this.getString("spawns.default.yaw")), Float.parseFloat(this.getString("spawns.default.pitch")));
return location;
} catch (NullPointerException | NumberFormatException npe) {
return null;
}
}
}

View File

@ -0,0 +1,84 @@
package fr.xephi.authme.process;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.process.join.AsyncronousJoin;
import fr.xephi.authme.process.login.AsyncronousLogin;
import fr.xephi.authme.process.logout.AsyncronousLogout;
import fr.xephi.authme.process.quit.AsyncronousQuit;
import fr.xephi.authme.process.register.AsyncronousRegister;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Settings;
/**
*
* @authors Xephi59,
* <a href="http://dev.bukkit.org/profiles/Possible/">Possible</a>
*
*/
public class Management {
public static RandomString rdm = new RandomString(Settings.captchaLength);
public AuthMe plugin;
public PluginManager pm;
public Management(AuthMe plugin) {
this.plugin = plugin;
this.pm = plugin.getServer().getPluginManager();
}
public void performJoin(final Player player) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
new AsyncronousJoin(player, plugin, plugin.database).process();
}
});
}
public void performLogin(final Player player, final String password, final boolean forceLogin) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
new AsyncronousLogin(player, password, forceLogin, plugin, plugin.database).process();
}
});
}
public void performLogout(final Player player) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
new AsyncronousLogout(player, plugin, plugin.database).process();
}
});
}
public void performQuit(final Player player, final boolean isKick) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
new AsyncronousQuit(player, plugin, plugin.database, isKick).process();
}
});
}
public void performRegister(final Player player, final String password, final String email) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
new AsyncronousRegister(player, password, email, plugin, plugin.database).process();
}
});
}
}

View File

@ -0,0 +1,296 @@
package fr.xephi.authme.process.join;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.FirstSpawnTeleportEvent;
import fr.xephi.authme.events.ProtectInventoryEvent;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class AsyncronousJoin {
private Messages m = Messages.getInstance();
protected DataSource database;
protected String name;
protected Player player;
protected AuthMe plugin;
public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) {
this.player = player;
this.plugin = plugin;
this.database = database;
this.name = player.getName().toLowerCase();
}
public void process() {
if (AuthMePlayerListener.gameMode.containsKey(name))
AuthMePlayerListener.gameMode.remove(name);
AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode());
BukkitScheduler sched = plugin.getServer().getScheduler();
if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return;
}
if (plugin.ess != null && Settings.disableSocialSpy) {
plugin.ess.getUser(player).setSocialSpyEnabled(false);
}
final String ip = plugin.getIP(player);
if (Settings.isAllowRestrictedIp && !Settings.getRestrictedIp(name, ip)) {
final GameMode gM = AuthMePlayerListener.gameMode.get(name);
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
player.setGameMode(gM);
player.kickPlayer("You are not the Owner of this account, please try another name!");
if (Settings.banUnsafeIp)
plugin.getServer().banIP(ip);
}
});
return;
}
if (Settings.getMaxJoinPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) {
if (plugin.hasJoinedIp(player.getName(), ip)) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
player.kickPlayer("A player with the same IP is already in game!");
}
});
return;
}
}
final Location spawnLoc = plugin.getSpawnLocation(player);
final boolean isAuthAvailable = database.isAuthAvailable(name);
if (isAuthAvailable) {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
Utils.forceGM(player);
}
});
}
if (!Settings.noTeleport)
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name));
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (player.isOnline() && tpEvent.getTo() != null) {
if (tpEvent.getTo().getWorld() != null)
player.teleport(tpEvent.getTo());
}
}
}
});
}
placePlayerSafely(player, spawnLoc);
LimboCache.getInstance().updateLimboPlayer(player);
// protect inventory
if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) {
ProtectInventoryEvent ev = new ProtectInventoryEvent(player);
plugin.getServer().getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
plugin.inventoryProtector.sendInventoryPacket(player);
if (!Settings.noConsoleSpam)
ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + " ...");
}
}
} else {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
Utils.forceGM(player);
}
});
}
if (!Settings.unRegisteredGroup.isEmpty()) {
Utils.setGroup(player, Utils.GroupType.UNREGISTERED);
}
if (!Settings.isForcedRegistrationEnabled) {
return;
}
if (!Settings.noTeleport)
if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name));
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (player.isOnline() && tpEvent.getTo() != null) {
if (tpEvent.getTo().getWorld() != null)
player.teleport(tpEvent.getTo());
}
}
}
});
}
}
String[] msg;
if (Settings.emailRegistration) {
msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_email_msg");
} else {
msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_msg");
}
int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval;
if (time != 0) {
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time);
if (!LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().addLimboPlayer(player);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
if (!LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().addLimboPlayer(player);
if (isAuthAvailable) {
Utils.setGroup(player, GroupType.NOTLOGGEDIN);
} else {
Utils.setGroup(player, GroupType.UNREGISTERED);
}
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (player.isOp())
player.setOp(false);
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
player.setAllowFlight(true);
player.setFlying(true);
}
player.setNoDamageTicks(Settings.getRegistrationTimeout * 20);
if (Settings.useEssentialsMotd)
player.performCommand("motd");
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.0f);
player.setFlySpeed(0.0f);
}
}
});
if (Settings.isSessionsEnabled && isAuthAvailable && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) {
if (plugin.sessions.containsKey(name))
plugin.sessions.get(name).cancel();
plugin.sessions.remove(name);
PlayerAuth auth = database.getAuth(name);
if (auth != null && auth.getIp().equals(ip)) {
m.send(player, "valid_session");
PlayerCache.getInstance().removePlayer(name);
database.setUnlogged(name);
plugin.management.performLogin(player, "dontneed", true);
} else if (Settings.sessionExpireOnIpChange) {
PlayerCache.getInstance().removePlayer(name);
database.setUnlogged(name);
m.send(player, "invalid_session");
}
return;
}
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, msgInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
}
private boolean needFirstspawn() {
if (player.hasPlayedBefore())
return false;
if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null)
return false;
FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn());
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) {
final Location fLoc = tpEvent.getTo();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
player.teleport(fLoc);
}
});
}
}
return true;
}
private void placePlayerSafely(final Player player, final Location spawnLoc) {
Location loc = null;
if (spawnLoc == null)
return;
if (!Settings.noTeleport)
return;
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())))
return;
if (!player.hasPlayedBefore())
return;
Block b = player.getLocation().getBlock();
if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) {
m.send(player, "unsafe_spawn");
if (spawnLoc.getWorld() != null)
loc = spawnLoc;
} else {
Block c = player.getLocation().add(0D, 1D, 0D).getBlock();
if (c.getType() == Material.PORTAL || c.getType() == Material.ENDER_PORTAL) {
m.send(player, "unsafe_spawn");
if (spawnLoc.getWorld() != null)
loc = spawnLoc;
}
}
if (loc != null) {
final Location floc = loc;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
player.teleport(floc);
}
});
}
}
}

View File

@ -0,0 +1,246 @@
package fr.xephi.authme.process.login;
import java.util.Date;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
public class AsyncronousLogin {
private static RandomString rdm = new RandomString(Settings.captchaLength);
private DataSource database;
private Messages m = Messages.getInstance();
private AuthMe plugin;
protected boolean forceLogin;
protected String name;
protected String password;
protected Player player;
protected String realName;
public AsyncronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data) {
this.player = player;
this.password = password;
name = player.getName().toLowerCase();
realName = player.getName();
this.forceLogin = forceLogin;
this.plugin = plugin;
this.database = data;
}
public void displayOtherAccounts(PlayerAuth auth, Player p) {
if (!Settings.displayOtherAccounts) {
return;
}
if (auth == null) {
return;
}
List<String> auths = this.database.getAllAuthsByName(auth);
// List<String> uuidlist =
// plugin.otherAccounts.getAllPlayersByUUID(player.getUniqueId());
if (auths.isEmpty()) {
return;
}
if (auths.size() == 1) {
return;
}
StringBuilder message = new StringBuilder("[AuthMe] ");
// String uuidaccounts =
// "[AuthMe] PlayerNames has %size% links to this UUID : ";
int i = 0;
for (String account : auths) {
i++;
message.append(account);
if (i != auths.size()) {
message.append(", ");
} else {
message.append(".");
}
}
/*
* TODO: Active uuid system i = 0; for (String account : uuidlist) {
* i++; uuidaccounts = uuidaccounts + account; if (i != auths.size()) {
* uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts =
* uuidaccounts + "."; } }
*/
for (Player player : Utils.getOnlinePlayers()) {
if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) {
player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts");
player.sendMessage(message.toString());
// player.sendMessage(uuidaccounts.replace("%size%",
// ""+uuidlist.size()));
}
}
}
public void process() {
PlayerAuth pAuth = preAuth();
if (pAuth == null || needsCaptcha())
return;
String hash = pAuth.getHash();
String email = pAuth.getEmail();
boolean passwordVerified = true;
if (!forceLogin)
try {
passwordVerified = PasswordSecurity.comparePasswordWithHash(password, hash, realName);
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
m.send(player, "error");
return;
}
if (passwordVerified && player.isOnline()) {
PlayerAuth auth = new PlayerAuth(name, hash, getIP(), new Date().getTime(), email, realName);
database.updateSession(auth);
if (Settings.useCaptcha) {
if (plugin.captcha.containsKey(name)) {
plugin.captcha.remove(name);
}
if (plugin.cap.containsKey(name)) {
plugin.cap.remove(name);
}
}
player.setNoDamageTicks(0);
if (!forceLogin)
m.send(player, "login");
displayOtherAccounts(auth, player);
if (Settings.recallEmail) {
if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com"))
m.send(player, "add_email");
}
if (!Settings.noConsoleSpam)
ConsoleLogger.info(realName + " logged in!");
// makes player isLoggedin via API
PlayerCache.getInstance().addPlayer(auth);
database.setLogged(name);
plugin.otherAccounts.addPlayer(player.getUniqueId());
// As the scheduling executes the Task most likely after the current
// task, we schedule it in the end
// so that we can be sure, and have not to care if it might be
// processed in other order.
ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(player, plugin, database);
if (syncronousPlayerLogin.getLimbo() != null) {
if (syncronousPlayerLogin.getLimbo().getTimeoutTaskId() != null)
syncronousPlayerLogin.getLimbo().getTimeoutTaskId().cancel();
if (syncronousPlayerLogin.getLimbo().getMessageTaskId() != null)
syncronousPlayerLogin.getLimbo().getMessageTaskId().cancel();
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, syncronousPlayerLogin);
} else if (player.isOnline()) {
if (!Settings.noConsoleSpam)
ConsoleLogger.info(realName + " used the wrong password");
if (Settings.isKickOnWrongPasswordEnabled) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (AuthMePlayerListener.gameMode != null && AuthMePlayerListener.gameMode.containsKey(name)) {
player.setGameMode(AuthMePlayerListener.gameMode.get(name));
}
player.kickPlayer(m.send("wrong_pwd")[0]);
}
});
} else {
m.send(player, "wrong_pwd");
}
} else {
ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... ");
}
}
protected String getIP() {
return plugin.getIP(player);
}
protected boolean needsCaptcha() {
if (Settings.useCaptcha) {
if (!plugin.captcha.containsKey(name)) {
plugin.captcha.putIfAbsent(name, 1);
} else {
int i = plugin.captcha.get(name) + 1;
plugin.captcha.remove(name);
plugin.captcha.putIfAbsent(name, i);
}
if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
plugin.cap.put(name, rdm.nextString());
for (String s : m.send("usage_captcha")) {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("<theCaptcha>", plugin.cap.get(name)));
}
return true;
} else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
plugin.captcha.remove(name);
plugin.cap.remove(name);
}
}
return false;
}
/**
* Checks the precondition for authentication (like user known) and returns
* the playerAuth-State
*/
protected PlayerAuth preAuth() {
if (PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "logged_in");
return null;
}
if (!database.isAuthAvailable(name)) {
m.send(player, "user_unknown");
if (LimboCache.getInstance().hasLimboPlayer(name)) {
LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId().cancel();
String[] msg;
if (Settings.emailRegistration) {
msg = m.send("reg_email_msg");
} else {
msg = m.send("reg_msg");
}
BukkitTask msgT = Bukkit.getScheduler().runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, Settings.getWarnMessageInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
}
return null;
}
if (Settings.getMaxLoginPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) {
if (plugin.isLoggedIp(name, getIP())) {
m.send(player, "logged_in");
return null;
}
}
PlayerAuth pAuth = database.getAuth(name);
if (pAuth == null) {
m.send(player, "user_unknown");
return null;
}
if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) {
m.send(player, "vb_nonActiv");
return null;
}
AuthMeAsyncPreLoginEvent event = new AuthMeAsyncPreLoginEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.canLogin())
return null;
return pAuth;
}
}

View File

@ -0,0 +1,205 @@
package fr.xephi.authme.process.login;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.potion.PotionEffectType;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.events.LoginEvent;
import fr.xephi.authme.events.RestoreInventoryEvent;
import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.settings.Settings;
public class ProcessSyncronousPlayerLogin implements Runnable {
private PlayerAuth auth;
private DataSource database;
private LimboPlayer limbo;
private String name;
private Player player;
private JsonCache playerCache;
private AuthMe plugin;
private PluginManager pm;
public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin, DataSource data) {
this.plugin = plugin;
this.database = data;
this.pm = plugin.getServer().getPluginManager();
this.player = player;
this.name = player.getName().toLowerCase();
this.limbo = LimboCache.getInstance().getLimboPlayer(name);
this.auth = database.getAuth(name);
this.playerCache = new JsonCache();
}
public LimboPlayer getLimbo() {
return limbo;
}
@Override
public void run() {
// Limbo contains the State of the Player before /login
if (limbo != null) {
// Op & Flying
restoreOpState();
/*
* Restore Inventories and GameMode We need to restore them before
* teleport the player Cause in AuthMePlayerListener, we call
* ProtectInventoryEvent after Teleporting Also it's the current
* world inventory !
*/
player.setGameMode(limbo.getGameMode());
// Inventory - Make it after restore GameMode , cause we need to
// restore the
// right inventory in the right gamemode
if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) {
restoreInventory();
}
if (Settings.forceOnlyAfterLogin) {
player.setGameMode(GameMode.SURVIVAL);
}
if (!Settings.noTeleport) {
// Teleport
if (Settings.isTeleportToSpawnEnabled && !Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) {
if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) {
packQuitLocation();
} else {
teleportBackFromSpawn();
}
} else if (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) {
teleportToSpawn();
} else if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) {
packQuitLocation();
} else {
teleportBackFromSpawn();
}
}
// Re-Force Survival GameMode if we need due to world change
// specification
if (Settings.isForceSurvivalModeEnabled)
Utils.forceGM(player);
// Restore Permission Group
Utils.setGroup(player, GroupType.LOGGEDIN);
// Cleanup no longer used temporary data
LimboCache.getInstance().deleteLimboPlayer(name);
if (playerCache.doesCacheExist(player)) {
playerCache.removeCache(player);
}
}
// We can now display the join message
if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
for (Player p : Utils.getOnlinePlayers()) {
if (p.isOnline())
p.sendMessage(AuthMePlayerListener.joinMessage.get(name));
}
AuthMePlayerListener.joinMessage.remove(name);
}
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.2f);
player.setFlySpeed(0.1f);
}
// The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
player.saveData();
// Login is finish, display welcome message
if (Settings.useWelcomeMessage)
if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(plugin.replaceAllInfos(s, player));
}
}
// Login is now finish , we can force all commands
forceCommands();
}
protected void forceCommands() {
for (String command : Settings.forceCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
} catch (Exception ignored) {
}
}
for (String command : Settings.forceCommandsAsConsole) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName()));
}
}
protected void packQuitLocation() {
Utils.packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player);
}
protected void restoreInventory() {
RestoreInventoryEvent event = new RestoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
plugin.inventoryProtector.sendInventoryPacket(player);
}
}
protected void restoreOpState() {
player.setOp(limbo.getOperator());
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
if (limbo.getGameMode() != GameMode.CREATIVE) {
player.setAllowFlight(limbo.isFlying());
player.setFlying(limbo.isFlying());
} else {
player.setAllowFlight(false);
player.setFlying(false);
}
}
}
protected void teleportBackFromSpawn() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc());
pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo();
if (!fLoc.getChunk().isLoaded()) {
fLoc.getChunk().load();
}
player.teleport(fLoc);
}
}
protected void teleportToSpawn() {
Location spawnL = plugin.getSpawnLocation(player);
SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnL, true);
pm.callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
Location fLoc = tpEvent.getTo();
if (!fLoc.getChunk().isLoaded()) {
fLoc.getChunk().load();
}
player.teleport(fLoc);
}
}
}

View File

@ -0,0 +1,80 @@
package fr.xephi.authme.process.logout;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitScheduler;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class AsyncronousLogout {
private Messages m = Messages.getInstance();
protected boolean canLogout = true;
protected DataSource database;
protected String name;
protected Player player;
protected AuthMe plugin;
public AsyncronousLogout(Player player, AuthMe plugin, DataSource database) {
this.player = player;
this.plugin = plugin;
this.database = database;
this.name = player.getName().toLowerCase();
}
public void process() {
preLogout();
if (!canLogout)
return;
final Player p = player;
BukkitScheduler sched = p.getServer().getScheduler();
PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
database.updateSession(auth);
auth.setQuitLocX(p.getLocation().getX());
auth.setQuitLocY(p.getLocation().getY());
auth.setQuitLocZ(p.getLocation().getZ());
auth.setWorld(p.getWorld().getName());
database.updateQuitLoc(auth);
PlayerCache.getInstance().removePlayer(name);
database.setUnlogged(name);
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(p);
final AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(p, spawnLoc);
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (tpEvent.getTo() != null)
p.teleport(tpEvent.getTo());
}
}
});
}
if (LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player);
Utils.setGroup(player, GroupType.NOTLOGGEDIN);
sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin));
}
private void preLogout() {
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "not_logged_in");
canLogout = false;
}
}
}

View File

@ -0,0 +1,65 @@
package fr.xephi.authme.process.logout;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.events.LogoutEvent;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class ProcessSyncronousPlayerLogout implements Runnable {
private Messages m = Messages.getInstance();
protected String name;
protected Player player;
protected AuthMe plugin;
public ProcessSyncronousPlayerLogout(Player player, AuthMe plugin) {
this.player = player;
this.plugin = plugin;
this.name = player.getName().toLowerCase();
}
@Override
public void run() {
if (plugin.sessions.containsKey(name))
plugin.sessions.get(name).cancel();
plugin.sessions.remove(name);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = player.getServer().getScheduler();
if (delay != 0) {
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
if (player.isInsideVehicle() && player.getVehicle() != null)
player.getVehicle().eject();
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
player.setOp(false);
if (!Settings.isMovementAllowed) {
player.setAllowFlight(true);
player.setFlying(true);
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setFlySpeed(0.0f);
player.setWalkSpeed(0.0f);
}
}
// Player is now logout... Time to fire event !
Bukkit.getServer().getPluginManager().callEvent(new LogoutEvent(player));
m.send(player, "logout");
ConsoleLogger.info(player.getName() + " logged out");
}
}

View File

@ -0,0 +1,92 @@
package fr.xephi.authme.process.quit;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.listener.AuthMePlayerListener;
import fr.xephi.authme.settings.Settings;
public class AsyncronousQuit {
private boolean isFlying = false;
private boolean isKick = false;
private boolean isOp = false;
private String name;
private boolean needToChange = false;
protected DataSource database;
protected Player player;
protected AuthMe plugin;
public AsyncronousQuit(Player p, AuthMe plugin, DataSource database, boolean isKick) {
this.player = p;
this.plugin = plugin;
this.database = database;
this.name = p.getName().toLowerCase();
this.isKick = isKick;
}
public void process() {
if (player == null)
return;
if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return;
}
String ip = plugin.getIP(player);
if (PlayerCache.getInstance().isAuthenticated(name)) {
if (Settings.isSaveQuitLocationEnabled && database.isAuthAvailable(name)) {
Location loc = player.getLocation();
PlayerAuth auth = new PlayerAuth(name, loc.getX(), loc.getY(), loc.getZ(), loc.getWorld().getName(), player.getName());
database.updateQuitLoc(auth);
}
PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis(), player.getName());
database.updateSession(auth);
}
if (LimboCache.getInstance().hasLimboPlayer(name)) {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo.getGroup() != null && !limbo.getGroup().equals(""))
Utils.addNormal(player, limbo.getGroup());
needToChange = true;
isOp = limbo.getOperator();
isFlying = limbo.isFlying();
if (limbo.getTimeoutTaskId() != null)
limbo.getTimeoutTaskId().cancel();
if (limbo.getMessageTaskId() != null)
limbo.getMessageTaskId().cancel();
LimboCache.getInstance().deleteLimboPlayer(name);
}
if (Settings.isSessionsEnabled && !isKick) {
if (Settings.getSessionTimeout != 0) {
BukkitTask task = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() {
@Override
public void run() {
PlayerCache.getInstance().removePlayer(name);
if (database.isLogged(name))
database.setUnlogged(name);
plugin.sessions.remove(name);
}
}, Settings.getSessionTimeout * 20 * 60);
plugin.sessions.put(name, task);
}
} else {
PlayerCache.getInstance().removePlayer(name);
database.setUnlogged(name);
}
AuthMePlayerListener.gameMode.remove(name);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerQuit(plugin, player, isOp, isFlying, needToChange));
}
}

View File

@ -0,0 +1,40 @@
package fr.xephi.authme.process.quit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.settings.Settings;
public class ProcessSyncronousPlayerQuit implements Runnable {
protected boolean isFlying;
protected boolean isOp;
protected boolean needToChange;
protected Player player;
protected AuthMe plugin;
public ProcessSyncronousPlayerQuit(AuthMe plugin, Player player, boolean isOp, boolean isFlying, boolean needToChange) {
this.plugin = plugin;
this.player = player;
this.isOp = isOp;
this.isFlying = isFlying;
this.needToChange = needToChange;
}
@Override
public void run() {
if (needToChange) {
player.setOp(isOp);
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
player.setAllowFlight(isFlying);
player.setFlying(isFlying);
}
}
try {
player.getVehicle().eject();
} catch (Exception e) {
}
}
}

View File

@ -0,0 +1,160 @@
package fr.xephi.authme.process.register;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
public class AsyncronousRegister {
private final DataSource database;
private final Messages m = Messages.getInstance();
private final AuthMe plugin;
protected boolean allowRegister;
protected String email = "";
protected String name;
protected String password;
protected Player player;
public AsyncronousRegister(final Player player, final String password, final String email, final AuthMe plugin, final DataSource data) {
this.player = player;
this.password = password;
name = player.getName().toLowerCase();
this.email = email;
this.plugin = plugin;
this.database = data;
this.allowRegister = true;
}
public void process() {
preRegister();
if (!allowRegister) {
return;
}
if (!email.isEmpty() && !email.equals("")) {
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m.send(player, "max_reg");
return;
}
}
emailRegister();
return;
}
passwordRegister();
}
protected void emailRegister() {
if (Settings.getmaxRegPerEmail > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) {
m.send(player, "max_reg");
return;
}
}
PlayerAuth auth;
try {
final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
auth = new PlayerAuth(name, hashnew, getIp(), 0, (int) player.getLocation().getX(), (int) player.getLocation().getY(), (int) player.getLocation().getZ(),
player.getLocation().getWorld().getName(), email, player.getName());
} catch (final NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
m.send(player, "error");
return;
}
if (PasswordSecurity.userSalt.containsKey(name)) {
auth.setSalt(PasswordSecurity.userSalt.get(name));
}
database.saveAuth(auth);
database.updateEmail(auth);
database.updateSession(auth);
final ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
}
protected String getIp() {
return plugin.getIP(player);
}
protected void passwordRegister() {
PlayerAuth auth;
String hash;
try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
} catch (final NoSuchAlgorithmException e) {
ConsoleLogger.showError(e.getMessage());
m.send(player, "error");
return;
}
if (Settings.getMySQLColumnSalt.isEmpty() && !PasswordSecurity.userSalt.containsKey(name)) {
auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(), "your@email.com", player.getName());
} else {
auth = new PlayerAuth(name, hash, PasswordSecurity.userSalt.get(name), getIp(), new Date().getTime(), player.getName());
}
if (!database.saveAuth(auth)) {
m.send(player, "error");
return;
}
if (!Settings.forceRegLogin) {
PlayerCache.getInstance().addPlayer(auth);
database.setLogged(name);
}
plugin.otherAccounts.addPlayer(player.getUniqueId());
final ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
}
protected void preRegister() {
final String lowpass = password.toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "logged_in");
allowRegister = false;
}
else if (!Settings.isRegistrationEnabled) {
m.send(player, "reg_disabled");
allowRegister = false;
}
else if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select")
|| lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
m.send(player, "password_error");
allowRegister = false;
}
else if (lowpass.equalsIgnoreCase(player.getName())) {
m.send(player, "password_error_nick");
allowRegister = false;
}
else if (password.length() < Settings.getPasswordMinLen || password.length() > Settings.passwordMaxLength) {
m.send(player, "pass_len");
allowRegister = false;
}
else if (!Settings.unsafePasswords.isEmpty() && Settings.unsafePasswords.contains(password.toLowerCase())) {
m.send(player, "password_error_unsafe");
allowRegister = false;
} else if (database.isAuthAvailable(name)) {
m.send(player, "user_regged");
allowRegister = false;
}
else if (Settings.getmaxRegPerIp > 0) {
if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp && !getIp().equalsIgnoreCase("127.0.0.1")
&& !getIp().equalsIgnoreCase("localhost")) {
m.send(player, "max_reg");
allowRegister = false;
}
}
}
}

View File

@ -0,0 +1,57 @@
package fr.xephi.authme.process.register;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class ProcessSyncronousEmailRegister implements Runnable {
private Messages m = Messages.getInstance();
private AuthMe plugin;
protected String name;
protected Player player;
public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) {
this.player = player;
this.name = player.getName().toLowerCase();
this.plugin = plugin;
}
@Override
public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (!Settings.getRegisteredGroup.isEmpty()) {
Utils.setGroup(player, Utils.GroupType.REGISTERED);
}
m.send(player, "vb_nonActiv");
int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval;
BukkitScheduler sched = plugin.getServer().getScheduler();
if (time != 0 && limbo != null) {
limbo.getTimeoutTaskId().cancel();
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time);
limbo.setTimeoutTaskId(id);
}
if (limbo != null) {
limbo.getMessageTaskId().cancel();
BukkitTask nwMsg = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), msgInterval));
limbo.setMessageTaskId(nwMsg);
}
player.saveData();
if (!Settings.noConsoleSpam)
ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player));
}
}

View File

@ -0,0 +1,159 @@
package fr.xephi.authme.process.register;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.events.LoginEvent;
import fr.xephi.authme.events.RegisterTeleportEvent;
import fr.xephi.authme.events.RestoreInventoryEvent;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
public class ProcessSyncronousPasswordRegister implements Runnable {
private Messages m = Messages.getInstance();
private AuthMe plugin;
protected String name;
protected Player player;
public ProcessSyncronousPasswordRegister(Player player, AuthMe plugin) {
this.player = player;
this.name = player.getName().toLowerCase();
this.plugin = plugin;
}
@Override
public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (limbo != null) {
player.setGameMode(limbo.getGameMode());
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location loca = plugin.getSpawnLocation(player);
RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
}
player.teleport(tpEvent.getTo());
}
}
if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) {
RestoreInventoryEvent event = new RestoreInventoryEvent(player);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
plugin.inventoryProtector.sendInventoryPacket(player);
}
}
limbo.getTimeoutTaskId().cancel();
limbo.getMessageTaskId().cancel();
LimboCache.getInstance().deleteLimboPlayer(name);
}
if (!Settings.getRegisteredGroup.isEmpty()) {
Utils.setGroup(player, Utils.GroupType.REGISTERED);
}
m.send(player, "registered");
if (!Settings.getmailAccount.isEmpty())
m.send(player, "add_email");
if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) {
player.setAllowFlight(false);
player.setFlying(false);
}
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
player.setWalkSpeed(0.2f);
player.setFlySpeed(0.1f);
}
// The LoginEvent now fires (as intended) after everything is processed
plugin.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
player.saveData();
if (!Settings.noConsoleSpam)
ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player));
// Kick Player after Registration is enabled, kick the player
if (Settings.forceRegKick) {
player.kickPlayer(m.send("registered")[0]);
return;
}
// Request Login after Registration
if (Settings.forceRegLogin) {
forceLogin(player);
return;
}
// Register is finish and player is logged, display welcome message
if (Settings.useWelcomeMessage)
if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
plugin.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
player.sendMessage(plugin.replaceAllInfos(s, player));
}
}
// Register is now finish , we can force all commands
forceCommands();
}
protected void forceCommands() {
for (String command : Settings.forceRegisterCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
} catch (Exception ignored) {
}
}
for (String command : Settings.forceRegisterCommandsAsConsole) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName()));
}
}
protected void forceLogin(Player player) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawnLoc = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc);
plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) {
if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
}
player.teleport(tpEvent.getTo());
}
}
if (LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player);
int delay = Settings.getRegistrationTimeout * 20;
int interval = Settings.getWarnMessageInterval;
BukkitScheduler sched = plugin.getServer().getScheduler();
if (delay != 0) {
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
}
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
if (player.isInsideVehicle() && player.getVehicle() != null) {
player.getVehicle().eject();
}
}
}

View File

@ -0,0 +1,46 @@
package fr.xephi.authme.security;
import org.apache.commons.lang.ObjectUtils.Null;
public enum HashAlgorithm {
BCRYPT(fr.xephi.authme.security.crypts.BCRYPT.class),
BCRYPT2Y(fr.xephi.authme.security.crypts.BCRYPT2Y.class),
CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class),
CUSTOM(Null.class),
DOUBLEMD5(fr.xephi.authme.security.crypts.DOUBLEMD5.class),
IPB3(fr.xephi.authme.security.crypts.IPB3.class),
JOOMLA(fr.xephi.authme.security.crypts.JOOMLA.class),
MD5(fr.xephi.authme.security.crypts.MD5.class),
MD5VB(fr.xephi.authme.security.crypts.MD5VB.class),
MYBB(fr.xephi.authme.security.crypts.MYBB.class),
PBKDF2(fr.xephi.authme.security.crypts.CryptPBKDF2.class),
PBKDF2DJANGO(fr.xephi.authme.security.crypts.CryptPBKDF2Django.class),
PHPBB(fr.xephi.authme.security.crypts.PHPBB.class),
PHPFUSION(fr.xephi.authme.security.crypts.PHPFUSION.class),
PLAINTEXT(fr.xephi.authme.security.crypts.PLAINTEXT.class),
ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class),
SALTED2MD5(fr.xephi.authme.security.crypts.SALTED2MD5.class),
SALTEDSHA512(fr.xephi.authme.security.crypts.SALTEDSHA512.class),
SHA1(fr.xephi.authme.security.crypts.SHA1.class),
SHA256(fr.xephi.authme.security.crypts.SHA256.class),
SHA512(fr.xephi.authme.security.crypts.SHA512.class),
SMF(fr.xephi.authme.security.crypts.SMF.class),
WBB3(fr.xephi.authme.security.crypts.WBB3.class),
WBB4(fr.xephi.authme.security.crypts.WBB4.class),
WHIRLPOOL(fr.xephi.authme.security.crypts.WHIRLPOOL.class),
WORDPRESS(fr.xephi.authme.security.crypts.WORDPRESS.class),
XAUTH(fr.xephi.authme.security.crypts.XAUTH.class),
XENFORO(fr.xephi.authme.security.crypts.XF.class);
Class<?> classe;
HashAlgorithm(Class<?> classe) {
this.classe = classe;
}
public Class<?> getclasse() {
return classe;
}
}

View File

@ -0,0 +1,185 @@
package fr.xephi.authme.security;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import org.bukkit.Bukkit;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.events.PasswordEncryptionEvent;
import fr.xephi.authme.security.crypts.BCRYPT;
import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.settings.Settings;
public class PasswordSecurity {
public static HashMap<String, String> userSalt = new HashMap<>();
private static SecureRandom rnd = new SecureRandom();
public static boolean comparePasswordWithHash(final String password, final String hash, final String playerName) throws NoSuchAlgorithmException {
final HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method;
try {
if (algo != HashAlgorithm.CUSTOM) {
method = (EncryptionMethod) algo.getclasse().newInstance();
} else {
method = null;
}
final PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
Bukkit.getPluginManager().callEvent(event);
method = event.getMethod();
if (method == null) {
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
if (method.comparePassword(hash, password, playerName)) {
return true;
}
if (Settings.supportOldPassword) {
if (compareWithAllEncryptionMethod(password, hash, playerName)) {
return true;
}
}
} catch (InstantiationException | IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
}
return false;
}
public static String createSalt(final int length) throws NoSuchAlgorithmException {
final byte[] msg = new byte[40];
rnd.nextBytes(msg);
final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.reset();
final byte[] digest = sha1.digest(msg);
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)).substring(0, length);
}
public static String getHash(final HashAlgorithm alg, final String password, final String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method;
try {
if (alg != HashAlgorithm.CUSTOM) {
method = (EncryptionMethod) alg.getclasse().newInstance();
} else {
method = null;
}
} catch (InstantiationException | IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
}
String salt = "";
switch (alg) {
case SHA256:
salt = createSalt(16);
break;
case MD5VB:
salt = createSalt(16);
break;
case XAUTH:
salt = createSalt(12);
break;
case MYBB:
salt = createSalt(8);
userSalt.put(playerName, salt);
break;
case IPB3:
salt = createSalt(5);
userSalt.put(playerName, salt);
break;
case PHPFUSION:
salt = createSalt(12);
userSalt.put(playerName, salt);
break;
case SALTED2MD5:
salt = createSalt(Settings.saltLength);
userSalt.put(playerName, salt);
break;
case JOOMLA:
salt = createSalt(32);
userSalt.put(playerName, salt);
break;
case BCRYPT:
salt = BCRYPT.gensalt(Settings.bCryptLog2Rounds);
userSalt.put(playerName, salt);
break;
case WBB3:
salt = createSalt(40);
userSalt.put(playerName, salt);
break;
case WBB4:
salt = BCRYPT.gensalt(8);
userSalt.put(playerName, salt);
break;
case PBKDF2DJANGO:
case PBKDF2:
salt = createSalt(12);
userSalt.put(playerName, salt);
break;
case SMF:
if (method != null) {
return method.getHash(password, null, playerName);
}
case PHPBB:
salt = createSalt(16);
userSalt.put(playerName, salt);
break;
case BCRYPT2Y:
salt = createSalt(16);
userSalt.put(playerName, salt);
break;
case SALTEDSHA512:
salt = createSalt(32);
userSalt.put(playerName, salt);
break;
case MD5:
case SHA1:
case WHIRLPOOL:
case PLAINTEXT:
case XENFORO:
case SHA512:
case ROYALAUTH:
case CRAZYCRYPT1:
case DOUBLEMD5:
case WORDPRESS:
case CUSTOM:
break;
default:
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
final PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
Bukkit.getPluginManager().callEvent(event);
method = event.getMethod();
if (method == null) {
throw new NoSuchAlgorithmException("Unknown hash algorithm");
}
return method.getHash(password, salt, playerName);
}
private static boolean compareWithAllEncryptionMethod(final String password, final String hash, final String playerName) throws NoSuchAlgorithmException {
for (final HashAlgorithm algo : HashAlgorithm.values()) {
if (algo != HashAlgorithm.CUSTOM) {
try {
final EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance();
if (method.comparePassword(hash, password, playerName)) {
final PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName);
if (nAuth != null) {
nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName));
nAuth.setSalt(userSalt.containsKey(playerName) ? userSalt.get(playerName) : "");
AuthMe.getInstance().database.updatePassword(nAuth);
AuthMe.getInstance().database.updateSalt(nAuth);
}
return true;
}
} catch (final Exception ignored) {
}
}
}
return false;
}
}

View File

@ -0,0 +1,38 @@
package fr.xephi.authme.security;
import java.util.Calendar;
import java.util.Random;
/**
*
* @author Xephi59
*/
public class RandomString {
private static final char[] chars = new char[36];
private final char[] buf;
private final Random random = new Random();
public RandomString(int length) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
random.setSeed(Calendar.getInstance().getTimeInMillis());
}
static {
for (int idx = 0; idx < 10; ++idx)
chars[idx] = (char) ('0' + idx);
for (int idx = 10; idx < 36; ++idx)
chars[idx] = (char) ('a' + idx - 10);
}
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = chars[random.nextInt(chars.length)];
return new String(buf);
}
}

View File

@ -0,0 +1,619 @@
// Copyright (c) 2006 Damien Miller <djm@mindrot.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package fr.xephi.authme.security.crypts;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* BCrypt implements OpenBSD-style Blowfish password hashing using the scheme
* described in "A Future-Adaptable Password Scheme" by Niels Provos and David
* Mazieres.
* <p>
* This password hashing system tries to thwart off-line password cracking using
* a computationally-intensive hashing algorithm, based on Bruce Schneier's
* Blowfish cipher. The work factor of the algorithm is parameterised, so it can
* be increased as computers get faster.
* <p>
* Usage is really simple. To hash a password for the first time, call the
* hashpw method with a random salt, like this:
* <p>
* <code>
* String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); <br />
* </code>
* <p>
* To check whether a plaintext password matches one that has been hashed
* previously, use the checkpw method:
* <p>
* <code>
* if (BCrypt.checkpw(candidate_password, stored_hash))<br />
* &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It matches");<br />
* else<br />
* &nbsp;&nbsp;&nbsp;&nbsp;System.out.println("It does not match");<br />
* </code>
* <p>
* The gensalt() method takes an optional parameter (log_rounds) that determines
* the computational complexity of the hashing:
* <p>
* <code>
* String strong_salt = BCrypt.gensalt(10)<br />
* String stronger_salt = BCrypt.gensalt(12)<br />
* </code>
* <p>
* The amount of work increases exponentially (2**log_rounds), so each increment
* is twice as much work. The default log_rounds is 10, and the valid range is 4
* to 31.
*
* @author Damien Miller
* @version 0.2
*/
public class BCRYPT implements EncryptionMethod {
// Table for Base64 encoding
static private final char base64_code[] = { '.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9' };
private static final int BCRYPT_SALT_LEN = 16;
// bcrypt IV: "OrpheanBeholderScryDoubt"
static private final int bf_crypt_ciphertext[] = { 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 };
// Blowfish parameters
private static final int BLOWFISH_NUM_ROUNDS = 16;
// BCrypt parameters
private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
// Table for Base64 decoding
static private final byte index_64[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1 };
// Initial contents of key schedule
private static final int P_orig[] = { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7,
0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b };
private static final int S_orig[] = { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8,
0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0,
0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862,
0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d,
0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e,
0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6,
0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd,
0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8,
0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479,
0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198,
0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191,
0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d,
0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b,
0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a,
0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04,
0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290,
0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17,
0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002,
0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba,
0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883,
0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775,
0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a,
0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15,
0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092,
0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2,
0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e,
0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec,
0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900,
0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab,
0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802,
0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1,
0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62,
0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7,
0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8,
0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f,
0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770,
0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025,
0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56,
0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5,
0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e,
0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb,
0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d,
0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad,
0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4,
0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64,
0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463,
0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d,
0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7,
0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e,
0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c,
0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5,
0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0,
0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 };
// Expanded Blowfish key
private int P[];
private int S[];
/**
* Check that a plaintext password matches a previously hashed one
*
* @param plaintext
* the plaintext password to verify
* @param hashed
* the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
return (hashed.compareTo(hashpw(plaintext, hashed)) == 0);
}
/**
* Check that a text password matches a previously hashed one with the
* specified number of rounds using recursion
*
* @param text
* plaintext or hashed text
* @param hashed
* the previously-hashed password
* @param rounds
* number of rounds to hash the password
* @return
*/
public static boolean checkpw(String text, String hashed, int rounds) {
boolean matched = false;
if (rounds > 0) {
String hash = hashpw(text, hashed);
if (rounds > 1) {
matched = checkpw(hash, hashed, rounds - 1);
} else {
matched = hash.compareTo(hashed) == 0;
}
} else {
matched = text.compareTo(hashed) == 0;
}
return matched;
}
/**
* Generate a salt for use with the BCrypt.hashpw() method, selecting a
* reasonable default for the number of hashing rounds to apply
*
* @return an encoded salt value
*/
public static String gensalt() {
return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
*
* @param log_rounds
* the log2 of the number of rounds of hashing to apply - the
* work factor therefore increases as 2**log_rounds.
* @return an encoded salt value
*/
public static String gensalt(int log_rounds) {
return gensalt(log_rounds, new SecureRandom());
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
*
* @param log_rounds
* the log2 of the number of rounds of hashing to apply - the
* work factor therefore increases as 2**log_rounds.
* @param random
* an instance of SecureRandom to use
* @return an encoded salt value
*/
public static String gensalt(int log_rounds, SecureRandom random) {
StringBuffer rs = new StringBuffer();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
rs.append("$2a$");
if (log_rounds < 10)
rs.append("0");
rs.append(Integer.toString(log_rounds));
rs.append("$");
rs.append(encode_base64(rnd, rnd.length));
return rs.toString();
}
public static String getDoubleHash(String text, String salt) {
String hash = hashpw(text, salt);
return hashpw(text, hash);
}
/**
* Hash a password using the OpenBSD bcrypt scheme
*
* @param password
* the password to hash
* @param salt
* the salt to hash with (perhaps generated using BCrypt.gensalt)
* @return the hashed password
*/
public static String hashpw(String password, String salt) {
BCRYPT B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuffer rs = new StringBuffer();
if (salt.charAt(0) != '$' || salt.charAt(1) != '2')
throw new IllegalArgumentException("Invalid salt version");
if (salt.charAt(2) == '$')
off = 3;
else {
minor = salt.charAt(2);
if (minor < 'a' || minor > 'z' || salt.charAt(3) != '$')
throw new IllegalArgumentException("Invalid salt revision");
off = 4;
}
// Extract number of rounds
if (salt.charAt(off + 2) > '$')
throw new IllegalArgumentException("Missing salt rounds");
rounds = Integer.parseInt(salt.substring(off, off + 2));
real_salt = salt.substring(off + 3, off + 25);
try {
passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
throw new AssertionError("UTF-8 is not supported");
}
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
B = new BCRYPT();
hashed = B.crypt_raw(passwordb, saltb, rounds);
rs.append("$2");
if (minor >= 'a')
rs.append(minor);
rs.append("$");
if (rounds < 10)
rs.append("0");
rs.append(Integer.toString(rounds));
rs.append("$");
rs.append(encode_base64(saltb, saltb.length));
rs.append(encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1));
return rs.toString();
}
/**
* Look up the 3 bits base64-encoded by the specified character,
* range-checking againt conversion table
*
* @param x
* the base64-encoded value
* @return the decoded value of x
*/
private static byte char64(char x) {
if ((int) x > index_64.length)
return -1;
return index_64[(int) x];
}
/**
* Decode a string encoded using bcrypt's base64 scheme to a byte array.
* Note that this is *not* compatible with the standard MIME-base64
* encoding.
*
* @param s
* the string to decode
* @param maxolen
* the maximum number of bytes to decode
* @return an array containing the decoded bytes
* @throws IllegalArgumentException
* if maxolen is invalid
*/
private static byte[] decode_base64(String s, int maxolen) throws IllegalArgumentException {
StringBuffer rs = new StringBuffer();
int off = 0, slen = s.length(), olen = 0;
byte ret[];
byte c1, c2, c3, c4, o;
if (maxolen <= 0)
throw new IllegalArgumentException("Invalid maxolen");
while (off < slen - 1 && olen < maxolen) {
c1 = char64(s.charAt(off++));
c2 = char64(s.charAt(off++));
if (c1 == -1 || c2 == -1)
break;
o = (byte) (c1 << 2);
o |= (c2 & 0x30) >> 4;
rs.append((char) o);
if (++olen >= maxolen || off >= slen)
break;
c3 = char64(s.charAt(off++));
if (c3 == -1)
break;
o = (byte) ((c2 & 0x0f) << 4);
o |= (c3 & 0x3c) >> 2;
rs.append((char) o);
if (++olen >= maxolen || off >= slen)
break;
c4 = char64(s.charAt(off++));
o = (byte) ((c3 & 0x03) << 6);
o |= c4;
rs.append((char) o);
++olen;
}
ret = new byte[olen];
for (off = 0; off < olen; off++)
ret[off] = (byte) rs.charAt(off);
return ret;
}
/**
* Encode a byte array using bcrypt's slightly-modified base64 encoding
* scheme. Note that this is *not* compatible with the standard MIME-base64
* encoding.
*
* @param d
* the byte array to encode
* @param len
* the number of bytes to encode
* @return base64-encoded string
* @throws IllegalArgumentException
* if the length is invalid
*/
private static String encode_base64(byte d[], int len) throws IllegalArgumentException {
int off = 0;
StringBuffer rs = new StringBuffer();
int c1, c2;
if (len <= 0 || len > d.length)
throw new IllegalArgumentException("Invalid len");
while (off < len) {
c1 = d[off++] & 0xff;
rs.append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.append(base64_code[c1 & 0x3f]);
rs.append(base64_code[c2 & 0x3f]);
}
return rs.toString();
}
/**
* Cycically extract a word of key material
*
* @param data
* the string to extract the data from
* @param offp
* a "pointer" (as a one-entry array) to the current offset into
* data
* @return the next word of material from data
*/
private static int streamtoword(byte data[], int offp[]) {
int i;
int word = 0;
int off = offp[0];
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[off] & 0xff);
off = (off + 1) % data.length;
}
offp[0] = off;
return word;
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
return checkpw(password, hash);
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return hashpw(password, salt);
}
/**
* Perform the central password hashing step in the bcrypt scheme
*
* @param password
* the password to hash
* @param salt
* the binary salt to hash with the password
* @param log_rounds
* the binary logarithm of the number of rounds of hashing to
* apply
* @return an array containing the binary hashed password
*/
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
int rounds, i, j;
int cdata[] = (int[]) bf_crypt_ciphertext.clone();
int clen = cdata.length;
byte ret[];
if (log_rounds < 4 || log_rounds > 31)
throw new IllegalArgumentException("Bad number of rounds");
rounds = 1 << log_rounds;
if (salt.length != BCRYPT_SALT_LEN)
throw new IllegalArgumentException("Bad salt length");
init_key();
ekskey(salt, password);
for (i = 0; i < rounds; i++) {
key(password);
key(salt);
}
for (i = 0; i < 64; i++) {
for (j = 0; j < (clen >> 1); j++)
encipher(cdata, j << 1);
}
ret = new byte[clen * 4];
for (i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte) ((cdata[i] >> 24) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 16) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 8) & 0xff);
ret[j++] = (byte) (cdata[i] & 0xff);
}
return ret;
}
/**
* Perform the "enhanced key schedule" step described by Provos and Mazieres
* in "A Future-Adaptable Password Scheme"
* http://www.openbsd.org/papers/bcrypt-paper.ps
*
* @param data
* salt information
* @param key
* password information
*/
private void ekskey(byte data[], byte key[]) {
int i;
int koffp[] = { 0 }, doffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
P[i] = P[i] ^ streamtoword(key, koffp);
for (i = 0; i < plen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Blowfish encipher a single 64-bit block encoded as two 32-bit halves
*
* @param lr
* an array containing the two 32-bit half blocks
* @param off
* the position in the array of the blocks
*/
private final void encipher(int lr[], int off) {
int i, n, l = lr[off], r = lr[off + 1];
l ^= P[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
n ^= S[0x200 | ((l >> 8) & 0xff)];
n += S[0x300 | (l & 0xff)];
r ^= n ^ P[++i];
// Feistel substitution on right word
n = S[(r >> 24) & 0xff];
n += S[0x100 | ((r >> 16) & 0xff)];
n ^= S[0x200 | ((r >> 8) & 0xff)];
n += S[0x300 | (r & 0xff)];
l ^= n ^ P[++i];
}
lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
lr[off + 1] = l;
}
/**
* Initialise the Blowfish key schedule
*/
private void init_key() {
P = (int[]) P_orig.clone();
S = (int[]) S_orig.clone();
}
/**
* Key the Blowfish cipher
*
* @param key
* an array containing the key
*/
private void key(byte key[]) {
int i;
int koffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
P[i] = P[i] ^ streamtoword(key, koffp);
for (i = 0; i < plen; i += 2) {
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
}

View File

@ -0,0 +1,22 @@
package fr.xephi.authme.security.crypts;
import java.security.NoSuchAlgorithmException;
public class BCRYPT2Y implements EncryptionMethod {
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
String ok = hash.substring(0, 29);
if (ok.length() != 29)
return false;
return hash.equals(getHash(password, ok, playerName));
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
if (salt.length() == 22)
salt = "$2y$10$" + salt;
return (BCRYPT.hashpw(password, salt));
}
}

View File

@ -0,0 +1,37 @@
package fr.xephi.authme.security.crypts;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CRAZYCRYPT1 implements EncryptionMethod {
private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
protected final Charset charset = Charset.forName("UTF-8");
public static String byteArrayToHexString(final byte... args) {
final char[] chars = new char[args.length * 2];
for (int i = 0; i < args.length; i++) {
chars[i * 2] = CRYPTCHARS[(args[i] >> 4) & 0xF];
chars[i * 2 + 1] = CRYPTCHARS[(args[i]) & 0xF];
}
return new String(chars);
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, null, playerName));
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
final String text = "ÜÄaeut//&/=I " + password + "7421€547" + name + "__+IÄIH§%NK " + password;
try {
final MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(text.getBytes(charset), 0, text.length());
return byteArrayToHexString(md.digest());
} catch (final NoSuchAlgorithmException e) {
return null;
}
}
}

View File

@ -0,0 +1,29 @@
package fr.xephi.authme.security.crypts;
import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.security.pbkdf2.PBKDF2Engine;
import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters;
public class CryptPBKDF2 implements EncryptionMethod {
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
String salt = line[2];
String derivedKey = line[3];
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000, derivedKey.getBytes());
PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password);
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$10000$" + salt + "$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000);
PBKDF2Engine engine = new PBKDF2Engine(params);
return result + String.valueOf(engine.deriveKey(password, 64));
}
}

View File

@ -0,0 +1,31 @@
package fr.xephi.authme.security.crypts;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import fr.xephi.authme.security.pbkdf2.PBKDF2Engine;
import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters;
public class CryptPBKDF2Django implements EncryptionMethod {
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
String salt = line[2];
byte[] derivedKey = DatatypeConverter.parseBase64Binary(line[3]);
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000, derivedKey);
PBKDF2Engine engine = new PBKDF2Engine(params);
return engine.verifyKey(password);
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
String result = "pbkdf2_sha256$15000$" + salt + "$";
PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000);
PBKDF2Engine engine = new PBKDF2Engine(params);
return result + String.valueOf(DatatypeConverter.printBase64Binary(engine.deriveKey(password, 32)));
}
}

View File

@ -0,0 +1,27 @@
package fr.xephi.authme.security.crypts;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class DOUBLEMD5 implements EncryptionMethod {
private static String getMD5(String message) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return getMD5(getMD5(password));
}
}

View File

@ -0,0 +1,38 @@
package fr.xephi.authme.security.crypts;
import java.security.NoSuchAlgorithmException;
/**
* <p>
* Public interface for Custom Password encryption method
* </p>
* <p>
* The getHash function is called when we need to crypt the password (/register
* usually)
* </p>
* <p>
* The comparePassword is called when we need to match password (/login usually)
* </p>
*/
public interface EncryptionMethod {
/**
* @param hash
* @param password
* @param playerName
* @return true if password match, false else
* @throws NoSuchAlgorithmException
*/
boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException;
/**
* @param password
* @param salt
* (can be an other data like playerName;salt , playerName,
* etc... for customs methods)
* @return Hashing password
* @throws NoSuchAlgorithmException
*/
String getHash(String password, String salt, String name) throws NoSuchAlgorithmException;
}

View File

@ -0,0 +1,29 @@
package fr.xephi.authme.security.crypts;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import fr.xephi.authme.AuthMe;
public class IPB3 implements EncryptionMethod {
private static String getMD5(String message) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt();
return hash.equals(getHash(password, salt, playerName));
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return getMD5(getMD5(salt) + getMD5(password));
}
}

View File

@ -0,0 +1,27 @@
package fr.xephi.authme.security.crypts;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class JOOMLA implements EncryptionMethod {
private static String getMD5(String message) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
String salt = hash.split(":")[1];
return hash.equals(getMD5(password + salt) + ":" + salt);
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return getMD5(password + salt) + ":" + salt;
}
}

View File

@ -0,0 +1,26 @@
package fr.xephi.authme.security.crypts;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 implements EncryptionMethod {
private static String getMD5(String message) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
return hash.equals(getHash(password, "", ""));
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return getMD5(password);
}
}

View File

@ -0,0 +1,28 @@
package fr.xephi.authme.security.crypts;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5VB implements EncryptionMethod {
private static String getMD5(String message) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(message.getBytes());
byte[] digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
}
@Override
public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException {
String[] line = hash.split("\\$");
return hash.equals(getHash(password, line[2], ""));
}
@Override
public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException {
return "$MD5vb$" + salt + "$" + getMD5(getMD5(password) + salt);
}
}

Some files were not shown because too many files have changed in this diff Show More