public release of asklyphe authservice

This commit is contained in:
husky 2025-03-07 15:51:57 -08:00
commit 434227543c
36 changed files with 3186 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
.idea

27
Cargo.toml Normal file
View file

@ -0,0 +1,27 @@
[package]
name = "authservice"
version = "0.1.0"
edition = "2021"
license = "AGPL-3"
license-file = "LICENSE"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
asklyphe-common = { git = "https://forge.voremicrocomputers.com/asklyphe-public/asklyphe-common.git", branch = "main" }
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sea-orm = { version = "1.0.0", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono"]}
entity = { path = "./entity" }
rmp-serde = "1.1.2"
async-nats = "0.38.0"
chrono = "0.4.26"
once_cell = "1.18.0"
ulid = "1.0.0"
rand = "0.8.5"
futures = "0.3.30"
log = "0.4.20"
env_logger = "0.10.2"
argon2 = "0.5.3"
regex = "1.10.3"
lettre = "0.11.10"

181
LICENSE Normal file
View file

@ -0,0 +1,181 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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.

7
entity/Cargo.toml Normal file
View file

@ -0,0 +1,7 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
[dependencies]
sea-orm = { version = "1.0.0", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono"]}

View file

@ -0,0 +1,37 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "announcement")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub slug: String,
pub title: String,
pub short_text_notice: String,
pub full_markdown_notice: String,
pub creator_id: String,
pub created_on: DateTime,
pub updated_on: Option<DateTime>,
pub flags: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::CreatorId",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "NoAction"
)]
User,
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

40
entity/src/invite_code.rs Normal file
View file

@ -0,0 +1,40 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "invite_code")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: String,
#[sea_orm(unique)]
pub code: String,
pub issuer: Option<String>,
pub root_issuer: String,
pub comment: Option<String>,
pub created_on: DateTime,
pub used: bool,
pub used_on: Option<DateTime>,
pub used_by: Option<String>,
pub flags: Option<i64>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::UsedBy",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "SetNull"
)]
User,
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

10
entity/src/lib.rs Normal file
View file

@ -0,0 +1,10 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub mod prelude;
pub mod announcement;
pub mod invite_code;
pub mod user;
pub mod user_session;
pub mod user_settings;
pub mod verification_code;

8
entity/src/prelude.rs Normal file
View file

@ -0,0 +1,8 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub use super::announcement::Entity as Announcement;
pub use super::invite_code::Entity as InviteCode;
pub use super::user::Entity as User;
pub use super::user_session::Entity as UserSession;
pub use super::user_settings::Entity as UserSettings;
pub use super::verification_code::Entity as VerificationCode;

57
entity/src/user.rs Normal file
View file

@ -0,0 +1,57 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: String,
#[sea_orm(unique)]
pub username: String,
pub display_name: Option<String>,
pub email: String,
pub new_email: Option<String>,
pub password: String,
pub flags: i64,
pub created_on: DateTime,
pub last_updated: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::announcement::Entity")]
Announcement,
#[sea_orm(has_many = "super::invite_code::Entity")]
InviteCode,
#[sea_orm(has_many = "super::user_session::Entity")]
UserSession,
#[sea_orm(has_one = "super::user_settings::Entity")]
UserSettings,
}
impl Related<super::announcement::Entity> for Entity {
fn to() -> RelationDef {
Relation::Announcement.def()
}
}
impl Related<super::invite_code::Entity> for Entity {
fn to() -> RelationDef {
Relation::InviteCode.def()
}
}
impl Related<super::user_session::Entity> for Entity {
fn to() -> RelationDef {
Relation::UserSession.def()
}
}
impl Related<super::user_settings::Entity> for Entity {
fn to() -> RelationDef {
Relation::UserSettings.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View file

@ -0,0 +1,38 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "user_session")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: String,
pub user: String,
pub display_id: String,
#[sea_orm(unique)]
pub token: String,
pub flags: i64,
pub ip_address: Option<String>,
pub created_on: DateTime,
pub death_date: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::User",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
User,
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View file

@ -0,0 +1,31 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "user_settings")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub user: String,
pub theme: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::user::Entity",
from = "Column::User",
to = "super::user::Column::Id",
on_update = "NoAction",
on_delete = "Cascade"
)]
User,
}
impl Related<super::user::Entity> for Entity {
fn to() -> RelationDef {
Relation::User.def()
}
}
impl ActiveModelBehavior for ActiveModel {}

View file

@ -0,0 +1,23 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "verification_code")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: String,
pub user: String,
pub set_new_email: bool,
#[sea_orm(unique)]
pub code: String,
pub created_on: DateTime,
pub death_date: DateTime,
pub used: bool,
pub used_on: Option<DateTime>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

22
migration/Cargo.toml Normal file
View file

@ -0,0 +1,22 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "1.0.0"
features = [
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
# e.g.
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
"sqlx-postgres", # `DATABASE_DRIVER` feature
]

41
migration/README.md Normal file
View file

@ -0,0 +1,41 @@
# Running Migrator CLI
- Generate a new migration file
```sh
cargo run -- generate MIGRATION_NAME
```
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

24
migration/src/lib.rs Normal file
View file

@ -0,0 +1,24 @@
pub use sea_orm_migration::prelude::*;
mod m20240814_013106_create_user;
mod m20240814_013750_create_invite_code;
mod m20240814_014654_create_user_session;
mod m20240814_015232_create_verification_code;
mod m20240829_214347_create_user_settings;
mod m20241115_003101_create_announcement;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20240814_013106_create_user::Migration),
Box::new(m20240814_013750_create_invite_code::Migration),
Box::new(m20240814_014654_create_user_session::Migration),
Box::new(m20240814_015232_create_verification_code::Migration),
Box::new(m20240829_214347_create_user_settings::Migration),
Box::new(m20241115_003101_create_announcement::Migration),
]
}
}

View file

@ -0,0 +1,47 @@
use sea_orm_migration::{prelude::*, schema::*};
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(ColumnDef::new(User::Id).string().not_null().primary_key())
.col(ColumnDef::new(User::Username).string().not_null().unique_key())
.col(ColumnDef::new(User::DisplayName).string())
.col(ColumnDef::new(User::Email).string().not_null())
.col(ColumnDef::new(User::NewEmail).string())
.col(ColumnDef::new(User::Password).string().not_null())
.col(ColumnDef::new(User::Flags).big_unsigned().not_null())
.col(ColumnDef::new(User::CreatedOn).date_time().not_null())
.col(ColumnDef::new(User::LastUpdated).date_time().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
pub enum User {
Table,
Id,
Username,
DisplayName,
Email,
NewEmail,
Password,
Flags,
CreatedOn,
LastUpdated,
}

View file

@ -0,0 +1,54 @@
use sea_orm_migration::{prelude::*, schema::*};
use crate::m20240814_013106_create_user::User;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(InviteCode::Table)
.if_not_exists()
.col(ColumnDef::new(InviteCode::Id).string().not_null().primary_key())
.col(ColumnDef::new(InviteCode::Code).string().not_null().unique_key())
.col(ColumnDef::new(InviteCode::Issuer).string())
.col(ColumnDef::new(InviteCode::RootIssuer).string().not_null())
.col(ColumnDef::new(InviteCode::Comment).string())
.col(ColumnDef::new(InviteCode::CreatedOn).date_time().not_null())
.col(ColumnDef::new(InviteCode::Used).boolean().not_null())
.col(ColumnDef::new(InviteCode::UsedOn).date_time())
.col(ColumnDef::new(InviteCode::UsedBy).string())
.col(ColumnDef::new(InviteCode::Flags).big_unsigned())
.foreign_key(ForeignKey::create().name("fk-invitecode-usedby")
.from(InviteCode::Table, InviteCode::UsedBy)
.to(User::Table, User::Id)
.on_delete(ForeignKeyAction::SetNull))
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(InviteCode::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
pub enum InviteCode {
Table,
Id,
Code,
Issuer,
RootIssuer,
Comment,
CreatedOn,
Used,
UsedOn,
UsedBy,
Flags,
}

View file

@ -0,0 +1,51 @@
use sea_orm_migration::{prelude::*, schema::*};
use crate::m20240814_013106_create_user::User;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(UserSession::Table)
.if_not_exists()
.col(ColumnDef::new(UserSession::Id).string().not_null().primary_key())
.col(ColumnDef::new(UserSession::User).string().not_null())
.col(ColumnDef::new(UserSession::DisplayId).string().not_null())
.col(ColumnDef::new(UserSession::Token).string().not_null().unique_key())
.col(ColumnDef::new(UserSession::Flags).big_unsigned().not_null())
.col(ColumnDef::new(UserSession::IPAddress).string())
.col(ColumnDef::new(UserSession::CreatedOn).date_time().not_null())
.col(ColumnDef::new(UserSession::DeathDate).date_time().not_null())
.foreign_key(ForeignKey::create()
.name("fk-usersession-user")
.from(UserSession::Table, UserSession::User)
.to(User::Table, User::Id)
.on_delete(ForeignKeyAction::Cascade))
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(UserSession::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum UserSession {
Table,
Id,
User,
DisplayId,
Token,
Flags,
IPAddress,
CreatedOn,
DeathDate,
}

View file

@ -0,0 +1,45 @@
use sea_orm_migration::{prelude::*, schema::*};
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(VerificationCode::Table)
.if_not_exists()
.col(ColumnDef::new(VerificationCode::Id).string().not_null().primary_key())
.col(ColumnDef::new(VerificationCode::User).string().not_null())
.col(ColumnDef::new(VerificationCode::SetNewEmail).boolean().not_null())
.col(ColumnDef::new(VerificationCode::Code).string().not_null().unique_key())
.col(ColumnDef::new(VerificationCode::CreatedOn).date_time().not_null())
.col(ColumnDef::new(VerificationCode::DeathDate).date_time().not_null())
.col(ColumnDef::new(VerificationCode::Used).boolean().not_null())
.col(ColumnDef::new(VerificationCode::UsedOn).date_time())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(VerificationCode::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum VerificationCode {
Table,
Id,
User,
Code,
SetNewEmail,
CreatedOn,
DeathDate,
Used,
UsedOn,
}

View file

@ -0,0 +1,40 @@
use sea_orm_migration::{prelude::*, schema::*};
use crate::m20240814_013106_create_user::User;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(UserSettings::Table)
.if_not_exists()
.col(ColumnDef::new(UserSettings::User).string().not_null().primary_key())
.col(ColumnDef::new(UserSettings::Theme).string().not_null())
.foreign_key(ForeignKey::create()
.name("fk-usersettings-user")
.from(UserSettings::Table, UserSettings::User)
.to(User::Table, User::Id)
.on_delete(ForeignKeyAction::Cascade)
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(UserSettings::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum UserSettings {
Table,
User, // used as id also
Theme,
}

View file

@ -0,0 +1,52 @@
use sea_orm_migration::{prelude::*, schema::*};
use crate::m20240814_013106_create_user::User;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Announcement::Table)
.if_not_exists()
.col(ColumnDef::new(Announcement::Slug).string().not_null().unique_key().primary_key())
.col(ColumnDef::new(Announcement::Title).string().not_null())
.col(ColumnDef::new(Announcement::ShortTextNotice).string().not_null())
.col(ColumnDef::new(Announcement::FullMarkdownNotice).string().not_null())
.col(ColumnDef::new(Announcement::CreatorId).string().not_null())
.col(ColumnDef::new(Announcement::CreatedOn).date_time().not_null())
.col(ColumnDef::new(Announcement::UpdatedOn).date_time())
.col(ColumnDef::new(Announcement::Flags).integer().not_null())
.foreign_key(ForeignKey::create()
.name("fk-announcement-user")
.from(Announcement::Table, Announcement::CreatorId)
.to(User::Table, User::Id)
.on_delete(ForeignKeyAction::NoAction)
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Announcement::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum Announcement {
Table,
Slug,
Title,
ShortTextNotice,
FullMarkdownNotice,
CreatorId,
CreatedOn,
UpdatedOn,
Flags,
}

6
migration/src/main.rs Normal file
View file

@ -0,0 +1,6 @@
use sea_orm_migration::prelude::*;
#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

145
src/db/announcements.rs Normal file
View file

@ -0,0 +1,145 @@
/*
* authservice db/announcements.rs
* - pgsql announcement functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use log::error;
use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, QueryFilter, QueryOrder};
use sea_orm::ActiveValue::Set;
use entity::announcement;
#[derive(Debug)]
pub enum AnnouncementInsertError {
SlugInUse,
DatabaseError,
}
pub async fn create_announcement(db: &DatabaseConnection, slug: String, title: String, short: String, full: String, creator_uid: String) -> Result<(), AnnouncementInsertError> {
if announcement::Entity::find().filter(announcement::Column::Slug.eq(&slug)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CREATEANNOUNCEMENT (check if slug free): {e}");
AnnouncementInsertError::DatabaseError
})?.is_some() {
return Err(AnnouncementInsertError::SlugInUse);
}
let record = announcement::ActiveModel {
slug: Set(slug),
title: Set(title),
short_text_notice: Set(short),
full_markdown_notice: Set(full),
creator_id: Set(creator_uid),
created_on: Set(chrono::Utc::now().naive_utc()),
updated_on: Default::default(),
flags: Set(0),
};
record.insert(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CREATEANNOUNCEMENT (insert): {e}");
AnnouncementInsertError::DatabaseError
})?;
Ok(())
}
#[derive(Debug)]
pub enum AnnouncementUpdateError {
SlugNotFound,
DatabaseError,
}
pub async fn update_announcement(db: &DatabaseConnection, slug: String, title: String, short: String, full: String) -> Result<(), AnnouncementUpdateError> {
if let Some(record) = announcement::Entity::find_by_id(&slug).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE UPDATEANNOUNCEMENT (find): {e}");
AnnouncementUpdateError::DatabaseError
})? {
let mut record = record.into_active_model();
record.title = Set(title);
record.short_text_notice = Set(short);
record.full_markdown_notice = Set(full);
record.updated_on = Set(Some(chrono::Utc::now().naive_utc()));
record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE UPDATEANNOUNCEMENT (update): {e}");
AnnouncementUpdateError::DatabaseError
})?;
Ok(())
} else {
Err(AnnouncementUpdateError::SlugNotFound)
}
}
pub struct AnnouncementRecord {
pub slug: String,
pub title: String,
pub short: String,
pub full: String,
pub creator_uid: String,
pub created_on: chrono::DateTime<chrono::Utc>,
pub updated_on: Option<chrono::DateTime<chrono::Utc>>,
}
#[derive(Debug)]
pub enum AnnouncementFetchError {
SlugNotFound,
DatabaseError,
}
pub async fn get_announcement(db: &DatabaseConnection, slug: String) -> Result<AnnouncementRecord, AnnouncementFetchError> {
Ok(announcement::Entity::find_by_id(slug).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE GETANNOUNCEMENT: {e}");
AnnouncementFetchError::DatabaseError
})?.ok_or(AnnouncementFetchError::SlugNotFound).map(|v| {
AnnouncementRecord {
slug: v.slug,
title: v.title,
short: v.short_text_notice,
full: v.full_markdown_notice,
creator_uid: v.creator_id,
created_on: v.created_on.and_utc(),
updated_on: v.updated_on.map(|v| v.and_utc()),
}
})?)
}
pub async fn get_all_announcements(db: &DatabaseConnection) -> Result<Vec<AnnouncementRecord>, AnnouncementFetchError> {
Ok(announcement::Entity::find().order_by_desc(announcement::Column::CreatedOn).all(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE ALLANNOUNCEMENT: {e}");
AnnouncementFetchError::DatabaseError
})?.into_iter().map(|v| {
AnnouncementRecord {
slug: v.slug,
title: v.title,
short: v.short_text_notice,
full: v.full_markdown_notice,
creator_uid: v.creator_id,
created_on: v.created_on.and_utc(),
updated_on: v.updated_on.map(|v| v.and_utc()),
}
}).collect())
}
pub async fn latest_announcement(db: &DatabaseConnection) -> Result<AnnouncementRecord, AnnouncementFetchError> {
Ok(announcement::Entity::find().order_by_desc(announcement::Column::CreatedOn).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE LATESTANNOUNCEMENT: {e}");
AnnouncementFetchError::DatabaseError
})?.ok_or(AnnouncementFetchError::SlugNotFound).map(|v| {
AnnouncementRecord {
slug: v.slug,
title: v.title,
short: v.short_text_notice,
full: v.full_markdown_notice,
creator_uid: v.creator_id,
created_on: v.created_on.and_utc(),
updated_on: v.updated_on.map(|v| v.and_utc()),
}
})?)
}

119
src/db/invite_code.rs Normal file
View file

@ -0,0 +1,119 @@
/*
* authservice db/invite_code.rs
* - pgsql invite code functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::time::Instant;
use log::error;
use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, QueryFilter};
use sea_orm::ActiveValue::Set;
use entity::{invite_code, user};
use crate::db::genid;
#[derive(Debug)]
pub enum ConsumeInviteCodeError {
InviteCodeAlreadyUsed,
InvalidInviteCode,
InvalidUser,
DatabaseError,
}
/// consumes an invite code by relating invite_code_used_by to the given user id
/// and setting the user's invite_code_assigned flag;
/// fails if the invite code is already used, the invite code isn't real, or the given user is invalid
pub async fn consume_invite_code(db: &DatabaseConnection, invite_code: String, user_id: String) -> Result<(), ConsumeInviteCodeError> {
// is the invite code real?
let record = invite_code::Entity::find().filter(invite_code::Column::Code.eq(&invite_code)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CONSUMEINVITECODE (check if real): {e}");
ConsumeInviteCodeError::DatabaseError
})?.ok_or(ConsumeInviteCodeError::InvalidInviteCode)?;
// has it been used?
if record.used == true {
return Err(ConsumeInviteCodeError::InvalidInviteCode);
}
// is user real?
user::Entity::find_by_id(&user_id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CONSUMEINVITECODE (check if user good): {e}");
ConsumeInviteCodeError::DatabaseError
})?.ok_or(ConsumeInviteCodeError::InvalidUser)?;
// we should be good to go, relate and set flags
let mut record = record.into_active_model();
record.used = Set(true);
record.used_by = Set(Some(user_id));
record.used_on = Set(Some(chrono::Utc::now().naive_utc()));
record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CONSUME INVITE CODE (update): {e}");
ConsumeInviteCodeError::DatabaseError
})?;
Ok(())
}
#[derive(Debug)]
pub enum InviteCodeGenerationError {
CodeAlreadyInserted,
DatabaseError,
}
pub async fn insert_new_invitecode(db: &DatabaseConnection, invite_code: String, issuer: String, root_issuer: String, comment: String) -> Result<(), InviteCodeGenerationError> {
let id = genid();
if invite_code::Entity::find().filter(invite_code::Column::Code.eq(&invite_code)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE INSERTINVITECODE (check if name free): {e}");
InviteCodeGenerationError::DatabaseError
})?.is_some() {
return Err(InviteCodeGenerationError::CodeAlreadyInserted);
}
let record = invite_code::ActiveModel {
id: Set(id),
code: Set(invite_code),
issuer: Set(Some(issuer)),
root_issuer: Set(root_issuer),
comment: Set(Some(comment)),
created_on: Set(chrono::Utc::now().naive_utc()),
used: Set(false),
used_on: Default::default(),
used_by: Default::default(),
flags: Set(Some(0)),
};
record.insert(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE INSERTINVITECODE (insert): {e}");
InviteCodeGenerationError::DatabaseError
})?;
Ok(())
}
#[derive(Debug)]
pub enum InviteCodeListError {
DatabaseError,
}
pub async fn list_invite_codes(db: &DatabaseConnection, show_used: bool) -> Result<Vec<invite_code::Model>, InviteCodeListError> {
let mut query = invite_code::Entity::find();
if show_used {
query = query.filter(invite_code::Column::Used.eq(true));
} else {
query = query.filter(invite_code::Column::Used.eq(false));
}
query.all(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE LISTINVITECODES: {e}");
InviteCodeListError::DatabaseError
})
}

22
src/db/mod.rs Normal file
View file

@ -0,0 +1,22 @@
/*
* authservice db/mod.rs
* - module file for pgsql database functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub mod user;
pub mod invite_code;
pub mod session;
pub mod usersettings;
pub mod announcements;
pub fn genid() -> String {
ulid::Ulid::new().to_string()
}

158
src/db/session.rs Normal file
View file

@ -0,0 +1,158 @@
/*
* authservice db/session.rs
* - pgsql session functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use chrono::{DateTime, Duration, TimeDelta, Utc};
use log::error;
use rand::Rng;
use sea_orm::ActiveValue::Set;
use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, QueryFilter};
use serde::{Deserialize, Serialize};
use entity::user_session;
use crate::db::{genid, user};
use crate::db::user::FetchUserError;
// todo: make this configurable
// 10 days
pub const SESSION_TTL_SECONDS: u64 = 10 * 24 * 60 * 60;
fn generate_session_token() -> String {
rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(64)
.map(char::from)
.collect()
}
#[derive(Debug)]
pub enum CreateSessionError {
UserDoesntExist,
DatabaseError,
}
pub async fn create_session(db: &DatabaseConnection, user_id: String, ip_address: String) -> Result<String, CreateSessionError> {
user::check_if_user_exists(db, user_id.to_string()).await.map_err(|e| match e {
FetchUserError::UserNotFound => { CreateSessionError::UserDoesntExist }
FetchUserError::DatabaseError => { CreateSessionError::DatabaseError }
})?;
let display_id = genid();
let token = generate_session_token();
let now = Utc::now();
let death = now + Duration::try_seconds(SESSION_TTL_SECONDS as i64).expect("BAD SESSION TTL SECONDS");
let record = user_session::ActiveModel {
id: Set(display_id.clone()),
user: Set(user_id),
display_id: Set(display_id),
token: Set(token.clone()),
flags: Set(0),
ip_address: Set(Some(ip_address)),
created_on: Set(now.naive_utc()),
death_date: Set(death.naive_utc()),
};
user_session::Entity::insert(record).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CREATESESSION: {e}");
CreateSessionError::DatabaseError
})?;
Ok(token)
}
#[derive(Debug)]
pub enum DeleteSessionError {
/// session doesn't exist
SessionDoesntExist,
DatabaseError,
}
/// deletes the given session from the session table, logging out the user
/// returns an error if the user or session doesn't exist, will delete the session regardless of
/// if it is expired
pub async fn delete_session(db: &DatabaseConnection, token: String) -> Result<(), DeleteSessionError> {
match check_if_session_died(db, token.clone(), false, false).await {
Ok(_) => {}
Err(e) => match e {
FetchSessionError::SessionInvalid => {}
FetchSessionError::SessionDoesntExist => { return Err(DeleteSessionError::SessionDoesntExist); }
FetchSessionError::DatabaseError => { return Err(DeleteSessionError::DatabaseError); }
}
}
user_session::Entity::delete(user_session::Entity::find().filter(user_session::Column::Token.eq(&token)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE DELETESESSION (query): {e}");
DeleteSessionError::DatabaseError
})?.ok_or(DeleteSessionError::SessionDoesntExist)?.into_active_model()).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE DELETESESSION (delete): {e}");
DeleteSessionError::DatabaseError
})?;
Ok(())
}
#[derive(Debug)]
pub enum FetchSessionError {
/// death date reached
SessionInvalid,
/// session doesn't exist
SessionDoesntExist,
DatabaseError,
}
pub async fn check_if_session_died(db: &DatabaseConnection, token: String, extend_life: bool, rm_session: bool) -> Result<(), FetchSessionError> {
let record = user_session::Entity::find().filter(user_session::Column::Token.eq(&token)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CHECKSESSIONDIED (query): {e}");
FetchSessionError::DatabaseError
})?.ok_or(FetchSessionError::SessionDoesntExist)?;
let now = Utc::now();
// is now bigger than death date?
if record.death_date.signed_duration_since(now.naive_utc()) <= TimeDelta::nanoseconds(0) {
// died
if rm_session {
user_session::Entity::delete(record.into_active_model()).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CHECKSESSIONDIED (delete): {e}");
FetchSessionError::DatabaseError
})?;
}
return Err(FetchSessionError::SessionInvalid);
}
if extend_life {
let death = now + Duration::try_seconds(SESSION_TTL_SECONDS as i64).expect("BAD SESSION TTL SECONDS");
let mut record = record.into_active_model();
record.death_date = Set(death.naive_utc());
record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CHECKSESSIONDIED (update): {e}");
FetchSessionError::DatabaseError
})?;
}
Ok(())
}
pub async fn get_session_death_date(db: &DatabaseConnection, token: String) -> Result<DateTime<Utc>, FetchSessionError> {
check_if_session_died(db, token.clone(), false, true).await?;
Ok(user_session::Entity::find().filter(user_session::Column::Token.eq(token)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE GETSESSIONDEATHDATE: {e}");
FetchSessionError::DatabaseError
})?.ok_or(FetchSessionError::SessionDoesntExist)?.death_date.and_utc())
}
pub async fn get_userid_from_session(db: &DatabaseConnection, token: String, extend_life: bool) -> Result<String, FetchSessionError> {
check_if_session_died(db, token.clone(), extend_life, true).await?;
Ok(user_session::Entity::find().filter(user_session::Column::Token.eq(&token)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE SESSION2USERID: {e}");
FetchSessionError::DatabaseError
})?.ok_or(FetchSessionError::SessionDoesntExist)?.user)
}

485
src/db/user.rs Normal file
View file

@ -0,0 +1,485 @@
/*
* authservice db/user.rs
* - pgsql user functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use argon2::{Argon2, PasswordHasher, PasswordVerifier};
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use chrono::{Days, Utc};
use futures::FutureExt;
use log::{debug, error};
use once_cell::sync::Lazy;
use regex::Regex;
use sea_orm::{ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, IntoActiveModel, ModelTrait, NotSet, PaginatorTrait, QueryFilter, QueryOrder, QuerySelect};
use sea_orm::ActiveValue::Set;
use sea_orm::prelude::Expr;
use sea_orm::sea_query::{BinOper, ExprTrait};
use entity::{user, verification_code};
use crate::db::genid;
static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"#).expect("BAD EMAIL REGEX"));
#[repr(i64)]
pub enum UserFlag {
Verified = 1 << 0,
NewEmail = 1 << 1,
Administrator = 1 << 2,
}
#[derive(Debug)]
pub enum CreateUserError {
/// user already exists with this username
UsernameTaken,
/// user already exists with this email
EmailTaken,
/// username contains invalid (not alphanumeric with dashes and underscores allowed) characters, or is arbitrarily too long
UsernameError,
/// display name contains invalid (not alphanumeric with dashes and underscores and spaces (but not at the beginning or end, or twice in a row) characters, or is arbitrarily too long
DisplayNameError,
/// email doesn't match funny email regex
EmailError,
/// password weak (not implemented yet)
PasswordError,
/// arbitrary database error, check logs
DatabaseError,
}
#[derive(Debug)]
pub enum FetchUserError {
UserNotFound,
DatabaseError,
}
/// takes a user id and returns Ok if the user exists
pub async fn check_if_user_exists(db: &DatabaseConnection, user_id: String) -> Result<(), FetchUserError> {
if user::Entity::find_by_id(&user_id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE USER EXIST CHECK: {e}");
FetchUserError::DatabaseError
})?.is_none() {
return Err(FetchUserError::UserNotFound);
}
Ok(())
}
/// takes a username and returns the associated user id, or an error if the user does not exist
pub async fn username_to_userid(db: &DatabaseConnection, username: String) -> Result<String, FetchUserError> {
let user_id: Option<String> = user::Entity::find().filter(user::Column::Username.eq(&username)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE USERNAME2USERID: {e}");
FetchUserError::DatabaseError
})?.map(|v| v.id);
if user_id.is_none() {
return Err(FetchUserError::UserNotFound);
}
Ok(user_id.unwrap())
}
/// takes an email and returns the associated user id, or an error if the user does not exist
pub async fn email_to_userid(db: &DatabaseConnection, email: String) -> Result<String, FetchUserError> {
let user_id: Option<String> = user::Entity::find().filter(user::Column::Email.eq(&email)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE EMAIL2USERID: {e}");
FetchUserError::DatabaseError
})?.map(|v| v.id);
if user_id.is_none() {
return Err(FetchUserError::UserNotFound);
}
Ok(user_id.unwrap())
}
/// creates a user in the database, you'll probably want to register an email verification code after this
/// returns id on success
pub async fn create_user(db: &DatabaseConnection, username: String, display_name: String, email: String, password: String) -> Result<String, CreateUserError> {
// rustrover gives some warnings here but don't change the regex because it's directly
// taken from the html standard
if !EMAIL_REGEX.is_match(&email) {
return Err(CreateUserError::EmailError);
}
if username.len() > 32 {
return Err(CreateUserError::UsernameError);
}
if user::Entity::find().filter(user::Column::Username.eq(&username)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CREATE USER (username taken check (database)): {e}");
CreateUserError::DatabaseError
})?.is_some() {
return Err(CreateUserError::UsernameTaken);
}
if user::Entity::find().filter(user::Column::Email.eq(&email)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CREATE USER (email taken check (database)): {e}");
CreateUserError::DatabaseError
})?.is_some() {
return Err(CreateUserError::EmailTaken);
}
let id = genid();
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let password_hash = argon2.hash_password(password.as_bytes(), &salt)
.expect("argon2 error").to_string();
let now = Utc::now();
let record = user::ActiveModel {
id: Set(id.clone()),
username: Set(username),
display_name: Set(Some(display_name)),
email: Set(email),
new_email: Set(None),
password: Set(password_hash),
flags: Set(0),
created_on: Set(now.naive_utc()),
last_updated: Set(now.naive_utc()),
};
user::Entity::insert(record).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CREATE USER (insert user): {e}");
CreateUserError::DatabaseError
})?;
Ok(id)
}
#[derive(Debug)]
pub enum DeleteUserError {
UserDoesntExist,
DatabaseError,
}
/// deletes the given user from the user table, doesn't do any other cleanup so be careful!
/// returns an error if the user doesn't exist
pub async fn delete_user(db: &DatabaseConnection, id: String) -> Result<(), DeleteUserError> {
let record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE DELETEUSER (exist check (database)): {e}");
DeleteUserError::DatabaseError
})?;
if record.is_none() {
return Err(DeleteUserError::UserDoesntExist);
}
record.unwrap().delete(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE DELETEUSER (delete (database)): {e}");
DeleteUserError::DatabaseError
})?;
Ok(())
}
#[derive(Debug)]
pub enum RegisterVerificationCodeError {
/// user is already verified, and thus we do not need a new verification code
/// note that for email changes, we use the new_verified field which is true until a new email is set
UserIsVerifiedAndNotChangingTheirEmail,
/// user seemingly doesn't exist in the database, this should be
/// shown to the user as an invalid session error, or an internal server error, depending
/// on the situation
UserDoesntExist,
DatabaseError,
}
/// inserts a new email verification code into the user flags for this user,
/// user is verified after you verify_verification_code
pub async fn register_verification_code(db: &DatabaseConnection, id: String, verification_code: String) -> Result<(), RegisterVerificationCodeError> {
let record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE REGISTERVERIFICATIONCODE (record for flags check (query)): {e}");
RegisterVerificationCodeError::DatabaseError
})?.ok_or(RegisterVerificationCodeError::UserDoesntExist)?;
// if verified and not asking for new email
if record.flags & UserFlag::Verified as i64 != 0 && record.flags & UserFlag::NewEmail as i64 == 0 {
return Err(RegisterVerificationCodeError::UserIsVerifiedAndNotChangingTheirEmail);
}
let vc_record = verification_code::ActiveModel {
id: Set(genid()),
user: Set(id.clone()),
code: Set(verification_code),
set_new_email: Set(false),
created_on: Set(Utc::now().naive_utc()),
death_date: Set(Utc::now().checked_add_days(Days::new(10)).unwrap().naive_utc()),
used: Set(false),
used_on: NotSet,
};
verification_code::Entity::insert(vc_record).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE REGISTERVERIFICATIONCODE (insert verification code): {e}");
RegisterVerificationCodeError::DatabaseError
})?;
Ok(())
}
#[derive(Debug)]
pub enum VerifyVerificationCodeError {
UserAlreadyVerified,
VerificationCodeInvalid,
UserDoesntExist,
DatabaseError,
}
/// verifies that the verification code is correct, and sets the user as verified if so
pub async fn verify_verification_code(db: &DatabaseConnection, id: String, verification_code: String) -> Result<(), VerifyVerificationCodeError> {
let vc_record = verification_code::Entity::find().filter(verification_code::Column::Code.eq(&verification_code)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (code record select): {e}");
VerifyVerificationCodeError::DatabaseError
})?.ok_or(VerifyVerificationCodeError::VerificationCodeInvalid)?;
if vc_record.user != id {
return Err(VerifyVerificationCodeError::UserDoesntExist);
}
let user_record = user::Entity::find_by_id(&vc_record.user).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (user record select): {e}");
VerifyVerificationCodeError::DatabaseError
})?.ok_or(VerifyVerificationCodeError::UserDoesntExist)?;
// if verified and not asking for new email
if user_record.flags & UserFlag::Verified as i64 != 0 && user_record.flags & UserFlag::NewEmail as i64 == 0 {
return Err(VerifyVerificationCodeError::UserAlreadyVerified);
}
let mut user_record = user_record.into_active_model();
user_record.flags = Set((*user_record.flags.as_ref() | UserFlag::Verified as i64) & !(UserFlag::NewEmail as i64));
if vc_record.set_new_email {
if let Some(email) = user_record.new_email.as_ref() {
user_record.email = Set(email.clone());
user_record.new_email = Set(None);
} else {
error!("vc record is SetNewEmail, but no new email exists for this user {id}!!! INVESTIGATE ASAP");
}
}
let mut vc_record = vc_record.into_active_model();
vc_record.used = Set(true);
vc_record.used_on = Set(Some(Utc::now().naive_utc()));
user_record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (user record update): {e}");
VerifyVerificationCodeError::DatabaseError
})?;
vc_record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE VERIFYVERIFICATIONCODE (vc record update): {e}");
VerifyVerificationCodeError::DatabaseError
})?;
Ok(())
}
/// checks if the user can log-in with their current registration status
pub async fn check_if_verified(db: &DatabaseConnection, id: String) -> Result<bool, FetchUserError> {
let user_record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CHECKVERIFICATION (user record select): {e}");
FetchUserError::DatabaseError
})?.ok_or(FetchUserError::UserNotFound)?;
Ok(user_record.flags & UserFlag::Verified as i64 != 0)
}
#[derive(Debug)]
pub enum VerifyEmailPassComboError {
ComboInvalid,
UserDoesntExist,
DatabaseError,
}
/// verifies that the given email/pass combo are correct for the account associated with the email
/// password must be unhashed
pub async fn verify_email_pass_combo(db: &DatabaseConnection, email: String, password: String) -> Result<(), VerifyEmailPassComboError> {
let password_hash = user::Entity::find().filter(user::Column::Email.eq(&email)).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE VERIFYEMAILPASSCOMBO (password hash query): {e}");
VerifyEmailPassComboError::DatabaseError
})?.ok_or(VerifyEmailPassComboError::UserDoesntExist)?.password;
let password_hash = argon2::PasswordHash::new(&password_hash).map_err(|e| {
error!("invalid password hash found for {email}! check database for corruption! argon2 error: {e}");
VerifyEmailPassComboError::DatabaseError
})?;
if Argon2::default().verify_password(password.as_bytes(), &password_hash).is_err() {
return Err(VerifyEmailPassComboError::ComboInvalid);
}
Ok(())
}
#[derive(Debug)]
pub struct UserInfo {
pub username: String,
pub email: String,
pub new_email: Option<String>,
pub admin: bool,
pub verified: bool,
}
/// gets all user info (:
pub async fn user_info(db: &DatabaseConnection, id: String) -> Result<UserInfo, FetchUserError> {
user::Entity::find_by_id(&id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE USERINFO: {e}");
FetchUserError::DatabaseError
})?.ok_or(FetchUserError::UserNotFound).map(|v| {
UserInfo {
username: v.username,
email: v.email,
new_email: v.new_email,
admin: v.flags & UserFlag::Administrator as i64 != 0,
verified: v.flags & UserFlag::Verified as i64 != 0,
}
})
}
#[derive(Debug)]
pub enum EmailChangeError {
UserNotFound,
NewEmailIsInvalid,
DatabaseError,
}
/// starts the process for changing a user's email
pub async fn start_email_change(db: &DatabaseConnection, id: String, new_email: String, verification_code: String) -> Result<(), EmailChangeError> {
if !EMAIL_REGEX.is_match(&new_email) {
return Err(EmailChangeError::NewEmailIsInvalid);
}
let user_record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE STARTEMAILCHANGE (user query): {e}");
EmailChangeError::DatabaseError
})?.ok_or(EmailChangeError::UserNotFound)?;
let flags = user_record.flags;
let mut user_record = user_record.into_active_model();
user_record.new_email = Set(Some(new_email));
user_record.flags = Set(flags | UserFlag::NewEmail as i64);
user_record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE STARTEMAILCHANGE (user update): {e}");
EmailChangeError::DatabaseError
})?;
let old_vc_records = verification_code::Entity::delete_many()
.filter(verification_code::Column::User.eq(&id))
.filter(verification_code::Column::SetNewEmail.eq(true))
.exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE STARTEMAILCHANGE (delete old email codes): {e}");
EmailChangeError::DatabaseError
})?;
debug!("deleted {} old vc code records during email change", old_vc_records.rows_affected);
let vc_record = verification_code::ActiveModel {
id: Set(genid()),
user: Set(id.clone()),
code: Set(verification_code),
set_new_email: Set(true),
created_on: Set(Utc::now().naive_utc()),
death_date: Set(Utc::now().checked_add_days(Days::new(10)).unwrap().naive_utc()),
used: Set(false),
used_on: NotSet,
};
verification_code::Entity::insert(vc_record).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE STARTEMAILCHANGE (insert verification code): {e}");
EmailChangeError::DatabaseError
})?;
Ok(())
}
/// cancels any in-progress user email change
pub async fn cancel_email_change(db: &DatabaseConnection, id: String) -> Result<(), FetchUserError> {
verification_code::Entity::delete_many()
.filter(verification_code::Column::User.eq(&id))
.filter(verification_code::Column::SetNewEmail.eq(true))
.exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CANCELEMAILCHANGE (delete old email codes): {e}");
FetchUserError::DatabaseError
})?;
let mut user_record = user::Entity::find_by_id(&id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CANCELEMAILCHANGE (query user): {e}");
FetchUserError::DatabaseError
})?.ok_or(FetchUserError::UserNotFound)?.into_active_model();
let flags = *user_record.flags.as_ref();
user_record.new_email = Set(None);
// unset new email
user_record.flags = Set(flags & !(UserFlag::NewEmail as i64));
user_record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE CANCELEMAILCHANGE (user update): {e}");
FetchUserError::DatabaseError
})?;
Ok(())
}
/// returns the last 10 users added to the database as usernames
pub async fn last_ten_usernames(db: &DatabaseConnection) -> Result<Vec<String>, FetchUserError> {
Ok(user::Entity::find()
.order_by_desc(user::Column::CreatedOn)
.limit(Some(10))
.all(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE LASTTENUSERNAMES: {e}");
FetchUserError::DatabaseError
})?.into_iter().map(|v| v.username).collect())
}
pub async fn all_users(db: &DatabaseConnection) -> Result<Vec<UserInfo>, FetchUserError> {
Ok(user::Entity::find().all(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE ALLUSERS: {e}");
FetchUserError::DatabaseError
})?.into_iter().map(|v| {
UserInfo {
username: v.username,
email: v.email,
new_email: v.new_email,
admin: v.flags & UserFlag::Administrator as i64 != 0,
verified: v.flags & UserFlag::Verified as i64 != 0,
}
}).collect())
}
/// returns the number of users in the database
pub async fn user_count(db: &DatabaseConnection) -> Result<usize, FetchUserError> {
Ok(user::Entity::find().count(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE USERCOUNT: {e}");
FetchUserError::DatabaseError
})? as usize)
}
/// returns the number of users in the database who are admins
pub async fn admin_count(db: &DatabaseConnection) -> Result<usize, FetchUserError> {
// dont fucking touch this, i don't know why it works but it does, it's actually evil
Ok(user::Entity::find().filter(user::Column::Flags.into_expr().binary(BinOper::LShift, Expr::value(63 - 2)).lt(1 << (63 - 2)))
.count(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE ADMINCOUNT: {e}");
FetchUserError::DatabaseError
})? as usize)
}
/// returns the number of unverified accounts (this does NOT count email change requests)
pub async fn unverified_count(db: &DatabaseConnection) -> Result<usize, FetchUserError> {
Ok(verification_code::Entity::find().filter(verification_code::Column::SetNewEmail.eq(false)).filter(verification_code::Column::Used.eq(false))
.count(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE UNVERIFIEDCOUNT: {e}");
FetchUserError::DatabaseError
})? as usize)
}
/// returns a list of all (username, email) to send announcement emails to
pub async fn email_list(db: &DatabaseConnection) -> Result<Vec<(String, String)>, FetchUserError> {
// fixme: filter by who wants emails and who doesn't when we implement that
Ok(user::Entity::find().all(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE EMAILLIST: {e}");
FetchUserError::DatabaseError
})?.into_iter().map(|v| {
(v.username, v.email)
}).collect())
}

79
src/db/usersettings.rs Normal file
View file

@ -0,0 +1,79 @@
/*
* authservice db/usersettings.rs
* - pgsql usersettings functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use log::error;
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, IntoActiveModel};
use sea_orm::ActiveValue::Set;
use entity::user_settings;
use crate::db::user::{check_if_user_exists, FetchUserError};
#[derive(Debug, Clone)]
pub struct UserSettings {
pub theme: String,
}
#[derive(Debug)]
pub enum FetchUserSettingsError {
UserNotFound,
DatabaseError,
}
pub async fn get_or_create_default_user_settings(db: &DatabaseConnection, user_id: String) -> Result<UserSettings, FetchUserSettingsError> {
if let Some(us) = user_settings::Entity::find_by_id(&user_id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE FETCH USER SETTINGS: {e}");
FetchUserSettingsError::DatabaseError
})? {
return Ok(UserSettings {
theme: us.theme
});
}
check_if_user_exists(db, user_id.clone()).await.map_err(|e| {
match e {
FetchUserError::UserNotFound => {FetchUserSettingsError::UserNotFound}
FetchUserError::DatabaseError => {FetchUserSettingsError::DatabaseError}
}
})?;
let us_record = user_settings::ActiveModel {
user: Set(user_id),
theme: Set("default".to_string()),
};
user_settings::Entity::insert(us_record).exec(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}");
FetchUserSettingsError::DatabaseError
})?;
Ok(UserSettings {
theme: "default".to_string(),
})
}
pub async fn set_theme(db: &DatabaseConnection, user_id: String, theme: String) -> Result<(), FetchUserSettingsError> {
get_or_create_default_user_settings(db, user_id.clone()).await?;
let mut us_record = user_settings::Entity::find_by_id(&user_id).one(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}");
FetchUserSettingsError::DatabaseError
})?.ok_or(FetchUserSettingsError::UserNotFound)?.into_active_model();
us_record.theme = Set(theme);
us_record.update(db).await.map_err(|e| {
error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}");
FetchUserSettingsError::DatabaseError
})?;
Ok(())
}

176
src/email/mod.rs Normal file
View file

@ -0,0 +1,176 @@
/*
* authservice email/mod.rs
* - email thread, most of everything needed for emails are in this file
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
mod templates;
use lettre::{Message, SmtpTransport, Transport};
use lettre::message::header::ContentType;
use lettre::transport::smtp::authentication::Credentials;
use log::{error, info};
use tokio::sync::{mpsc, OnceCell};
use crate::{SMTP_DISABLE, SMTP_PASSWORD, SMTP_URL, SMTP_USERNAME};
pub enum EmailMessage {
VerificationCode {
to: String,
username: String,
url: String,
},
DeveloperWarning {
message: String,
},
Announcement {
to: String,
username: String,
title: String,
text_contents: String,
}
}
static EMAIL_SENDER: OnceCell<mpsc::UnboundedSender<EmailMessage>> = OnceCell::const_new();
const EMAIL_RETRY_TIME_SECS: u64 = 10;
const DEVWARNING_TARGET: &str = "AskLyphe Developer <devnull@voremicrocomputers.com>";
pub fn send_devwarn_email(message: &str) {
EMAIL_SENDER.get().unwrap().send(EmailMessage::DeveloperWarning {
message: message.to_string(),
}).unwrap();
}
pub fn send_verification_code_email(to: &str, username: &str, url: &str) {
EMAIL_SENDER.get().unwrap().send(EmailMessage::VerificationCode {
to: to.to_string(),
username: username.to_string(),
url: url.to_string(),
}).unwrap();
}
pub fn send_announcement_email(to: &str, username: &str, title: &str, content: &str) {
EMAIL_SENDER.get().unwrap().send(EmailMessage::Announcement {
to: to.to_string(),
username: username.to_string(),
title: title.to_string(),
text_contents: content.to_string(),
}).unwrap()
}
pub async fn email_init() {
let (email_sender, email_receiver) = mpsc::unbounded_channel();
EMAIL_SENDER.set(email_sender).unwrap();
tokio::spawn(async move {
info!("email thread spawned");
if *SMTP_DISABLE {
info!("SMTP disable");
}
let creds = Credentials::new(SMTP_USERNAME.to_string(), SMTP_PASSWORD.to_string());
let mailer = SmtpTransport::starttls_relay(&SMTP_URL).expect("FAILED TO CONNECT TO EMAIL SMTP RELAY")
.credentials(creds)
.build();
let mut rx = email_receiver;
loop {
if let Ok(message) = rx.try_recv() {
match message {
EmailMessage::VerificationCode { to, username, url } => {
if *SMTP_DISABLE {
info!("not sending smtp verification code due to smtp disable");
continue;
}
let body = templates::gen_verification_code_email(&url);
let email = Message::builder()
.from("Vore Microcomputers No-Reply <no-reply@voremicrocomputers.com>".parse().unwrap())
.reply_to("Vore Microcomputers Support <devnull@voremicrocomputers.com>".parse().unwrap());
let to_mbox = format!("{username} <{to}>").parse();
if let Err(e) = to_mbox {
error!("couldn't parse \"to\" field for verification code email! \"{username}\" \"{to}\"");
send_devwarn_email(&format!("couldn't parse \"to\" field for verification code email! \"{username}\" \"{to}\" you need to send the email manually and investigate"));
continue;
}
let email = email.to(to_mbox.unwrap())
.subject("AskLyphe Account Verification")
.header(ContentType::TEXT_PLAIN)
.body(body);
if let Err(e) = email {
error!("couldn't generate email for verification! \"{e}\" \"{username}\" \"{to}\"");
send_devwarn_email(&format!("couldn't generate verification code email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate"));
continue;
}
let email = email.unwrap();
if let Err(e) = mailer.send(&email) {
error!("couldn't send email for verification! \"{e}\" \"{username}\" \"{to}\"");
send_devwarn_email(&format!("couldn't send verification code email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate"));
continue;
}
}
EmailMessage::DeveloperWarning { message } => {
if *SMTP_DISABLE {
info!("not sending smtp developer warning due to smtp disable");
continue;
}
let body = templates::gen_developer_warning_email(&message);
let email = Message::builder()
.from("Vore Microcomputers No-Reply <no-reply@voremicrocomputers.com>".parse().unwrap())
.to(DEVWARNING_TARGET.parse().unwrap())
.subject("AskLyphe Developer Warning")
.header(ContentType::TEXT_PLAIN)
.body(body);
if let Err(e) = email {
error!("couldn't generate email for developer warning!! \"{e}\" \"{message}\"");
continue;
}
let email = email.unwrap();
if let Err(e) = mailer.send(&email) {
error!("couldn't send email for developer warning!!! \"{e}\" \"{message}\"");
continue;
}
}
EmailMessage::Announcement { to, username, title, text_contents } => {
if *SMTP_DISABLE {
info!("not sending smtp announcement due to smtp disable");
continue;
}
let body = templates::gen_announcement_email(&text_contents);
let email = Message::builder()
.from("Vore Microcomputers No-Reply <no-reply@voremicrocomputers.com>".parse().unwrap())
.reply_to("Vore Microcomputers Support <devnull@voremicrocomputers.com>".parse().unwrap());
let to_mbox = format!("{username} <{to}>").parse();
if let Err(e) = to_mbox {
error!("couldn't parse \"to\" field for announcement email! \"{username}\" \"{to}\"");
send_devwarn_email(&format!("couldn't parse \"to\" field for announcement email! \"{username}\" \"{to}\" you need to send the email manually and investigate"));
continue;
}
let email = email.to(to_mbox.unwrap())
.subject(format!("AskLyphe Announcement: {title}").as_str())
.header(ContentType::TEXT_PLAIN)
.body(body);
if let Err(e) = email {
error!("couldn't generate email for announcement! \"{e}\" \"{username}\" \"{to}\"");
send_devwarn_email(&format!("couldn't generate announcement email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate"));
continue;
}
let email = email.unwrap();
if let Err(e) = mailer.send(&email) {
error!("couldn't send email for announcement! \"{e}\" \"{username}\" \"{to}\"");
send_devwarn_email(&format!("couldn't send announcement email! \"{e}\" \"{username}\" \"{to}\" you need to send the email manually and investigate"));
continue;
}
}
}
}
}
});
}

54
src/email/templates.rs Normal file
View file

@ -0,0 +1,54 @@
/*
* authservice email/templates.rs
* - high tech templating system for emails
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pub fn gen_verification_code_email(url: &str) -> String {
format!(r#"thank you for signing up for AskLyphe!
before you can ask lyphe, you must verify your account by opening the link below!
{url}
please note that if your email client has a feature which generates a preview of the link,
your account may already be verified and the url will show an error.
in this case, you can just go ahead and login, hopefully without any further issues!
this issue will be fixed by the end of beta testing.
we won't email you much, but if you don't want us to email you regarding updates to the service that
we consider important, please email devnull@voremicrocomputers.com with your username and we will
opt you out of future announcements.
please note that this email account (no-reply@voremicrocomputers.com) is not checked for received
mail, and all inquiries should be sent to devnull@voremicrocomputers.com
thank you (:
"#)
}
pub fn gen_developer_warning_email(message: &str) -> String {
format!(r#"hello asklyphe developer!
an error occurred within the authservice which needs attention!
the given message is as follows:
{message}
"#)
}
pub fn gen_announcement_email(contents: &str) -> String {
format!(r#"{contents}
---
this email was automatically sent because an announcement was posted,
if you would like to not receive these emails in the future, please email us at devnull@voremicrocomputers.com
in the future, you will be able to configure this on your account settings page
we try to keep our email send count as minimal as possible, and we don't want to fill your inbox with spam (:
"#)
}

92
src/main.rs Normal file
View file

@ -0,0 +1,92 @@
/*
* authservice main.rs
* - entrypoint for the asklyphe authentication service
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
mod process;
pub mod db;
mod email;
use std::string::ToString;
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
use asklyphe_common::nats::authservice::AuthServiceResponse;
use async_nats::jetstream;
use log::{debug, error, info, warn};
use once_cell::sync::Lazy;
use asklyphe_common::nats::comms;
use sea_orm::Database;
use crate::email::email_init;
pub static NATS_URL: Lazy<String> = Lazy::new(|| std::env::var("NATS_URL").expect("NO NATS DEFINED"));
pub static NATS_CERT: Lazy<String> = Lazy::new(|| std::env::var("NATS_CERT").expect("NO NATS_CERT DEFINED"));
pub static NATS_KEY: Lazy<String> = Lazy::new(|| std::env::var("NATS_KEY").expect("NO NATS_KEY DEFINED"));
pub static DB_URL: Lazy<String> = Lazy::new(|| std::env::var("DB_URL").expect("NO DB_URL DEFINED"));
pub static SMTP_DISABLE: Lazy<bool> = Lazy::new(|| std::env::var("SMTP_DISABLE").is_ok());
pub static SMTP_URL: Lazy<String> = Lazy::new(|| std::env::var("SMTP_URL").expect("NO SMTP_URL DEFINED"));
pub static SMTP_USERNAME: Lazy<String> = Lazy::new(|| std::env::var("SMTP_USERNAME").expect("NO SMTP_USERNAME DEFINED"));
pub static SMTP_PASSWORD: Lazy<String> = Lazy::new(|| std::env::var("SMTP_PASSWORD").expect("NO SMTP_PASSWORD DEFINED"));
pub static PROCESSES_HANDLED: AtomicU64 = AtomicU64::new(0);
pub static LAST_MESSAGE: AtomicI64 = AtomicI64::new(0);
#[tokio::main]
async fn main() {
env_logger::init();
info!("authservice began at {}", chrono::Utc::now().to_string());
let nats = async_nats::ConnectOptions::new()
.add_client_certificate(NATS_CERT.as_str().into(), NATS_KEY.as_str().into())
.connect(NATS_URL.as_str())
.await;
if let Err(e) = nats {
error!("FATAL ERROR, COULDN'T CONNECT TO NATS: {}", e);
return;
}
let nats = nats.unwrap();
let nats = jetstream::new(nats);
email_init().await;
info!("authservice thread spawned");
async fn on_recv(query: comms::Query) -> comms::ServiceResponse {
debug!("recv");
let db = Database::connect(DB_URL.as_str()).await;
if let Err(e) = db {
error!("FATAL ERROR, COULDN'T CONNECT TO DATABASE: {e}");
return comms::ServiceResponse::AuthService(AuthServiceResponse::OtherError("FATAL ERROR, COULDN'T CONNECT TO DATABASE".to_string()));
}
let db = db.unwrap();
let now = chrono::Utc::now().timestamp();
LAST_MESSAGE.store(now, Ordering::Relaxed);
let response = match query {
comms::Query::AuthService(query) => {
process::process(query, db).await
}
_ => {
AuthServiceResponse::InvalidRequest
}
};
if PROCESSES_HANDLED.load(Ordering::Relaxed) % 100 == 0 {
info!("handled {} requests!", PROCESSES_HANDLED.load(Ordering::Relaxed));
}
PROCESSES_HANDLED.fetch_add(1, Ordering::Relaxed);
comms::ServiceResponse::AuthService(response)
}
if let Err(e) = comms::subscribe_service(comms::Service::AuthService, &nats, Arc::new(on_recv)).await {
error!("failed to subscribe to authservice nats! reason {:?}", e);
}
}

361
src/process/admin.rs Normal file
View file

@ -0,0 +1,361 @@
/*
* authservice process/admin.rs
* - admin request functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::future::Future;
use asklyphe_common::nats::authservice::admin::{AdminCreateAnnouncementRequest, AdminCreateAnnouncementResponse, AdminInviteCodeGenerateRequest, AdminInviteCodeGenerateResponse, AdminListAllUsersRequest, AdminListAllUsersResponse, AdminListInviteCodesRequest, AdminListInviteCodesResponse, AdminUpdateAnnouncementRequest, AdminUpdateAnnouncementResponse, InviteCodeSerialized, Stats, StatsRequest, StatsResponse, UserSerialized};
use log::error;
use sea_orm::DatabaseConnection;
use entity::invite_code::Model;
use crate::db::{announcements, invite_code, session, user};
use crate::db::announcements::{AnnouncementInsertError, AnnouncementUpdateError};
use crate::db::invite_code::{InviteCodeGenerationError, InviteCodeListError};
use crate::db::session::FetchSessionError;
use crate::db::user::{FetchUserError, UserInfo};
use crate::email::send_announcement_email;
async fn admin_info(db: &DatabaseConnection, token: String) -> Result<Option<UserInfo>, FetchSessionError> {
let uid = match session::get_userid_from_session(db, token, true).await {
Ok(u) => u,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
Err(FetchSessionError::SessionInvalid)
}
FetchSessionError::SessionDoesntExist => {
Err(FetchSessionError::SessionDoesntExist)
}
FetchSessionError::DatabaseError => {
Err(FetchSessionError::DatabaseError)
}
}
}
};
let info = match user::user_info(db, uid).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserError::UserNotFound => {
Err(FetchSessionError::SessionDoesntExist)
}
FetchUserError::DatabaseError => {
Err(FetchSessionError::DatabaseError)
}
}
};
if !info.admin {
return Ok(None);
}
Ok(Some(info))
}
pub async fn stats(db: &DatabaseConnection, request: StatsRequest) -> StatsResponse {
let info = admin_info(db, request.token).await;
let _info = if let Ok(info) = info {
if let Some(info) = info {
info
} else {
return StatsResponse::AccessDenied;
}
} else {
return match info.unwrap_err() {
FetchSessionError::SessionInvalid => {
StatsResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
StatsResponse::Logout
}
FetchSessionError::DatabaseError => {
StatsResponse::InternalServerError("database error".to_string())
}
};
};
let last_ten_users = match user::last_ten_usernames(db).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserError::UserNotFound => { unreachable!() }
FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )}
}
};
let user_count = match user::user_count(db).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserError::UserNotFound => { unreachable!() }
FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )}
}
};
let admin_count = match user::admin_count(db).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserError::UserNotFound => { unreachable!() }
FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )}
}
};
let active_verification_requests = match user::unverified_count(db).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserError::UserNotFound => { unreachable!() }
FetchUserError::DatabaseError => { StatsResponse::InternalServerError("database error".to_string() )}
}
};
StatsResponse::Success(Stats {
last_ten_users,
user_count,
admin_count,
active_verification_requests,
})
}
pub async fn admin_invite_code_gen(db: &DatabaseConnection, request: AdminInviteCodeGenerateRequest) -> AdminInviteCodeGenerateResponse {
let info = admin_info(db, request.token).await;
let info = if let Ok(info) = info {
if let Some(info) = info {
info
} else {
return AdminInviteCodeGenerateResponse::AccessDenied;
}
} else {
return match info.unwrap_err() {
FetchSessionError::SessionInvalid => {
AdminInviteCodeGenerateResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
AdminInviteCodeGenerateResponse::Logout
}
FetchSessionError::DatabaseError => {
AdminInviteCodeGenerateResponse::InternalServerError("database error".to_string())
}
};
};
let issuer = info.username;
match invite_code::insert_new_invitecode(db, request.invite_code, issuer.clone(), issuer, request.comment).await {
Ok(_) => {
AdminInviteCodeGenerateResponse::Success
}
Err(e) => match e {
InviteCodeGenerationError::CodeAlreadyInserted => {
AdminInviteCodeGenerateResponse::CodeAlreadyExists
}
InviteCodeGenerationError::DatabaseError => {
AdminInviteCodeGenerateResponse::InternalServerError("database error".to_string())
}
}
}
}
pub async fn admin_create_announcement(db: &DatabaseConnection, request: AdminCreateAnnouncementRequest) -> AdminCreateAnnouncementResponse {
let info = admin_info(db, request.token).await;
let info = if let Ok(info) = info {
if let Some(info) = info {
info
} else {
return AdminCreateAnnouncementResponse::AccessDenied;
}
} else {
return match info.unwrap_err() {
FetchSessionError::SessionInvalid => {
AdminCreateAnnouncementResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
AdminCreateAnnouncementResponse::Logout
}
FetchSessionError::DatabaseError => {
AdminCreateAnnouncementResponse::InternalServerError("database error".to_string())
}
};
};
let uid = match user::username_to_userid(db, info.username.clone()).await {
Ok(v) => v,
Err(e) => {
match e {
FetchUserError::UserNotFound => {
error!("user id not found for username {}", info.username);
}
FetchUserError::DatabaseError => {
}
}
return AdminCreateAnnouncementResponse::InternalServerError("database error".to_string());
}
};
match announcements::create_announcement(db, request.slug, request.title.clone(), request.short_text, request.full_markdown_text.clone(), uid).await {
Ok(_) => {
if request.send_emails {
let email_list = user::email_list(db).await.unwrap_or_else(|e| match e {
FetchUserError::UserNotFound => {
unreachable!()
}
FetchUserError::DatabaseError => {
error!("couldn't send announcement emails due to a database error! you will need to send them manually!");
vec![]
}
});
for (username, email) in email_list {
send_announcement_email(&email, &username, &request.title, &request.full_markdown_text);
}
}
AdminCreateAnnouncementResponse::Success
}
Err(e) => match e {
AnnouncementInsertError::SlugInUse => {
AdminCreateAnnouncementResponse::SlugTaken
}
AnnouncementInsertError::DatabaseError => {
AdminCreateAnnouncementResponse::InternalServerError("database error".to_string())
}
}
}
}
pub async fn admin_update_announcement(db: &DatabaseConnection, request: AdminUpdateAnnouncementRequest) -> AdminUpdateAnnouncementResponse {
let info = admin_info(db, request.token).await;
let _info = if let Ok(info) = info {
if let Some(info) = info {
info
} else {
return AdminUpdateAnnouncementResponse::AccessDenied;
}
} else {
return match info.unwrap_err() {
FetchSessionError::SessionInvalid => {
AdminUpdateAnnouncementResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
AdminUpdateAnnouncementResponse::Logout
}
FetchSessionError::DatabaseError => {
AdminUpdateAnnouncementResponse::InternalServerError("database error".to_string())
}
};
};
match announcements::update_announcement(db, request.slug, request.new_title, request.new_short_text, request.new_full_markdown_text).await {
Ok(_) => {
AdminUpdateAnnouncementResponse::Success
}
Err(e) => match e {
AnnouncementUpdateError::SlugNotFound => {
AdminUpdateAnnouncementResponse::OriginalNotFound
}
AnnouncementUpdateError::DatabaseError => {
AdminUpdateAnnouncementResponse::InternalServerError("database error".to_string())
}
}
}
}
pub async fn admin_list_invite_codes(db: &DatabaseConnection, request: AdminListInviteCodesRequest) -> AdminListInviteCodesResponse {
let info = admin_info(db, request.token).await;
let _info = if let Ok(info) = info {
if let Some(info) = info {
info
} else {
return AdminListInviteCodesResponse::AccessDenied;
}
} else {
return match info.unwrap_err() {
FetchSessionError::SessionInvalid => {
AdminListInviteCodesResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
AdminListInviteCodesResponse::Logout
}
FetchSessionError::DatabaseError => {
AdminListInviteCodesResponse::InternalServerError("database error".to_string())
}
};
};
match invite_code::list_invite_codes(db, request.show_used).await {
Ok(v) => {
let mut serialized = vec![];
for v in v {
let used_by = if let Some(used_by) = v.used_by {
Some(match user::user_info(db, used_by.clone()).await {
Ok(v) => { v.username }
Err(v) => { format!("error fetching {}, err is {:?}", used_by, v) }
})
} else {
None
};
serialized.push(
InviteCodeSerialized {
code: v.code,
comment: v.comment.unwrap_or_default(),
creator: v.issuer.unwrap_or_default(),
root_creator: v.root_issuer,
created_at: v.created_on.and_utc().to_string(),
used_at: v.used_on.map(|v| v.and_utc().to_string()),
used_by,
});
}
AdminListInviteCodesResponse::Success(serialized)
}
Err(e) => {
match e {
InviteCodeListError::DatabaseError => {
AdminListInviteCodesResponse::InternalServerError("database error".to_string())
}
}
}
}
}
pub async fn admin_list_all_users(db: &DatabaseConnection, request: AdminListAllUsersRequest) -> AdminListAllUsersResponse {
let info = admin_info(db, request.token).await;
let _info = if let Ok(info) = info {
if let Some(info) = info {
info
} else {
return AdminListAllUsersResponse::AccessDenied;
}
} else {
return match info.unwrap_err() {
FetchSessionError::SessionInvalid => {
AdminListAllUsersResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
AdminListAllUsersResponse::Logout
}
FetchSessionError::DatabaseError => {
AdminListAllUsersResponse::InternalServerError("database error".to_string())
}
};
};
match user::all_users(db).await {
Ok(v) => {
AdminListAllUsersResponse::Success(v.into_iter().map(|v| {
UserSerialized {
username: v.username,
email: v.email,
verified: v.verified,
admin: v.admin,
}
}).collect())
}
Err(e) => {
match e {
FetchUserError::UserNotFound => {
unreachable!("usernotfound should not be returned from user::all_users!")
}
FetchUserError::DatabaseError => {
AdminListAllUsersResponse::InternalServerError("database error".to_string())
}
}
}
}
}

View file

@ -0,0 +1,104 @@
/*
* authservice process/announcements.rs
* - announcement-related request functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::future::Future;
use asklyphe_common::nats::authservice::announcements::{AnnouncementFull, AnnouncementFullRequest, AnnouncementFullResponse, AnnouncementListRequest, AnnouncementListResponse, AnnouncementShortForm, LatestAnnouncementRequest, LatestAnnouncementResponse};
use log::warn;
use sea_orm::DatabaseConnection;
use crate::db::{announcements, user};
use crate::db::announcements::{AnnouncementFetchError, AnnouncementRecord};
use crate::db::user::{FetchUserError, UserInfo};
pub async fn latest_announcement(db: &DatabaseConnection, request: LatestAnnouncementRequest) -> LatestAnnouncementResponse {
match announcements::latest_announcement(db).await {
Ok(v) => {
LatestAnnouncementResponse::Some(AnnouncementShortForm {
title: v.title,
short_text: v.short,
date: v.created_on.timestamp(),
slug: v.slug,
})
}
Err(e) => match e {
AnnouncementFetchError::SlugNotFound => {
LatestAnnouncementResponse::None
}
AnnouncementFetchError::DatabaseError => {
LatestAnnouncementResponse::InternalServerError("database error".to_string())
}
}
}
}
// fixme: listen to limit and actually limit the amount returned
pub async fn announcement_list(db: &DatabaseConnection, request: AnnouncementListRequest) -> AnnouncementListResponse {
match announcements::get_all_announcements(db).await {
Ok(v) => {
AnnouncementListResponse::Success(v.into_iter().map(|v| {
AnnouncementShortForm {
title: v.title,
short_text: v.short,
date: v.created_on.timestamp(),
slug: v.slug,
}
}).collect())
}
Err(e) => match e {
AnnouncementFetchError::SlugNotFound => {
AnnouncementListResponse::Success(vec![])
}
AnnouncementFetchError::DatabaseError => {
AnnouncementListResponse::InternalServerError("database error".to_string())
}
}
}
}
pub async fn announcement_full(db: &DatabaseConnection, request: AnnouncementFullRequest) -> AnnouncementFullResponse {
match announcements::get_announcement(db, request.slug).await {
Ok(v) => {
let username = match user::user_info(db, v.creator_uid.clone()).await {
Ok(v) => {
v.username
}
Err(e) => {
match e {
FetchUserError::UserNotFound => {
warn!("creator {} not found for announcement", v.creator_uid);
}
FetchUserError::DatabaseError => {
warn!("database error while getting full announcement");
}
}
"lyphe".to_string()
}
};
AnnouncementFullResponse::Some(AnnouncementFull {
title: v.title,
created_on: v.created_on.timestamp(),
updated_on: v.updated_on.map(|v| v.timestamp()),
slug: v.slug,
creator: username,
markdown_text: v.full,
})
}
Err(e) => match e {
AnnouncementFetchError::SlugNotFound => {
AnnouncementFullResponse::NotFound
}
AnnouncementFetchError::DatabaseError => {
AnnouncementFullResponse::InternalServerError("database error".to_string())
}
}
}
}

View file

@ -0,0 +1,349 @@
/*
* authservice process/basic_accounts.rs
* - basic authentication + creation for accounts, as well as a few other things
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::future::Future;
use asklyphe_common::nats::authservice::{AuthError, AuthRequest, AuthResponse, AuthServiceResponse, CancelEmailChangeRequest, CancelEmailChangeResponse, EmailChangeRequest, EmailChangeResponse, EmailError, LoginError, LoginRequest, LoginResponse, LogoutRequest, LogoutResponse, PasswordError, RegisterError, RegisterRequest, RegisterResponse, TokenAssignment, UsernameError, VerifyEmailRequest, VerifyEmailResponse};
use chrono::{DateTime, Utc};
use log::{debug, error};
use rand::Rng;
use sea_orm::DatabaseConnection;
use crate::db::{invite_code, session, user};
use crate::db::invite_code::ConsumeInviteCodeError;
use crate::db::session::{CreateSessionError, DeleteSessionError, FetchSessionError};
use crate::db::user::{CreateUserError, DeleteUserError, EmailChangeError, FetchUserError, RegisterVerificationCodeError, VerifyEmailPassComboError, VerifyVerificationCodeError};
use crate::email;
fn generate_email_verification_code() -> String {
rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(16)
.map(char::from)
.collect()
}
pub async fn register_request(db: &DatabaseConnection, request: RegisterRequest) -> RegisterResponse {
// goes something like:
// 1. create user in db
// 2. try to consume invite code
// 2.5. if that fails, delete user from db
// 3. otherwise, register email verification code in db
// 4. this is where we'd send emails out with the verification code, if we had that set up...
let user = user::create_user(
db,
request.username.clone(),
request.username.clone(),
request.email.clone(),
request.password).await;
if let Err(e) = user {
return match e {
CreateUserError::UsernameTaken => {
RegisterResponse::Failure(RegisterError::Username(UsernameError::Taken))
}
CreateUserError::EmailTaken => {
RegisterResponse::Failure(RegisterError::Email(EmailError::EmailTaken))
}
CreateUserError::UsernameError => {
RegisterResponse::Failure(RegisterError::Username(UsernameError::InvalidCharacters))
}
CreateUserError::DisplayNameError => {
unimplemented!("we don't explicitly allow display names to be set, username error would be hit before display name error")
}
CreateUserError::EmailError => {
RegisterResponse::Failure(RegisterError::Email(EmailError::InvalidEmail))
}
CreateUserError::PasswordError => {
// todo: actual password errors that tell you why it's bad
RegisterResponse::Failure(RegisterError::Password(PasswordError::TooShort))
}
CreateUserError::DatabaseError => {
RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string()))
}
};
}
let user_id = user.unwrap();
if let Err(e) = invite_code::consume_invite_code(db, request.invite_code.clone(), user_id.clone()).await {
if let Err(e) = user::delete_user(db, user_id.clone()).await {
return match e {
DeleteUserError::UserDoesntExist => {
RegisterResponse::Failure(RegisterError::InternalServer("unexpected missing user".to_string()))
}
DeleteUserError::DatabaseError => {
RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string()))
}
};
}
return match e {
ConsumeInviteCodeError::InvalidUser => {
RegisterResponse::Failure(RegisterError::InternalServer("unexpected missing user".to_string()))
}
ConsumeInviteCodeError::DatabaseError => {
RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string()))
}
_ => {
RegisterResponse::Failure(RegisterError::BadInviteCode)
}
};
}
let verification_code = generate_email_verification_code();
if let Err(e) = user::register_verification_code(db, user_id.clone(), verification_code.clone()).await {
if let Err(e) = user::delete_user(db, user_id.clone()).await {
match e {
DeleteUserError::UserDoesntExist => {
error!("failed to register verify code during signup, and couldn't delete the user because they don't exist?")
}
DeleteUserError::DatabaseError => {
error!("database error while trying to delete user after registering verify code failed during signup")
}
}
}
return match e {
RegisterVerificationCodeError::UserIsVerifiedAndNotChangingTheirEmail => {
RegisterResponse::Failure(RegisterError::InternalServer("unexpected corrupt user struct".to_string()))
}
RegisterVerificationCodeError::UserDoesntExist => {
RegisterResponse::Failure(RegisterError::InternalServer("unexpected missing user".to_string()))
}
RegisterVerificationCodeError::DatabaseError => {
RegisterResponse::Failure(RegisterError::InternalServer("database error".to_string()))
}
};
}
debug!("verification code for {} is \"{}\"", request.username, verification_code);
email::send_verification_code_email(&request.email, &request.username, format!("https://auth.asklyphe.com/verify?username={}&token={}", request.username, verification_code).as_str());
RegisterResponse::Success
}
pub async fn verify_email(db: &DatabaseConnection, request: VerifyEmailRequest) -> VerifyEmailResponse {
let user_id = user::username_to_userid(db, request.username).await;
if let Err(e) = user_id {
return match e {
FetchUserError::UserNotFound => {
VerifyEmailResponse::InvalidToken
}
FetchUserError::DatabaseError => {
VerifyEmailResponse::InternalServerError("database error during username2userid".to_string())
}
};
}
let user_id = user_id.unwrap();
if let Err(e) = user::verify_verification_code(db, user_id, request.token).await {
return match e {
VerifyVerificationCodeError::UserAlreadyVerified => {
VerifyEmailResponse::InvalidToken
}
VerifyVerificationCodeError::VerificationCodeInvalid => {
VerifyEmailResponse::InvalidToken
}
VerifyVerificationCodeError::UserDoesntExist => {
VerifyEmailResponse::InvalidToken
}
VerifyVerificationCodeError::DatabaseError => {
VerifyEmailResponse::InternalServerError("database error during username2userid".to_string())
}
};
}
VerifyEmailResponse::Success
}
pub async fn login(db: &DatabaseConnection, request: LoginRequest) -> LoginResponse {
// 1. verify that credentials are correct
// 2. create session
// 3. return token
if let Err(e) = user::verify_email_pass_combo(db, request.email.clone(), request.password).await {
return match e {
VerifyEmailPassComboError::ComboInvalid => {
LoginResponse::Failure(LoginError::InvalidAccount)
}
VerifyEmailPassComboError::UserDoesntExist => {
LoginResponse::Failure(LoginError::InvalidAccount)
}
VerifyEmailPassComboError::DatabaseError => {
LoginResponse::Failure(LoginError::InternalServer("database error while verifying email/pass combo".to_string()))
}
};
}
let user_id = match user::email_to_userid(db, request.email).await {
Ok(user_id) => { user_id }
Err(e) => {
return match e {
FetchUserError::UserNotFound => {
LoginResponse::Failure(LoginError::InvalidAccount)
}
FetchUserError::DatabaseError => {
LoginResponse::Failure(LoginError::InternalServer("database error while converting email to userid".to_string()))
}
};
}
};
match user::check_if_verified(db, user_id.clone()).await {
Ok(b) => {
if !b {
return LoginResponse::Failure(LoginError::AccountNotVerified);
}
}
Err(e) => {
return match e {
FetchUserError::UserNotFound => {
LoginResponse::Failure(LoginError::InvalidAccount)
}
FetchUserError::DatabaseError => {
LoginResponse::Failure(LoginError::InternalServer("database error while checking verification status".to_string()))
}
};
}
}
let session_token = match session::create_session(db, user_id, "".to_string()).await {
Ok(s) => s,
Err(e) => {
return match e {
CreateSessionError::UserDoesntExist => {
LoginResponse::Failure(LoginError::InvalidAccount)
}
CreateSessionError::DatabaseError => {
LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string()))
}
};
}
};
let death_date = match session::get_session_death_date(db, session_token.clone()).await {
Ok(s) => s,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
error!("unexpected session invalid after just creating it during login!");
LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string()))
}
FetchSessionError::SessionDoesntExist => {
error!("unexpected session not found after just creating it during login!");
LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string()))
}
FetchSessionError::DatabaseError => {
LoginResponse::Failure(LoginError::InternalServer("database error while creating session".to_string()))
}
};
}
};
LoginResponse::Success(TokenAssignment {
token: session_token,
ttl: death_date.timestamp(),
})
}
pub async fn verify_session(db: &DatabaseConnection, request: AuthRequest) -> AuthResponse {
let uid = match session::get_userid_from_session(db, request.token, true).await {
Ok(u) => u,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
AuthResponse::Failure(AuthError::TokenExpired)
}
FetchSessionError::SessionDoesntExist => {
AuthResponse::Failure(AuthError::TokenInvalid)
}
FetchSessionError::DatabaseError => {
AuthResponse::Failure(AuthError::InternalServer("database error while querying user id".to_string()))
}
};
}
};
AuthResponse::Success(uid)
}
pub async fn logout(db: &DatabaseConnection, request: LogoutRequest) -> LogoutResponse {
match session::delete_session(db, request.token).await {
Ok(_) => LogoutResponse::Success,
Err(e) => match e {
DeleteSessionError::SessionDoesntExist => { LogoutResponse::BadTokenError }
DeleteSessionError::DatabaseError => { LogoutResponse::InternalServerError("database error while deleting session".to_string()) }
}
}
}
pub async fn email_change(db: &DatabaseConnection, request: EmailChangeRequest) -> EmailChangeResponse {
let uid = match session::get_userid_from_session(db, request.token, true).await {
Ok(u) => u,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
EmailChangeResponse::InvalidToken
}
FetchSessionError::SessionDoesntExist => {
EmailChangeResponse::InvalidToken
}
FetchSessionError::DatabaseError => {
EmailChangeResponse::InternalError
}
};
}
};
let verification_code = generate_email_verification_code();
let res = user::start_email_change(db, uid.clone(), request.new_email, verification_code.clone()).await;
if let Err(e) = res {
return match e {
EmailChangeError::UserNotFound => {
EmailChangeResponse::InvalidToken
}
EmailChangeError::NewEmailIsInvalid => {
EmailChangeResponse::InvalidEmail
}
EmailChangeError::DatabaseError => {
EmailChangeResponse::InternalError
}
};
}
debug!("verification code for new email on {} is \"{}\"", {user::user_info(db, uid.clone()).await.map(|v| v.username).unwrap_or(uid.clone())}, verification_code);
EmailChangeResponse::Success
}
pub async fn cancel_email_change(db: &DatabaseConnection, request: CancelEmailChangeRequest) -> CancelEmailChangeResponse {
let uid = match session::get_userid_from_session(db, request.token, true).await {
Ok(u) => u,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
CancelEmailChangeResponse::InvalidToken
}
FetchSessionError::SessionDoesntExist => {
CancelEmailChangeResponse::InvalidToken
}
FetchSessionError::DatabaseError => {
CancelEmailChangeResponse::InternalError
}
};
}
};
if let Err(e) = user::cancel_email_change(db, uid).await {
return match e {
FetchUserError::UserNotFound => {
CancelEmailChangeResponse::InvalidToken
}
FetchUserError::DatabaseError => {
CancelEmailChangeResponse::InternalError
}
};
}
CancelEmailChangeResponse::Success
}

94
src/process/mod.rs Normal file
View file

@ -0,0 +1,94 @@
/*
* authservice process/mod.rs
* - route incoming nats requests to their specific functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
mod basic_accounts;
mod profile;
mod admin;
mod announcements;
use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse};
use sea_orm::DatabaseConnection;
use crate::process::admin::{admin_create_announcement, admin_invite_code_gen, admin_list_all_users, admin_list_invite_codes, admin_update_announcement, stats};
use crate::process::announcements::{announcement_full, announcement_list, latest_announcement};
use crate::process::basic_accounts::{cancel_email_change, email_change, login, logout, register_request, verify_email, verify_session};
use crate::process::profile::{change_theme, user_info};
pub async fn process(query: AuthServiceQuery, db: DatabaseConnection) -> AuthServiceResponse {
// a future is used so that the whole program doesn't die if an algorithm panics
// yes i know that's probably not the best way to do it, i'll fix it eventually
let response = tokio::spawn(async move {
match query.request {
AuthServiceRequest::RegisterRequest(req) => {
AuthServiceResponse::RegisterResponse(register_request(&db, req).await)
}
AuthServiceRequest::VerifyEmailRequest(req) => {
AuthServiceResponse::VerifyEmailResponse(verify_email(&db, req).await)
}
AuthServiceRequest::LoginRequest(req) => {
AuthServiceResponse::LoginResponse(login(&db, req).await)
}
AuthServiceRequest::AuthRequest(req) => {
AuthServiceResponse::AuthResponse(verify_session(&db, req).await)
}
AuthServiceRequest::LogoutRequest(req) => {
AuthServiceResponse::LogoutResponse(logout(&db, req).await)
}
AuthServiceRequest::UserInfoRequest(req) => {
AuthServiceResponse::UserInfoResponse(user_info(&db, req).await)
}
AuthServiceRequest::EmailChangeRequest(req) => {
AuthServiceResponse::EmailChangeResponse(email_change(&db, req).await)
}
AuthServiceRequest::CancelEmailChangeRequest(req) => {
AuthServiceResponse::CancelEmailChangeResponse(cancel_email_change(&db, req).await)
}
AuthServiceRequest::ThemeChangeRequest(req) => {
AuthServiceResponse::ThemeChangeResponse(change_theme(&db, req).await)
}
AuthServiceRequest::StatsRequest(req) => {
AuthServiceResponse::StatsResponse(stats(&db, req).await)
}
AuthServiceRequest::AdminInviteCodeGenerateRequest(req) => {
AuthServiceResponse::AdminInviteCodeGenerateResponse(admin_invite_code_gen(&db, req).await)
}
AuthServiceRequest::LatestAnnouncementRequest(req) => {
AuthServiceResponse::LatestAnnouncementResponse(latest_announcement(&db, req).await)
}
AuthServiceRequest::AnnouncementListRequest(req) => {
AuthServiceResponse::AnnouncementListResponse(announcement_list(&db, req).await)
}
AuthServiceRequest::AnnouncementFullRequest(req) => {
AuthServiceResponse::AnnouncementFullResponse(announcement_full(&db, req).await)
}
AuthServiceRequest::AdminCreateAnnouncementRequest(req) => {
AuthServiceResponse::AdminCreateAnnouncementResponse(admin_create_announcement(&db, req).await)
}
AuthServiceRequest::AdminUpdateAnnouncementRequest(req) => {
AuthServiceResponse::AdminUpdateAnnouncementResponse(admin_update_announcement(&db, req).await)
}
AuthServiceRequest::AdminListInviteCodesRequest(req) => {
AuthServiceResponse::AdminListInviteCodesResponse(admin_list_invite_codes(&db, req).await)
}
AuthServiceRequest::AdminListAllUsersRequest(req) => {
AuthServiceResponse::AdminListAllUsersResponse(admin_list_all_users(&db, req).await)
}
}}).await;
if let Ok(response) = response {
response
} else if let Err(e) = response {
AuthServiceResponse::OtherError(e.to_string())
} else {
unreachable!()
}
}

105
src/process/profile.rs Normal file
View file

@ -0,0 +1,105 @@
/*
* authservice process/profile.rs
* - "customization-related" request functions
*
* Copyright (C) 2025 Real Microsoft, LLC
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use asklyphe_common::nats::authservice::{AuthError, AuthResponse};
use asklyphe_common::nats::authservice::profile::{ThemeChangeRequest, ThemeChangeResponse, UserInfo, UserInfoRequest, UserInfoResponse};
use sea_orm::DatabaseConnection;
use crate::db::{session, user, usersettings};
use crate::db::session::FetchSessionError;
use crate::db::user::FetchUserError;
use crate::db::usersettings::{FetchUserSettingsError, UserSettings};
pub async fn user_info(db: &DatabaseConnection, request: UserInfoRequest) -> UserInfoResponse {
let uid = match session::get_userid_from_session(db, request.token, true).await {
Ok(u) => u,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
UserInfoResponse::TokenExpired
}
FetchSessionError::SessionDoesntExist => {
UserInfoResponse::TokenInvalid
}
FetchSessionError::DatabaseError => {
UserInfoResponse::InternalServerError("database error while querying user id".to_string())
}
};
}
};
let user_info = match user::user_info(db, uid.clone()).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserError::UserNotFound => {
UserInfoResponse::TokenInvalid
}
FetchUserError::DatabaseError => {
UserInfoResponse::InternalServerError("database error while querying user id".to_string())
}
}
};
let user_settings = match usersettings::get_or_create_default_user_settings(db, uid).await {
Ok(u) => u,
Err(e) => return match e {
FetchUserSettingsError::UserNotFound => {
UserInfoResponse::InternalServerError("database error while querying user id".to_string())
}
FetchUserSettingsError::DatabaseError => {
UserInfoResponse::InternalServerError("database error while querying user id".to_string())
}
}
};
UserInfoResponse::Success(UserInfo {
username: user_info.username,
email: user_info.email,
new_email: user_info.new_email,
theme: user_settings.theme,
administrator: user_info.admin,
})
}
pub async fn change_theme(db: &DatabaseConnection, request: ThemeChangeRequest) -> ThemeChangeResponse {
let uid = match session::get_userid_from_session(db, request.token, true).await {
Ok(u) => u,
Err(e) => {
return match e {
FetchSessionError::SessionInvalid => {
ThemeChangeResponse::Logout
}
FetchSessionError::SessionDoesntExist => {
ThemeChangeResponse::Logout
}
FetchSessionError::DatabaseError => {
ThemeChangeResponse::InternalServerError
}
};
}
};
match usersettings::set_theme(db, uid, request.theme).await {
Ok(_) => {
ThemeChangeResponse::Success
}
Err(e) => {
match e {
FetchUserSettingsError::UserNotFound => {
ThemeChangeResponse::Logout
}
FetchUserSettingsError::DatabaseError => {
ThemeChangeResponse::InternalServerError
}
}
}
}
}